file_path
stringlengths
21
202
content
stringlengths
13
1.02M
size
int64
13
1.02M
lang
stringclasses
9 values
avg_line_length
float64
5.43
98.5
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.91
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ARTICULATION_CORE_H #define SC_ARTICULATION_CORE_H #include "ScActorCore.h" #include "DyFeatherstoneArticulation.h" namespace physx { class PxNodeIndex; namespace Sc { class ArticulationSim; class ArticulationCore { //--------------------------------------------------------------------------------- // Construction, destruction & initialization //--------------------------------------------------------------------------------- // PX_SERIALIZATION public: ArticulationCore(const PxEMPTY) : mSim(NULL), mCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationCore(); ~ArticulationCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PX_FORCE_INLINE PxReal getSleepThreshold() const { return mCore.sleepThreshold; } PX_FORCE_INLINE void setSleepThreshold(const PxReal v) { mCore.sleepThreshold = v; } PX_FORCE_INLINE PxReal getFreezeThreshold() const { return mCore.freezeThreshold; } PX_FORCE_INLINE void setFreezeThreshold(const PxReal v) { mCore.freezeThreshold = v; } PX_FORCE_INLINE PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } PX_FORCE_INLINE void setSolverIterationCounts(PxU16 c) { mCore.solverIterationCounts = c; } PX_FORCE_INLINE PxReal getWakeCounter() const { return mCore.wakeCounter; } PX_FORCE_INLINE void setWakeCounterInternal(const PxReal v) { mCore.wakeCounter = v; } void setWakeCounter(const PxReal v); PX_FORCE_INLINE PxReal getMaxLinearVelocity() const { return mCore.maxLinearVelocity; } void setMaxLinearVelocity(const PxReal max); PX_FORCE_INLINE PxReal getMaxAngularVelocity() const { return mCore.maxAngularVelocity; } void setMaxAngularVelocity(const PxReal max); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); //--------------------------------------------------------------------------------- // external reduced coordinate API //--------------------------------------------------------------------------------- void setArticulationFlags(PxArticulationFlags flags); PxArticulationFlags getArticulationFlags() const { return mCore.flags; } PxU32 getDofs() const; PxArticulationCache* createCache() const; PxU32 getCacheDataSize() const; void zeroCache(PxArticulationCache& cache) const; bool applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag)const; void copyInternalStateToCache (PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const; void packJointData(const PxReal* maximum, PxReal* reduced) const; void unpackJointData(const PxReal* reduced, PxReal* maximum) const; void commonInit() const; void computeGeneralizedGravityForce(PxArticulationCache& cache) const; void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const; void computeGeneralizedExternalForce(PxArticulationCache& cache) const; void computeJointAcceleration(PxArticulationCache& cache) const; void computeJointForce(PxArticulationCache& cache) const; void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const; void computeCoefficientMatrix(PxArticulationCache& cache) const; bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter) const; void computeGeneralizedMassMatrix(PxArticulationCache& cache) const; PxU32 getCoefficientMatrixSize() const; PxSpatialVelocity getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const; PxU32 getGpuArticulationIndex() const; void updateKinematic(PxArticulationKinematicFlags flags); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: PX_FORCE_INLINE void setSim(ArticulationSim* sim) { PX_ASSERT((sim==0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ArticulationSim* getSim() const { return mSim; } PX_FORCE_INLINE Dy::ArticulationCore& getCore() { return mCore; } static PX_FORCE_INLINE ArticulationCore& getArticulationCore(ArticulationCore& core) { const size_t offset = PX_OFFSET_OF(ArticulationCore, mCore); return *reinterpret_cast<ArticulationCore*>(reinterpret_cast<PxU8*>(&core) - offset); } PxNodeIndex getIslandNodeIndex() const; void setGlobalPose(); private: ArticulationSim* mSim; Dy::ArticulationCore mCore; }; } // namespace Sc } #endif
6,973
C
41.012048
176
0.637746
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScActorCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ACTOR_CORE_H #define SC_ACTOR_CORE_H #include "common/PxMetaData.h" #include "PxActor.h" namespace physx { namespace Sc { class ActorSim; class ActorCore { public: // PX_SERIALIZATION ActorCore(const PxEMPTY) : mSim(NULL), mActorFlags(PxEmpty) { } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ActorCore(PxActorType::Enum actorType, PxU8 actorFlags, PxClientID owner, PxDominanceGroup dominanceGroup); ~ActorCore(); PX_FORCE_INLINE ActorSim* getSim() const { return mSim; } PX_FORCE_INLINE void setSim(ActorSim* sim) { PX_ASSERT((sim==NULL) ^ (mSim==NULL)); mSim = sim; } PX_FORCE_INLINE PxActorFlags getActorFlags() const { return mActorFlags; } void setActorFlags(PxActorFlags af); PX_FORCE_INLINE PxDominanceGroup getDominanceGroup() const { return PxDominanceGroup(mDominanceGroup); } void setDominanceGroup(PxDominanceGroup g); PX_FORCE_INLINE void setOwnerClient(PxClientID inId) { const PxU32 aggid = mAggregateIDOwnerClient & 0x00ffffff; mAggregateIDOwnerClient = (PxU32(inId)<<24) | aggid; } PX_FORCE_INLINE PxClientID getOwnerClient() const { return mAggregateIDOwnerClient>>24; } PX_FORCE_INLINE PxActorType::Enum getActorCoreType() const { return PxActorType::Enum(mActorType); } void reinsertShapes(); PX_FORCE_INLINE void setAggregateID(PxU32 id) { PX_ASSERT(id==0xffffffff || id<(1<<24)); const PxU32 ownerClient = mAggregateIDOwnerClient & 0xff000000; mAggregateIDOwnerClient = (id & 0x00ffffff) | ownerClient; } PX_FORCE_INLINE PxU32 getAggregateID() const { const PxU32 id = mAggregateIDOwnerClient & 0x00ffffff; return id == 0x00ffffff ? PX_INVALID_U32 : id; } private: ActorSim* mSim; // PxU32 mAggregateIDOwnerClient; // PxClientID (8bit) | aggregate ID (24bit) // PT: TODO: the remaining members could be packed into just a 16bit mask PxActorFlags mActorFlags; // PxActor's flags (PxU8) => only 4 bits used PxU8 mActorType; // Actor type (8 bits, but 3 would be enough) PxU8 mDominanceGroup; // Dominance group (8 bits, but 5 would be enough because "must be < 32") }; #if PX_P64_FAMILY PX_COMPILE_TIME_ASSERT(sizeof(Sc::ActorCore)==16); #else PX_COMPILE_TIME_ASSERT(sizeof(Sc::ActorCore)==12); #endif } // namespace Sc } ////////////////////////////////////////////////////////////////////////// #endif
4,467
C
37.517241
118
0.666443
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScPhysics.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_PHYSICS_H #define SC_PHYSICS_H #include "PxPhysics.h" #include "PxScene.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxBasicTemplates.h" #include "PxActor.h" namespace physx { class PxMaterial; class PxTolerancesScale; struct PxvOffsetTable; #if PX_SUPPORT_GPU_PHYSX class PxPhysXGpu; #endif namespace Sc { class Scene; class StaticCore; class RigidCore; class BodyCore; class ArticulationCore; class ArticulationJointCore; class ConstraintCore; class ShapeCore; struct OffsetTable { PX_FORCE_INLINE OffsetTable() {} PX_FORCE_INLINE PxShape* convertScShape2Px(ShapeCore* sc) const { return PxPointerOffset<PxShape*>(sc, scShape2Px); } PX_FORCE_INLINE const PxShape* convertScShape2Px(const ShapeCore* sc) const { return PxPointerOffset<const PxShape*>(sc, scShape2Px); } PX_FORCE_INLINE PxConstraint* convertScConstraint2Px(ConstraintCore* sc) const { return PxPointerOffset<PxConstraint*>(sc, scConstraint2Px); } PX_FORCE_INLINE const PxConstraint* convertScConstraint2Px(const ConstraintCore* sc) const { return PxPointerOffset<const PxConstraint*>(sc, scConstraint2Px); } PX_FORCE_INLINE PxArticulationReducedCoordinate* convertScArticulation2Px(ArticulationCore* sc) const { return PxPointerOffset<PxArticulationReducedCoordinate*>(sc, scArticulationRC2Px); } PX_FORCE_INLINE const PxArticulationReducedCoordinate* convertScArticulation2Px(const ArticulationCore* sc) const { return PxPointerOffset<const PxArticulationReducedCoordinate*>(sc, scArticulationRC2Px); } PX_FORCE_INLINE PxArticulationJointReducedCoordinate* convertScArticulationJoint2Px(ArticulationJointCore* sc) const { return PxPointerOffset<PxArticulationJointReducedCoordinate*>(sc, scArticulationJointRC2Px); } PX_FORCE_INLINE const PxArticulationJointReducedCoordinate* convertScArticulationJoint2Px(const ArticulationJointCore* sc) const { return PxPointerOffset<const PxArticulationJointReducedCoordinate*>(sc, scArticulationJointRC2Px); } ptrdiff_t scRigidStatic2PxActor; ptrdiff_t scRigidDynamic2PxActor; ptrdiff_t scArticulationLink2PxActor; ptrdiff_t scSoftBody2PxActor; ptrdiff_t scPBDParticleSystem2PxActor; ptrdiff_t scFLIPParticleSystem2PxActor; ptrdiff_t scMPMParticleSystem2PxActor; ptrdiff_t scHairSystem2PxActor; ptrdiff_t scShape2Px; ptrdiff_t scArticulationRC2Px; ptrdiff_t scArticulationJointRC2Px; ptrdiff_t scConstraint2Px; ptrdiff_t scCore2PxActor[PxActorType::eACTOR_COUNT]; }; extern OffsetTable gOffsetTable; class Physics : public PxUserAllocated { public: PX_FORCE_INLINE static Physics& getInstance() { return *mInstance; } Physics(const PxTolerancesScale&, const PxvOffsetTable& pxvOffsetTable); ~Physics(); PX_FORCE_INLINE const PxTolerancesScale& getTolerancesScale() const { return mScale; } private: PxTolerancesScale mScale; static Physics* mInstance; public: static const PxReal sWakeCounterOnCreation; }; } // namespace Sc } #endif
4,800
C
35.930769
167
0.770417
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScRigidCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_RIGID_CORE_H #define SC_RIGID_CORE_H #include "ScActorCore.h" #include "ScPhysics.h" #include "PxvDynamics.h" #include "PxShape.h" namespace physx { namespace Sc { class RigidSim; class ShapeCore; struct ShapeChangeNotifyFlag { enum Enum { eGEOMETRY = 1<<0, eMATERIAL = 1<<1, eSHAPE2BODY = 1<<2, eFILTERDATA = 1<<3, eCONTACTOFFSET = 1<<4, eRESTOFFSET = 1<<5, eRESET_FILTERING = 1<<6 }; }; typedef PxFlags<ShapeChangeNotifyFlag::Enum, PxU32> ShapeChangeNotifyFlags; PX_FLAGS_OPERATORS(ShapeChangeNotifyFlag::Enum,PxU32) class RigidCore : public ActorCore { public: PX_FORCE_INLINE PxActor* getPxActor() const { return PxPointerOffset<PxActor*>(const_cast<RigidCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); } void addShapeToScene(ShapeCore& shape); void removeShapeFromScene(ShapeCore& shape, bool wakeOnLostTouch); void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags); void onShapeFlagsChange(ShapeCore& shape, PxShapeFlags oldShapeFlags); void unregisterShapeFromNphase(ShapeCore& shapeCore); void registerShapeInNphase(ShapeCore& shapeCore); RigidSim* getSim() const; PxU32 getRigidID() const; static void getBinaryMetaData(PxOutputStream& stream); protected: RigidCore(const PxEMPTY) : ActorCore(PxEmpty) {} RigidCore(PxActorType::Enum type); ~RigidCore(); }; } // namespace Sc } #endif
3,198
C
34.153846
121
0.73546
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScSqBoundsSync.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SQ_BOUNDS_SYNC_H #define SC_SQ_BOUNDS_SYNC_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxBitMap.h" #include "PxSceneQuerySystem.h" namespace physx { class PxBounds3; class PxRigidBody; class PxShape; typedef PxSQPrunerHandle ScPrunerHandle; namespace Sc { // PT: TODO: revisit the need for a virtual interface struct SqRefFinder { virtual ScPrunerHandle find(const PxRigidBody* body, const PxShape* shape, PxU32& prunerIndex) = 0; virtual ~SqRefFinder() {} }; // PT: TODO: revisit the need for a virtual interface struct SqBoundsSync { virtual void sync(PxU32 prunerIndex, const ScPrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0; virtual ~SqBoundsSync() {} }; } } #endif
2,536
C
37.439393
205
0.76183
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScShapeCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SHAPE_CORE_H #define SC_SHAPE_CORE_H #include "foundation/PxUtilities.h" #include "PxvGeometry.h" #include "PxFiltering.h" #include "PxShape.h" namespace physx { class PxShape; class PxsSimulationController; namespace Sc { class ShapeSim; class ShapeCore { public: // PX_SERIALIZATION ShapeCore(const PxEMPTY); void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void resolveMaterialReference(PxU32 materialTableIndex, PxU16 materialIndex); //~PX_SERIALIZATION ShapeCore(const PxGeometry& geometry, PxShapeFlags shapeFlags, const PxU16* materialIndices, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum softOrClothFlags = PxShapeCoreFlag::Enum(0)); ~ShapeCore(); PX_FORCE_INLINE PxGeometryType::Enum getGeometryType() const { return mCore.mGeometry.getType(); } PxShape* getPxShape(); const PxShape* getPxShape() const; PX_FORCE_INLINE const GeometryUnion& getGeometryUnion() const { return mCore.mGeometry; } PX_FORCE_INLINE const PxGeometry& getGeometry() const { return mCore.mGeometry.getGeometry(); } void setGeometry(const PxGeometry& geom); PxU16 getNbMaterialIndices() const; const PxU16* getMaterialIndices() const; void setMaterialIndices(const PxU16* materialIndices, PxU16 materialIndexCount); PX_FORCE_INLINE const PxTransform& getShape2Actor() const { return mCore.getTransform(); } PX_FORCE_INLINE void setShape2Actor(const PxTransform& s2b) { mCore.setTransform(s2b); } PX_FORCE_INLINE const PxFilterData& getSimulationFilterData() const { return mSimulationFilterData; } PX_FORCE_INLINE void setSimulationFilterData(const PxFilterData& data) { mSimulationFilterData = data; } PX_FORCE_INLINE PxReal getContactOffset() const { return mCore.mContactOffset; } void setContactOffset(PxReal offset); PX_FORCE_INLINE PxReal getRestOffset() const { return mCore.mRestOffset; } PX_FORCE_INLINE void setRestOffset(PxReal offset) { mCore.mRestOffset = offset; } PX_FORCE_INLINE PxReal getDensityForFluid() const { return mCore.getDensityForFluid(); } PX_FORCE_INLINE void setDensityForFluid(PxReal densityForFluid) { mCore.setDensityForFluid(densityForFluid); } PX_FORCE_INLINE PxReal getTorsionalPatchRadius() const { return mCore.mTorsionalRadius; } PX_FORCE_INLINE void setTorsionalPatchRadius(PxReal tpr) { mCore.mTorsionalRadius = tpr; } PX_FORCE_INLINE PxReal getMinTorsionalPatchRadius() const {return mCore.mMinTorsionalPatchRadius; } PX_FORCE_INLINE void setMinTorsionalPatchRadius(PxReal radius) { mCore.mMinTorsionalPatchRadius = radius; } PX_FORCE_INLINE PxShapeFlags getFlags() const { return PxShapeFlags(mCore.mShapeFlags); } PX_FORCE_INLINE void setFlags(PxShapeFlags f) { mCore.mShapeFlags = f; } PX_FORCE_INLINE const PxsShapeCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF(ShapeCore, mCore); } static PX_FORCE_INLINE ShapeCore& getCore(PxsShapeCore& core) { return *reinterpret_cast<ShapeCore*>(reinterpret_cast<PxU8*>(&core) - getCoreOffset()); } PX_FORCE_INLINE ShapeSim* getExclusiveSim() const { return mExclusiveSim; } PX_FORCE_INLINE void setExclusiveSim(ShapeSim* sim) { if (!sim || mCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eIS_EXCLUSIVE)) { mExclusiveSim = sim; } } PxU32 getInternalShapeIndex(PxsSimulationController& simulationController) const; #if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux protected: #endif PxFilterData mSimulationFilterData; // Simulation filter data PxsShapeCore PX_ALIGN(16, mCore); ShapeSim* mExclusiveSim; //only set if shape is exclusive #if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux public: #endif const char* mName; // PT: moved here from NpShape to fill padding bytes }; } // namespace Sc } #endif
6,269
C
43.785714
119
0.707609
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationJointCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ARTICULATION_JOINT_CORE_H #define SC_ARTICULATION_JOINT_CORE_H #include "foundation/PxTransform.h" #include "common/PxMetaData.h" #include "DyVArticulation.h" namespace physx { namespace Sc { class BodyCore; class ArticulationJointSim; class ArticulationCore; class ArticulationJointDesc { public: BodyCore* parent; BodyCore* child; PxTransform parentPose; PxTransform childPose; }; class ArticulationJointCore { public: // PX_SERIALIZATION ArticulationJointCore(const PxEMPTY) : mCore(PxEmpty), mSim(NULL) {} void preExportDataReset() { mCore.jointDirtyFlag = Dy::ArticulationJointCoreDirtyFlag::eALL; } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationJointCore(const PxTransform& parentFrame, const PxTransform& childFrame); ~ArticulationJointCore(); //Those methods are not allowed while the articulation are in the scene PX_FORCE_INLINE const PxTransform& getParentPose() const { return mCore.parentPose; } void setParentPose(const PxTransform&); PX_FORCE_INLINE const PxTransform& getChildPose() const { return mCore.childPose; } void setChildPose(const PxTransform&); //Those functions doesn't change the articulation configuration so the application is allowed to change those value in run-time PX_FORCE_INLINE PxArticulationLimit getLimit(PxArticulationAxis::Enum axis) const { return mCore.limits[axis]; } void setLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit); PX_FORCE_INLINE PxArticulationDrive getDrive(PxArticulationAxis::Enum axis) const { return mCore.drives[axis]; } void setDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive); void setTargetP(PxArticulationAxis::Enum axis, PxReal targetP); PX_FORCE_INLINE PxReal getTargetP(PxArticulationAxis::Enum axis) const { return mCore.targetP[axis]; } void setTargetV(PxArticulationAxis::Enum axis, PxReal targetV); PX_FORCE_INLINE PxReal getTargetV(PxArticulationAxis::Enum axis) const { return mCore.targetV[axis]; } void setArmature(PxArticulationAxis::Enum axis, PxReal armature); PX_FORCE_INLINE PxReal getArmature(PxArticulationAxis::Enum axis) const { return mCore.armature[axis]; } void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos); PxReal getJointPosition(PxArticulationAxis::Enum axis) const; void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel); PxReal getJointVelocity(PxArticulationAxis::Enum axis) const; // PT: TODO: don't we need to set ArticulationJointCoreDirtyFlag::eMOTION here? PX_FORCE_INLINE void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { mCore.motion[axis] = PxU8(motion); } PX_FORCE_INLINE PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const { return PxArticulationMotion::Enum(mCore.motion[axis]); } PX_FORCE_INLINE void setJointType(PxArticulationJointType::Enum type) { mCore.initJointType(type); } PX_FORCE_INLINE PxArticulationJointType::Enum getJointType() const { return PxArticulationJointType::Enum(mCore.jointType); } PX_FORCE_INLINE void setFrictionCoefficient(const PxReal coefficient) { mCore.initFrictionCoefficient(coefficient); } PX_FORCE_INLINE PxReal getFrictionCoefficient() const { return mCore.frictionCoefficient; } PX_FORCE_INLINE void setMaxJointVelocity(const PxReal maxJointV) { mCore.initMaxJointVelocity(maxJointV); } PX_FORCE_INLINE PxReal getMaxJointVelocity() const { return mCore.maxJointVelocity; } PX_FORCE_INLINE ArticulationJointSim* getSim() const { return mSim; } PX_FORCE_INLINE void setSim(ArticulationJointSim* sim) { PX_ASSERT((sim==0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE Dy::ArticulationJointCore& getCore() { return mCore; } PX_FORCE_INLINE void setArticulation(ArticulationCore* articulation) { mArticulation = articulation; } PX_FORCE_INLINE const ArticulationCore* getArticulation() const { return mArticulation; } PX_FORCE_INLINE void setRoot(PxArticulationJointReducedCoordinate* base) { mRootType = base; } PX_FORCE_INLINE PxArticulationJointReducedCoordinate* getRoot() const { return mRootType; } PX_FORCE_INLINE void setLLIndex(const PxU32 llLinkIndex) { mLLLinkIndex = llLinkIndex; } private: void setSimDirty(); PX_FORCE_INLINE void setDirty(Dy::ArticulationJointCoreDirtyFlag::Enum dirtyFlag) { mCore.jointDirtyFlag |= dirtyFlag; setSimDirty(); } Dy::ArticulationJointCore mCore; ArticulationJointSim* mSim; ArticulationCore* mArticulation; PxArticulationJointReducedCoordinate* mRootType; PxU32 mLLLinkIndex; #if PX_P64_FAMILY PxU32 pad; #endif }; } // namespace Sc } #endif
6,991
C
47.220689
158
0.710914
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScStaticCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_STATIC_CORE_H #define SC_STATIC_CORE_H #include "ScRigidCore.h" #include "PxvDynamics.h" namespace physx { namespace Sc { class StaticSim; class StaticCore : public RigidCore { public: StaticCore(const PxTransform& actor2World): RigidCore(PxActorType::eRIGID_STATIC) { mCore.body2World = actor2World; mCore.mFlags = PxRigidBodyFlags(); } PX_FORCE_INLINE const PxTransform& getActor2World() const { return mCore.body2World; } void setActor2World(const PxTransform& actor2World); PX_FORCE_INLINE PxsRigidCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(StaticCore, mCore);} StaticCore(const PxEMPTY) : RigidCore(PxEmpty), mCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); StaticSim* getSim() const; PX_FORCE_INLINE void onOriginShift(const PxVec3& shift) { mCore.body2World.p -= shift; } private: PxsRigidCore mCore; }; } // namespace Sc } #endif
2,784
C
37.680555
96
0.727371
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScBodyCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_BODY_CORE_H #define SC_BODY_CORE_H #include "foundation/PxTransform.h" #include "ScRigidCore.h" #include "PxRigidDynamic.h" #include "PxvDynamics.h" #include "PxvConfig.h" namespace physx { namespace Sc { class BodySim; class BodyCore : public RigidCore { public: // PX_SERIALIZATION BodyCore(const PxEMPTY) : RigidCore(PxEmpty), mCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); void restoreDynamicData(); //~PX_SERIALIZATION BodyCore(PxActorType::Enum type, const PxTransform& bodyPose); ~BodyCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PX_FORCE_INLINE const PxTransform& getBody2World() const { return mCore.body2World; } void setBody2World(const PxTransform& p); void setCMassLocalPose(const PxTransform& body2Actor); PX_FORCE_INLINE const PxVec3& getLinearVelocity() const { return mCore.linearVelocity; } void setLinearVelocity(const PxVec3& v, bool skipBodySimUpdate=false); PX_FORCE_INLINE const PxVec3& getAngularVelocity() const { return mCore.angularVelocity; } void setAngularVelocity(const PxVec3& v, bool skipBodySimUpdate=false); PX_FORCE_INLINE PxReal getCfmScale() const { return mCore.cfmScale; } void setCfmScale(PxReal d); PX_FORCE_INLINE void updateVelocities(const PxVec3& linearVelModPerStep, const PxVec3& angularVelModPerStep) { mCore.linearVelocity += linearVelModPerStep; mCore.angularVelocity += angularVelModPerStep; } PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return mCore.getBody2Actor(); } void setBody2Actor(const PxTransform& p); void addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc); void setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc); void clearSpatialAcceleration(bool force, bool torque); void addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta); void clearSpatialVelocity(bool force, bool torque); PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; } PX_FORCE_INLINE void setMaxPenetrationBias(PxReal p) { mCore.maxPenBias = p; } PxReal getInverseMass() const; void setInverseMass(PxReal m); const PxVec3& getInverseInertia() const; void setInverseInertia(const PxVec3& i); PxReal getLinearDamping() const; void setLinearDamping(PxReal d); PxReal getAngularDamping() const; void setAngularDamping(PxReal d); PX_FORCE_INLINE PxRigidBodyFlags getFlags() const { return mCore.mFlags; } void setFlags(PxRigidBodyFlags f); PX_FORCE_INLINE PxRigidDynamicLockFlags getRigidDynamicLockFlags() const { return mCore.lockFlags; } PX_FORCE_INLINE void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) { mCore.lockFlags = flags; } PX_FORCE_INLINE PxReal getSleepThreshold() const { return mCore.sleepThreshold; } void setSleepThreshold(PxReal t); PX_FORCE_INLINE PxReal getFreezeThreshold() const { return mCore.freezeThreshold; } void setFreezeThreshold(PxReal t); PX_FORCE_INLINE PxReal getMaxContactImpulse() const { return mCore.maxContactImpulse; } void setMaxContactImpulse(PxReal m); PX_FORCE_INLINE PxReal getOffsetSlop() const { return mCore.offsetSlop; } void setOffsetSlop(PxReal slop); PxNodeIndex getInternalIslandNodeIndex() const; PX_FORCE_INLINE PxReal getWakeCounter() const { return mCore.wakeCounter; } void setWakeCounter(PxReal wakeCounter, bool forceWakeUp=false); bool isSleeping() const; PX_FORCE_INLINE void wakeUp(PxReal wakeCounter) { setWakeCounter(wakeCounter, true); } void putToSleep(); PxReal getMaxAngVelSq() const; void setMaxAngVelSq(PxReal v); PxReal getMaxLinVelSq() const; void setMaxLinVelSq(PxReal v); PX_FORCE_INLINE PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } void setSolverIterationCounts(PxU16 c); bool getKinematicTarget(PxTransform& p) const; bool getHasValidKinematicTarget() const; void setKinematicTarget(const PxTransform& p, PxReal wakeCounter); void invalidateKinematicTarget(); PX_FORCE_INLINE PxReal getContactReportThreshold() const { return mCore.contactReportThreshold; } void setContactReportThreshold(PxReal t) { mCore.contactReportThreshold = t; } void onOriginShift(const PxVec3& shift); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- PX_FORCE_INLINE void setLinearVelocityInternal(const PxVec3& v) { mCore.linearVelocity = v; } PX_FORCE_INLINE void setAngularVelocityInternal(const PxVec3& v) { mCore.angularVelocity = v; } PX_FORCE_INLINE void setWakeCounterFromSim(PxReal c) { mCore.wakeCounter = c; } BodySim* getSim() const; PX_FORCE_INLINE PxsBodyCore& getCore() { return mCore; } PX_FORCE_INLINE const PxsBodyCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(BodyCore, mCore); } PX_FORCE_INLINE PxReal getCCDAdvanceCoefficient() const { return mCore.ccdAdvanceCoefficient; } PX_FORCE_INLINE void setCCDAdvanceCoefficient(PxReal c) { mCore.ccdAdvanceCoefficient = c; } void onRemoveKinematicFromScene(); PxIntBool isFrozen() const; static PX_FORCE_INLINE BodyCore& getCore(PxsBodyCore& core) { return *reinterpret_cast<BodyCore*>(reinterpret_cast<PxU8*>(&core) - getCoreOffset()); } void setFixedBaseLink(bool value); private: PX_ALIGN_PREFIX(16) PxsBodyCore mCore PX_ALIGN_SUFFIX(16); }; } // namespace Sc } #endif
7,887
C
41.637838
113
0.684037
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScSoftBodyCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SOFT_BODY_CORE_H #define SC_SOFT_BODY_CORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxSoftBody.h" #include "DySoftBodyCore.h" #include "foundation/PxAssert.h" #include "ScActorCore.h" #include "ScShapeCore.h" #include "PxFiltering.h" #include "ScRigidCore.h" //KS - needed for ShapeChangeNotifyFlags. Move to a shared header namespace physx { namespace Sc { class SoftBodySim; class BodyCore; class FEMClothCore; class ParticleSystemCore; class SoftBodyCore : public ActorCore { // PX_SERIALIZATION public: SoftBodyCore(const PxEMPTY) : ActorCore(PxEmpty){} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION SoftBodyCore(); ~SoftBodyCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- void setMaterial(const PxU16 handle); void clearMaterials(); PxFEMParameters getParameter() const; void setParameter(const PxFEMParameters paramters); PxReal getSleepThreshold() const; void setSleepThreshold(const PxReal v); PxReal getFreezeThreshold() const; void setFreezeThreshold(const PxReal v); PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxReal getWakeCounter() const; void setWakeCounter(const PxReal v); void setWakeCounterInternal(const PxReal v); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); PxActor* getPxActor() const; void attachShapeCore(ShapeCore* shapeCore); void attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState); void addParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId); void removeParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId); PxU32 addParticleAttachment(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric); void removeParticleAttachment(Sc::ParticleSystemCore* core, PxU32 handle); void addRigidFilter(Sc::BodyCore* core, PxU32 vertId); void removeRigidFilter(Sc::BodyCore* core, PxU32 vertId); PxU32 addRigidAttachment(Sc::BodyCore* core, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeRigidAttachment(Sc::BodyCore* core, PxU32 handle); void addTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx); void removeTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx); PxU32 addTetRigidAttachment(Sc::BodyCore* core, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void addSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1); void removeSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1); void addSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); void removeSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); PxU32 addSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset); void removeSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 handle); void addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx); void removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx); void addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx); void removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx); PxU32 addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset); void removeClothAttachment(Sc::FEMClothCore& core, PxU32 handle); PxU32 getGpuSoftBodyIndex() const; void setKinematicTargets(const PxVec4* positions, PxSoftBodyFlags flags); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: SoftBodySim* getSim() const; PX_FORCE_INLINE const Dy::SoftBodyCore& getCore() const { return mCore; } PX_FORCE_INLINE Dy::SoftBodyCore& getCore() { return mCore; } void setSimulationFilterData(const PxFilterData& data); PxFilterData getSimulationFilterData() const; PxSoftBodyFlags getFlags() const { return mCore.mFlags; } void setFlags(PxSoftBodyFlags flags); PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; } PX_FORCE_INLINE void setMaxPenetrationBias(PxReal p) { mCore.maxPenBias = p; } PX_FORCE_INLINE PxU64& getGpuMemStat() { return mGpuMemStat; } void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags); private: Dy::SoftBodyCore mCore; PxFilterData mFilterData; PxU64 mGpuMemStat; }; } // namespace Sc } #endif #endif
7,290
C
41.389535
151
0.697257
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScIterators.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ITERATORS_H #define SC_ITERATORS_H #include "foundation/PxVec3.h" #include "PxContact.h" namespace physx { class PxShape; class PxsContactManagerOutputIterator; namespace Sc { class ShapeSimBase; class ElementSimInteraction; class ActorSim; struct Contact { Contact() : normal(0.0f) , point(0.0f) , separation(0.0f) , normalForce(0.0f) {} PxVec3 normal; PxVec3 point; PxShape* shape0; PxShape* shape1; PxReal separation; PxReal normalForce; PxU32 faceIndex0; // these are the external indices PxU32 faceIndex1; bool normalForceAvailable; }; class ContactIterator { public: class Pair { public: Pair() : mIter(NULL, NULL, NULL, 0, 0) {} Pair(const void*& contactPatches, const void*& contactPoints, const PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches, ShapeSimBase& shape0, ShapeSimBase& shape1, ActorSim* actor0, ActorSim* actor1); Contact* getNextContact(); PxActor* getActor0() { return mActor0; } PxActor* getActor1() { return mActor1; } private: PxU32 mIndex; PxU32 mNumContacts; PxContactStreamIterator mIter; const PxReal* mForces; Contact mCurrentContact; PxActor* mActor0; PxActor* mActor1; }; ContactIterator() {} explicit ContactIterator(ElementSimInteraction** first, ElementSimInteraction** last, PxsContactManagerOutputIterator& outputs): mCurrent(first), mLast(last), mOffset(0), mOutputs(&outputs) { if ((!first) || (!last) || (first == last)) { mCurrent = NULL; mLast = NULL; } } Pair* getNextPair(); private: ElementSimInteraction** mCurrent; ElementSimInteraction** mLast; Pair mCurrentPair; PxU32 mOffset; PxsContactManagerOutputIterator* mOutputs; private: }; } // namespace Sc } #endif
3,590
C
30.5
239
0.716713
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScParticleSystemCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_PARTICLESYSTEM_CORE_H #define SC_PARTICLESYSTEM_CORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxParticleSystem.h" #include "foundation/PxAssert.h" #include "ScActorCore.h" #include "ScShapeCore.h" #include "PxFiltering.h" #include "DyParticleSystem.h" #include "ScParticleSystemShapeCore.h" namespace physx { namespace Sc { class ParticleSystemSim; class BodyCore; class ParticleSystemCore : public ActorCore { // PX_SERIALIZATION public: ParticleSystemCore(const PxEMPTY) : ActorCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ParticleSystemCore(PxActorType::Enum actorType); ~ParticleSystemCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PxReal getSleepThreshold() const; void setSleepThreshold(const PxReal v); PxReal getRestOffset() const; void setRestOffset(const PxReal v); PxReal getContactOffset() const; void setContactOffset(const PxReal v); PxReal getParticleContactOffset() const; void setParticleContactOffset(const PxReal v); PxReal getSolidRestOffset() const; void setSolidRestOffset(const PxReal v); PxReal getFluidRestOffset() const; void setFluidRestOffset(const PxReal v); PxReal getMaxDepenetrationVelocity() const; void setMaxDepenetrationVelocity(const PxReal v); PxReal getMaxVelocity() const; void setMaxVelocity(const PxReal v); PxParticleSystemCallback* getParticleSystemCallback() const; void setParticleSystemCallback(PxParticleSystemCallback* callback); PxReal getFluidBoundaryDensityScale() const; void setFluidBoundaryDensityScale(const PxReal v); PxU32 getGridSizeX() const; void setGridSizeX(const PxU32 v); PxU32 getGridSizeY() const; void setGridSizeY(const PxU32 v); PxU32 getGridSizeZ() const; void setGridSizeZ(const PxU32 v); PxU16 getSolverIterationCounts() const { return mShapeCore.getLLCore().solverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxReal getWakeCounter() const; void setWakeCounter(const PxReal v); void setWakeCounterInternal(const PxReal v); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); PxActor* getPxActor() const; // TOFIX void enableCCD(const bool enable); PxParticleFlags getFlags() const { return mShapeCore.getLLCore().mFlags; } //void setFlags(PxParticleFlags flags) { mShapeCore.getLLCore().mFlags = flags; } void setFlags(PxParticleFlags flags); void setWind(const PxVec3& wind) {mShapeCore.getLLCore().mWind = wind;} PxVec3 getWind() const { return mShapeCore.getLLCore().mWind; } void setSolverType(const PxParticleSolverType::Enum solverType) { mShapeCore.getLLCore().solverType = solverType; } PxParticleSolverType::Enum getSolverType() const { return mShapeCore.getLLCore().solverType; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxSparseGridParams getSparseGridParams() const { return mShapeCore.getLLCore().sparseGridParams; } void setSparseGridParams(const PxSparseGridParams& params) { mShapeCore.getLLCore().sparseGridParams = params; } PxFLIPParams getFLIPParams() const { return mShapeCore.getLLCore().flipParams; } void setFLIPParams(const PxFLIPParams& params) { mShapeCore.getLLCore().flipParams = params; } PxMPMParams getMPMParams() const { return mShapeCore.getLLCore().mpmParams; } void setMPMParams(const PxMPMParams& params) { mShapeCore.getLLCore().mpmParams = params; } #endif void addRigidAttachment(Sc::BodyCore* core); void removeRigidAttachment(Sc::BodyCore* core); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: ParticleSystemSim* getSim() const; PX_FORCE_INLINE const ParticleSystemShapeCore& getShapeCore() const { return mShapeCore; } PX_FORCE_INLINE ParticleSystemShapeCore& getShapeCore() { return mShapeCore; } void setDirty(const bool dirty); private: //ParticleSystemSim* mSim; ParticleSystemShapeCore mShapeCore; }; } // namespace Sc } #endif #endif
6,305
C
36.987952
123
0.686439
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScConstraintCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_CONSTRAINT_CORE_H #define SC_CONSTRAINT_CORE_H #include "PxConstraint.h" namespace physx { namespace Sc { class ConstraintSim; class RigidCore; class ConstraintCore { public: // PX_SERIALIZATION ConstraintCore(const PxEMPTY) : mFlags(PxEmpty), mConnector(NULL), mSim(NULL) {} PX_FORCE_INLINE void setConstraintFunctions(PxConstraintConnector& n, const PxConstraintShaderTable& shaders) { mConnector = &n; mSolverPrep = shaders.solverPrep; mVisualize = shaders.visualize; } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ConstraintCore(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize); ~ConstraintCore() {} void setBodies(RigidCore* r0v, RigidCore* r1v); PxConstraint* getPxConstraint(); const PxConstraint* getPxConstraint() const; PX_FORCE_INLINE PxConstraintConnector* getPxConnector() const { return mConnector; } PX_FORCE_INLINE PxConstraintFlags getFlags() const { return mFlags; } void setFlags(PxConstraintFlags flags); void getForce(PxVec3& force, PxVec3& torque) const; void setBreakForce(PxReal linear, PxReal angular); PX_FORCE_INLINE void getBreakForce(PxReal& linear, PxReal& angular) const { linear = mLinearBreakForce; angular = mAngularBreakForce; } void setMinResponseThreshold(PxReal threshold); PX_FORCE_INLINE PxReal getMinResponseThreshold() const { return mMinResponseThreshold; } void breakApart(); PX_FORCE_INLINE PxConstraintVisualize getVisualize() const { return mVisualize; } PX_FORCE_INLINE PxConstraintSolverPrep getSolverPrep() const { return mSolverPrep; } PX_FORCE_INLINE PxU32 getConstantBlockSize() const { return mDataSize; } PX_FORCE_INLINE void setSim(ConstraintSim* sim) { PX_ASSERT((sim==0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ConstraintSim* getSim() const { return mSim; } PX_FORCE_INLINE bool isDirty() const { return mIsDirty ? true : false; } PX_FORCE_INLINE void setDirty() { mIsDirty = 1; } PX_FORCE_INLINE void clearDirty() { mIsDirty = 0; } private: PxConstraintFlags mFlags; //In order to support O(1) insert/remove mIsDirty really wants to be an index into NpScene's dirty joint array PxU8 mIsDirty; PxU8 mPadding; PxVec3 mAppliedForce; PxVec3 mAppliedTorque; PxConstraintConnector* mConnector; PxConstraintSolverPrep mSolverPrep; PxConstraintVisualize mVisualize; PxU32 mDataSize; PxReal mLinearBreakForce; PxReal mAngularBreakForce; PxReal mMinResponseThreshold; ConstraintSim* mSim; }; } // namespace Sc } #endif
4,717
C
38.316666
116
0.690269
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScHairSystemCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SC_HAIR_SYSTEM_CORE_H #define SC_HAIR_SYSTEM_CORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScActorCore.h" #include "ScHairSystemShapeCore.h" #include "DyHairSystem.h" namespace physx { namespace Sc { class HairSystemSim; class BodySim; class SoftBodySim; class HairSystemCore : public ActorCore { // PX_SERIALIZATION public: HairSystemCore(const PxEMPTY) : ActorCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION HairSystemCore(); ~HairSystemCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- void setMaterial(const PxU16 handle); void clearMaterials(); PxReal getContactOffset() const; void setContactOffset(PxReal v); PxReal getSleepThreshold() const { return mShapeCore.getLLCore().mSleepThreshold; } void setSleepThreshold(const PxReal v); PxU16 getSolverIterationCounts() const { return mShapeCore.getLLCore().mSolverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxReal getWakeCounter() const { return mShapeCore.getLLCore().mWakeCounter; } void setWakeCounter(const PxReal v); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); PxActor* getPxActor() const; void addAttachment(const BodySim& bodySim); void removeAttachment(const BodySim& bodySim); void addAttachment(const SoftBodySim& sbSim); void removeAttachment(const SoftBodySim& sbSim); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: HairSystemSim* getSim() const; PX_FORCE_INLINE const HairSystemShapeCore& getShapeCore() const { return mShapeCore; } PX_FORCE_INLINE HairSystemShapeCore& getShapeCore() { return mShapeCore; } PxHairSystemFlags getFlags() const { return PxHairSystemFlags(mShapeCore.getLLCore().mParams.mFlags); } void setFlags(PxHairSystemFlags flags); private: HairSystemShapeCore mShapeCore; }; } // namespace Sc } // namespace physx #endif #endif
3,762
C
34.838095
104
0.702818
NVIDIA-Omniverse/PhysX/physx/source/fastxml/src/PsFastXml.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxAssert.h" #include "foundation/PxMemory.h" #include "foundation/PxFoundationConfig.h" #include "foundation/PxAllocator.h" #include "PsFastXml.h" #include <stdio.h> #include <string.h> #include <new> #include <ctype.h> using namespace physx; namespace { #define MIN_CLOSE_COUNT 2 #define DEFAULT_READ_BUFFER_SIZE (16 * 1024) #define NUM_ENTITY 5 struct Entity { const char* str; unsigned int strLength; char chr; }; static const Entity entity[NUM_ENTITY] = { { "&lt;", 4, '<' }, { "&amp;", 5, '&' }, { "&gt;", 4, '>' }, { "&quot;", 6, '\"' }, { "&apos;", 6, '\'' } }; class MyFastXml : public physx::shdfnd::FastXml { public: enum CharType { CT_DATA, CT_EOF, CT_SOFT, CT_END_OF_ELEMENT, // either a forward slash or a greater than symbol CT_END_OF_LINE }; MyFastXml(Callback* c) { mStreamFromMemory = true; mCallback = c; memset(mTypes, CT_DATA, sizeof(mTypes)); mTypes[0] = CT_EOF; mTypes[uint8_t(' ')] = mTypes[uint8_t('\t')] = CT_SOFT; mTypes[uint8_t('/')] = mTypes[uint8_t('>')] = mTypes[uint8_t('?')] = CT_END_OF_ELEMENT; mTypes[uint8_t('\n')] = mTypes[uint8_t('\r')] = CT_END_OF_LINE; mError = 0; mStackIndex = 0; mFileBuf = NULL; mReadBufferEnd = NULL; mReadBuffer = NULL; mReadBufferSize = DEFAULT_READ_BUFFER_SIZE; mOpenCount = 0; mLastReadLoc = 0; for(uint32_t i = 0; i < (MAX_STACK + 1); i++) { mStack[i] = NULL; mStackAllocated[i] = false; } } char* processClose(char c, const char* element, char* scan, int32_t argc, const char** argv, FastXml::Callback* iface, bool& isError) { AttributePairs attr(argc, argv); if(c == '/' || c == '?') { char* slash = const_cast<char*>(static_cast<const char*>(strchr(element, c))); if(slash) *slash = 0; if(c == '?' && strcmp(element, "xml") == 0) { isError = true; if(!iface->processXmlDeclaration(attr, 0, mLineNo)) return NULL; } else { if(!iface->processElement(element, 0, attr, mLineNo)) { isError = true; mError = "User aborted the parsing process"; return NULL; } pushElement(element); const char* close = popElement(); if(!iface->processClose(close, mStackIndex, isError)) { return NULL; } } if(!slash) ++scan; } else { scan = skipNextData(scan); char* data = scan; // this is the data portion of the element, only copies memory if we encounter line feeds char* dest_data = 0; while(*scan && *scan != '<') { if(getCharType(scan) == CT_END_OF_LINE) { if(*scan == '\r') mLineNo++; dest_data = scan; *dest_data++ = ' '; // replace the linefeed with a space... scan = skipNextData(scan); while(*scan && *scan != '<') { if(getCharType(scan) == CT_END_OF_LINE) { if(*scan == '\r') mLineNo++; *dest_data++ = ' '; // replace the linefeed with a space... scan = skipNextData(scan); } else { *dest_data++ = *scan++; } } break; } else if('&' == *scan) { dest_data = scan; while(*scan && *scan != '<') { if('&' == *scan) { if(*(scan + 1) && *(scan + 1) == '#' && *(scan + 2)) { if(*(scan + 2) == 'x') { // Hexadecimal. if(!*(scan + 3)) break; char* q = scan + 3; q = strchr(q, ';'); if(!q || !*q) PX_ASSERT(0); --q; char ch = char(*q > '9' ? (tolower(*q) - 'a' + 10) : *q - '0'); if(*(--q) != tolower('x')) ch |= char(*q > '9' ? (tolower(*q) - 'a' + 10) : *q - '0') << 4; *dest_data++ = ch; } else { // Decimal. if(!*(scan + 2)) break; const char* q = scan + 2; q = strchr(q, ';'); if(!q || !*q) PX_ASSERT(0); --q; char ch = *q - '0'; if(*(--q) != '#') ch |= (*q - '0') * 10; *dest_data++ = ch; } char* start = scan; char* end = strchr(start, ';'); if(end) { *end = 0; scan = end + 1; } continue; } for(int i = 0; i < NUM_ENTITY; ++i) { if(strncmp(entity[i].str, scan, entity[i].strLength) == 0) { *dest_data++ = entity[i].chr; scan += entity[i].strLength; break; } } } else { *dest_data++ = *scan++; } } break; } else ++scan; } if(*scan == '<') { if(scan[1] != '/') { PX_ASSERT(mOpenCount > 0); mOpenCount--; } if(dest_data) { *dest_data = 0; } else { *scan = 0; } scan++; // skip it.. if(*data == 0) data = 0; if(!iface->processElement(element, data, attr, mLineNo)) { isError = true; mError = "User aborted the parsing process"; return NULL; } pushElement(element); // check for the comment use case... if(scan[0] == '!' && scan[1] == '-' && scan[2] == '-') { scan += 3; while(*scan && *scan == ' ') ++scan; char* comment = scan; char* comment_end = strstr(scan, "-->"); if(comment_end) { *comment_end = 0; scan = comment_end + 3; if(!iface->processComment(comment)) { isError = true; mError = "User aborted the parsing process"; return NULL; } } } else if(*scan == '/') { scan = processClose(scan, iface, isError); if(scan == NULL) { return NULL; } } } else { isError = true; mError = "Data portion of an element wasn't terminated properly"; return NULL; } } if(mOpenCount < MIN_CLOSE_COUNT) { scan = readData(scan); } return scan; } char* processClose(char* scan, FastXml::Callback* iface, bool& isError) { const char* start = popElement(), *close = start; if(scan[1] != '>') { scan++; close = scan; while(*scan && *scan != '>') scan++; *scan = 0; } if(0 != strcmp(start, close)) { isError = true; mError = "Open and closing tags do not match"; return 0; } if(!iface->processClose(close, mStackIndex, isError)) { // we need to set the read pointer! uint32_t offset = uint32_t(mReadBufferEnd - scan) - 1; uint32_t readLoc = mLastReadLoc - offset; mFileBuf->seek(readLoc); return NULL; } ++scan; return scan; } virtual bool processXml(physx::PxInputData& fileBuf, bool streamFromMemory) { releaseMemory(); mFileBuf = &fileBuf; mStreamFromMemory = streamFromMemory; return processXml(mCallback); } // if we have finished processing the data we had pending.. char* readData(char* scan) { for(uint32_t i = 0; i < (mStackIndex + 1); i++) { if(!mStackAllocated[i]) { const char* text = mStack[i]; if(text) { uint32_t tlen = uint32_t(strlen(text)); mStack[i] = static_cast<const char*>(mCallback->allocate(tlen + 1)); PxMemCopy(const_cast<void*>(static_cast<const void*>(mStack[i])), text, tlen + 1); mStackAllocated[i] = true; } } } if(!mStreamFromMemory) { if(scan == NULL) { uint32_t seekLoc = mFileBuf->tell(); mReadBufferSize = (mFileBuf->getLength() - seekLoc); } else { return scan; } } if(mReadBuffer == NULL) { mReadBuffer = static_cast<char*>(mCallback->allocate(mReadBufferSize + 1)); } uint32_t offset = 0; uint32_t readLen = mReadBufferSize; if(scan) { offset = uint32_t(scan - mReadBuffer); uint32_t copyLen = mReadBufferSize - offset; if(copyLen) { PX_ASSERT(scan >= mReadBuffer); memmove(mReadBuffer, scan, copyLen); mReadBuffer[copyLen] = 0; readLen = mReadBufferSize - copyLen; } offset = copyLen; } uint32_t readCount = mFileBuf->read(&mReadBuffer[offset], readLen); while(readCount > 0) { mReadBuffer[readCount + offset] = 0; // end of string terminator... mReadBufferEnd = &mReadBuffer[readCount + offset]; const char* scan_ = &mReadBuffer[offset]; while(*scan_) { if(*scan_ == '<' && scan_[1] != '/') { mOpenCount++; } scan_++; } if(mOpenCount < MIN_CLOSE_COUNT) { uint32_t oldSize = uint32_t(mReadBufferEnd - mReadBuffer); mReadBufferSize = mReadBufferSize * 2; char* oldReadBuffer = mReadBuffer; mReadBuffer = static_cast<char*>(mCallback->allocate(mReadBufferSize + 1)); PxMemCopy(mReadBuffer, oldReadBuffer, oldSize); mCallback->deallocate(oldReadBuffer); offset = oldSize; uint32_t readSize = mReadBufferSize - oldSize; readCount = mFileBuf->read(&mReadBuffer[offset], readSize); if(readCount == 0) break; } else { break; } } mLastReadLoc = mFileBuf->tell(); return mReadBuffer; } bool processXml(FastXml::Callback* iface) { bool ret = true; const int MAX_ATTRIBUTE = 2048; // can't imagine having more than 2,048 attributes in a single element right? mLineNo = 1; char* element, *scan = readData(0); while(*scan) { scan = skipNextData(scan); if(*scan == 0) break; if(*scan == '<') { if(scan[1] != '/') { PX_ASSERT(mOpenCount > 0); mOpenCount--; } scan++; if(*scan == '?') // Allow xml declarations { scan++; } else if(scan[0] == '!' && scan[1] == '-' && scan[2] == '-') { scan += 3; while(*scan && *scan == ' ') scan++; char* comment = scan, *comment_end = strstr(scan, "-->"); if(comment_end) { *comment_end = 0; scan = comment_end + 3; if(!iface->processComment(comment)) { mError = "User aborted the parsing process"; return false; } } continue; } else if(scan[0] == '!') // Allow doctype { scan++; // DOCTYPE syntax differs from usual XML so we parse it here // Read DOCTYPE const char* tag = "DOCTYPE"; if(!strstr(scan, tag)) { mError = "Invalid DOCTYPE"; return false; } scan += strlen(tag); // Skip whites while(CT_SOFT == getCharType(scan)) ++scan; // Read rootElement const char* rootElement = scan; while(CT_DATA == getCharType(scan)) ++scan; char* endRootElement = scan; // TODO: read remaining fields (fpi, uri, etc.) while(CT_END_OF_ELEMENT != getCharType(scan++)) ; *endRootElement = 0; if(!iface->processDoctype(rootElement, 0, 0, 0)) { mError = "User aborted the parsing process"; return false; } continue; // Restart loop } } if(*scan == '/') { bool isError = false; scan = processClose(scan, iface, isError); if(!scan) { if(isError) { mError = "User aborted the parsing process"; } return !isError; } } else { if(*scan == '?') scan++; element = scan; int32_t argc = 0; const char* argv[MAX_ATTRIBUTE]; bool close; scan = nextSoftOrClose(scan, close); if(close) { char c = *(scan - 1); if(c != '?' && c != '/') { c = '>'; } *scan++ = 0; bool isError = false; scan = processClose(c, element, scan, argc, argv, iface, isError); if(!scan) { if(isError) { mError = "User aborted the parsing process"; } return !isError; } } else { if(*scan == 0) { return ret; } *scan = 0; // place a zero byte to indicate the end of the element name... scan++; while(*scan) { scan = skipNextData(scan); // advance past any soft seperators (tab or space) if(getCharType(scan) == CT_END_OF_ELEMENT) { char c = *scan++; if('?' == c) { if('>' != *scan) //?> { PX_ASSERT(0); return false; } scan++; } bool isError = false; scan = processClose(c, element, scan, argc, argv, iface, isError); if(!scan) { if(isError) { mError = "User aborted the parsing process"; } return !isError; } break; } else { if(argc >= MAX_ATTRIBUTE) { mError = "encountered too many attributes"; return false; } argv[argc] = scan; scan = nextSep(scan); // scan up to a space, or an equal if(*scan) { if(*scan != '=') { *scan = 0; scan++; while(*scan && *scan != '=') scan++; if(*scan == '=') scan++; } else { *scan = 0; scan++; } if(*scan) // if not eof... { scan = skipNextData(scan); if(*scan == '"') { scan++; argc++; argv[argc] = scan; argc++; while(*scan && *scan != 34) scan++; if(*scan == '"') { *scan = 0; scan++; } else { mError = "Failed to find closing quote for attribute"; return false; } } else { // mError = "Expected quote to begin attribute"; // return false; // PH: let's try to have a more graceful fallback argc--; while(*scan != '/' && *scan != '>' && *scan != 0) scan++; } } } // if( *scan ) } // if ( mTypes[*scan] } // if( close ) } // if( *scan == '/' } // while( *scan ) } if(mStackIndex) { mError = "Invalid file format"; return false; } return ret; } const char* getError(int32_t& lineno) { const char* ret = mError; lineno = mLineNo; mError = 0; return ret; } virtual void release(void) { Callback* c = mCallback; // get the user allocator interface MyFastXml* f = this; // cast the this pointer f->~MyFastXml(); // explicitely invoke the destructor for this class c->deallocate(f); // now free up the memory associated with it. } private: virtual ~MyFastXml(void) { releaseMemory(); } PX_INLINE void releaseMemory(void) { mFileBuf = NULL; mCallback->deallocate(mReadBuffer); mReadBuffer = NULL; mStackIndex = 0; mReadBufferEnd = NULL; mOpenCount = 0; mLastReadLoc = 0; mError = NULL; for(uint32_t i = 0; i < (mStackIndex + 1); i++) { if(mStackAllocated[i]) { mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[i]))); mStackAllocated[i] = false; } mStack[i] = NULL; } } PX_INLINE CharType getCharType(char* scan) const { return mTypes[uint8_t(*scan)]; } PX_INLINE char* nextSoftOrClose(char* scan, bool& close) { while(*scan && getCharType(scan) != CT_SOFT && *scan != '>') scan++; close = *scan == '>'; return scan; } PX_INLINE char* nextSep(char* scan) { while(*scan && getCharType(scan) != CT_SOFT && *scan != '=') scan++; return scan; } PX_INLINE char* skipNextData(char* scan) { // while we have data, and we encounter soft seperators or line feeds... while(*scan && (getCharType(scan) == CT_SOFT || getCharType(scan) == CT_END_OF_LINE)) { if(*scan == '\n') mLineNo++; scan++; } return scan; } void pushElement(const char* element) { PX_ASSERT(mStackIndex < uint32_t(MAX_STACK)); if(mStackIndex < uint32_t(MAX_STACK)) { if(mStackAllocated[mStackIndex]) { mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[mStackIndex]))); mStackAllocated[mStackIndex] = false; } mStack[mStackIndex++] = element; } } const char* popElement(void) { PX_ASSERT(mStackIndex > 0); if(mStackAllocated[mStackIndex]) { mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[mStackIndex]))); mStackAllocated[mStackIndex] = false; } mStack[mStackIndex] = NULL; return mStackIndex ? mStack[--mStackIndex] : NULL; } static const int MAX_STACK = 2048; CharType mTypes[256]; physx::PxInputData* mFileBuf; char* mReadBuffer; char* mReadBufferEnd; uint32_t mOpenCount; uint32_t mReadBufferSize; uint32_t mLastReadLoc; int32_t mLineNo; const char* mError; uint32_t mStackIndex; const char* mStack[MAX_STACK + 1]; bool mStreamFromMemory; bool mStackAllocated[MAX_STACK + 1]; Callback* mCallback; }; } namespace physx { namespace shdfnd { FastXml* createFastXml(FastXml::Callback* iface) { MyFastXml* m = static_cast<MyFastXml*>(iface->allocate(sizeof(MyFastXml))); if(m) { PX_PLACEMENT_NEW(m, MyFastXml(iface)); } return static_cast<FastXml*>(m); } } }
18,519
C++
21.073897
111
0.550138
NVIDIA-Omniverse/PhysX/physx/source/fastxml/include/PsFastXml.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PSFASTXML_PSFASTXML_H #define PSFASTXML_PSFASTXML_H #include "foundation/PxSimpleTypes.h" // defines basic data types; modify for your platform as needed. #include "foundation/PxIO.h" #include "foundation/PxAssert.h" #include "foundation/PxAllocator.h" namespace physx { namespace shdfnd { class FastXml { PX_NOCOPY(FastXml) public: class AttributePairs { int argc; const char** argv; public: AttributePairs() : argc(0), argv(NULL) { } AttributePairs(int c, const char** v) : argc(c), argv(v) { } PX_INLINE int getNbAttr() const { return argc / 2; } const char* getKey(uint32_t index) const { PX_ASSERT((index * 2) < uint32_t(argc)); return argv[index * 2]; } const char* getValue(uint32_t index) const { PX_ASSERT((index * 2 + 1) < uint32_t(argc)); return argv[index * 2 + 1]; } const char* get(const char* attr) const { int32_t count = argc / 2; for(int32_t i = 0; i < count; ++i) { const char* key = argv[i * 2], *value = argv[i * 2 + 1]; if(strcmp(key, attr) == 0) return value; } return NULL; } }; /*** * Callbacks to the user with the contents of the XML file properly digested. */ class Callback { public: virtual ~Callback() { } virtual bool processComment(const char* comment) = 0; // encountered a comment in the XML // 'element' is the name of the element that is being closed. // depth is the recursion depth of this element. // Return true to continue processing the XML file. // Return false to stop processing the XML file; leaves the read pointer of the stream right after this close // tag. // The bool 'isError' indicates whether processing was stopped due to an error, or intentionally canceled early. virtual bool processClose(const char* element, uint32_t depth, bool& isError) = 0; // process the 'close' // indicator for a previously // encountered element // return true to continue processing the XML document, false to skip. virtual bool processElement(const char* elementName, // name of the element const char* elementData, // element data, null if none const AttributePairs& attr, // attributes int32_t lineno) = 0; // line number in the source XML file // process the XML declaration header virtual bool processXmlDeclaration(const AttributePairs&, // attributes const char* /*elementData*/, int32_t /*lineno*/) { return true; } virtual bool processDoctype(const char* /*rootElement*/, // Root element tag const char* /*type*/, // SYSTEM or PUBLIC const char* /*fpi*/, // Formal Public Identifier const char* /*uri*/) // Path to schema file { return true; } virtual void* allocate(uint32_t size) { return PxGetBroadcastAllocator()->allocate(size, "FastXml", PX_FL); } virtual void deallocate(void* ptr) { PxGetBroadcastAllocator()->deallocate(ptr); } }; virtual bool processXml(PxInputData& buff, bool streamFromMemory = false) = 0; virtual const char* getError(int32_t& lineno) = 0; // report the reason for a parsing error, and the line number // where it occurred. FastXml() { } virtual void release(void) = 0; protected: virtual ~FastXml() { } }; FastXml* createFastXml(FastXml::Callback* iface); } // shdfnd } // physx #endif // PSFASTXML_PSFASTXML_H
5,249
C
30.437126
114
0.674414
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMSoftBodyMaterial.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "NpFEMSoftBodyMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX using namespace physx; using namespace Cm; NpFEMSoftBodyMaterial::NpFEMSoftBodyMaterial(const PxsFEMSoftBodyMaterialCore& desc) : PxFEMSoftBodyMaterial(PxConcreteType::eSOFTBODY_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpFEMSoftBodyMaterial::~NpFEMSoftBodyMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpFEMSoftBodyMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. NpPhysics::getInstance().addMaterial(this); } void NpFEMSoftBodyMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseFEMMaterialToPool(*this); } else this->~NpFEMSoftBodyMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpFEMSoftBodyMaterial* NpFEMSoftBodyMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpFEMSoftBodyMaterial* obj = PX_PLACEMENT_NEW(address, NpFEMSoftBodyMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpFEMSoftBodyMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpFEMSoftBodyMaterial::release() { RefCountable_decRefCount(*this); } void NpFEMSoftBodyMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpFEMSoftBodyMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpFEMSoftBodyMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setYoungsModulus(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "NpFEMSoftBodyMaterial::setYoungsModulus: invalid float"); mMaterial.youngs = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getYoungsModulus() const { return mMaterial.youngs; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setPoissons(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x < 0.5f, "PxMaterial::setPoissons: invalid float"); mMaterial.poissons = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getPoissons() const { return mMaterial.poissons; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDynamicFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMaterial::setDynamicFriction: invalid float"); mMaterial.dynamicFriction = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDynamicFriction() const { return mMaterial.dynamicFriction; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDampingScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x<= 1.f, "PxMaterial::setDampingScale: invalid float, must be in [0.0, 1.0] range."); mMaterial.dampingScale = toUniformU16(x); updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDampingScale() const { return toUniformReal(mMaterial.dampingScale); } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setMaterialModel(PxFEMSoftBodyMaterialModel::Enum model) { mMaterial.materialModel = PxU16(model); updateMaterial(); } PxFEMSoftBodyMaterialModel::Enum NpFEMSoftBodyMaterial::getMaterialModel() const { return PxFEMSoftBodyMaterialModel::Enum(mMaterial.materialModel); } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDeformThreshold(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformThreshold: invalid float"); mMaterial.deformThreshold = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDeformThreshold() const { return mMaterial.deformThreshold; } ///////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDeformLowLimitRatio(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformLowLimitRatio: invalid float"); mMaterial.deformLowLimitRatio = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDeformLowLimitRatio() const { return mMaterial.deformLowLimitRatio; } ///////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDeformHighLimitRatio(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformLowLimitRatio: invalid float"); mMaterial.deformHighLimitRatio = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDeformHighLimitRatio() const { return mMaterial.deformHighLimitRatio; } /////////////////////////////////////////////////////////////////////////////// #endif
7,394
C++
28.939271
118
0.692183
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMPMMaterial.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_MPM_MATERIAL_H #define NP_MPM_MATERIAL_H #include "common/PxSerialFramework.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" #include "CmRefCountable.h" #include "PxsMPMMaterialCore.h" #include "PxMPMMaterial.h" namespace physx { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION // Compared to other objects, materials are special since they belong to the SDK and not to scenes // (similar to meshes). That's why the NpMPMMaterial does have direct access to the core material instead // of having a buffered interface for it. Scenes will have copies of the SDK material table and there // the materials will be buffered. class NpMPMMaterial : public PxMPMMaterial, public PxUserAllocated { public: // PX_SERIALIZATION NpMPMMaterial(PxBaseFlags baseFlags) : PxMPMMaterial(baseFlags), mMaterial(PxEmpty) {} virtual void resolveReferences(PxDeserializationContext& context); static NpMPMMaterial* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&) {} //~PX_SERIALIZATION NpMPMMaterial(const PxsMPMMaterialCore& desc); virtual ~NpMPMMaterial(); // PxBase virtual void release() PX_OVERRIDE; //~PxBase // PxRefCounted virtual void acquireReference() PX_OVERRIDE; virtual PxU32 getReferenceCount() const PX_OVERRIDE; virtual void onRefCountZero() PX_OVERRIDE; //~PxRefCounted // PxParticleMaterial virtual void setFriction(PxReal friction) PX_OVERRIDE; virtual PxReal getFriction() const PX_OVERRIDE; virtual void setDamping(PxReal damping) PX_OVERRIDE; virtual PxReal getDamping() const PX_OVERRIDE; virtual void setAdhesion(PxReal adhesion) PX_OVERRIDE; virtual PxReal getAdhesion() const PX_OVERRIDE; virtual void setGravityScale(PxReal scale) PX_OVERRIDE; virtual PxReal getGravityScale() const PX_OVERRIDE; virtual void setAdhesionRadiusScale(PxReal scale) PX_OVERRIDE; virtual PxReal getAdhesionRadiusScale() const PX_OVERRIDE; //~PxParticleMaterial // PxMPMMaterial virtual void setStretchAndShearDamping(PxReal stretchAndShearDamping) PX_OVERRIDE; virtual PxReal getStretchAndShearDamping() const PX_OVERRIDE; virtual void setRotationalDamping(PxReal rotationalDamping) PX_OVERRIDE; virtual PxReal getRotationalDamping() const PX_OVERRIDE; virtual void setDensity(PxReal) PX_OVERRIDE; virtual PxReal getDensity() const PX_OVERRIDE; virtual void setMaterialModel(PxMPMMaterialModel::Enum) PX_OVERRIDE; virtual PxMPMMaterialModel::Enum getMaterialModel() const PX_OVERRIDE; virtual void setCuttingFlags(PxMPMCuttingFlags cuttingFlags) PX_OVERRIDE; virtual PxMPMCuttingFlags getCuttingFlags() const PX_OVERRIDE; virtual void setSandFrictionAngle(PxReal sandFrictionAngle) PX_OVERRIDE; virtual PxReal getSandFrictionAngle() const PX_OVERRIDE; virtual void setYieldStress(PxReal yieldStress) PX_OVERRIDE; virtual PxReal getYieldStress() const PX_OVERRIDE; virtual void setIsPlastic(bool) PX_OVERRIDE; virtual bool getIsPlastic() const PX_OVERRIDE; virtual void setYoungsModulus(PxReal) PX_OVERRIDE; virtual PxReal getYoungsModulus() const PX_OVERRIDE; virtual void setPoissons(PxReal) PX_OVERRIDE; virtual PxReal getPoissons() const PX_OVERRIDE; virtual void setHardening(PxReal) PX_OVERRIDE; virtual PxReal getHardening() const PX_OVERRIDE; virtual void setCriticalCompression(PxReal) PX_OVERRIDE; virtual PxReal getCriticalCompression() const PX_OVERRIDE; virtual void setCriticalStretch(PxReal) PX_OVERRIDE; virtual PxReal getCriticalStretch() const PX_OVERRIDE; virtual void setTensileDamageSensitivity(PxReal) PX_OVERRIDE; virtual PxReal getTensileDamageSensitivity() const PX_OVERRIDE; virtual void setCompressiveDamageSensitivity(PxReal) PX_OVERRIDE; virtual PxReal getCompressiveDamageSensitivity() const PX_OVERRIDE; virtual void setAttractiveForceResidual(PxReal) PX_OVERRIDE; virtual PxReal getAttractiveForceResidual() const PX_OVERRIDE; //~PxMPMMaterial PX_FORCE_INLINE static void getMaterialIndices(NpMPMMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount); private: PX_INLINE void updateMaterial(); // PX_SERIALIZATION public: //~PX_SERIALIZATION PxsMPMMaterialCore mMaterial; }; PX_FORCE_INLINE void NpMPMMaterial::getMaterialIndices(NpMPMMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount) { for (PxU32 i = 0; i < materialCount; i++) materialIndices[i] = static_cast<NpMPMMaterial*>(materials[i])->mMaterial.mMaterialIndex; } #endif } #endif
6,754
C
45.909722
132
0.758513
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidStatic.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_RIGID_STATIC_H #define NP_RIGID_STATIC_H #include "common/PxMetaData.h" #include "PxRigidStatic.h" #include "NpRigidActorTemplate.h" #include "ScStaticCore.h" namespace physx { typedef NpRigidActorTemplate<PxRigidStatic> NpRigidStaticT; class NpRigidStatic : public NpRigidStaticT { public: // PX_SERIALIZATION NpRigidStatic(PxBaseFlags baseFlags) : NpRigidStaticT(baseFlags), mCore(PxEmpty) {} void preExportDataReset() { NpRigidStaticT::preExportDataReset(); } virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpRigidStatic* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpRigidStatic(const PxTransform& pose); virtual ~NpRigidStatic(); // PxActor virtual void release() PX_OVERRIDE; virtual PxActorType::Enum getType() const PX_OVERRIDE { return PxActorType::eRIGID_STATIC; } //~PxActor // PxRigidActor virtual void setGlobalPose(const PxTransform& pose, bool wake) PX_OVERRIDE; virtual PxTransform getGlobalPose() const PX_OVERRIDE; //~PxRigidActor // PT: I think these come from NpRigidActorTemplate // PT: TODO: drop them eventually, they all re-route to NpActor now virtual void switchToNoSim() PX_OVERRIDE; virtual void switchFromNoSim() PX_OVERRIDE; #if PX_CHECKED bool checkConstraintValidity() const; #endif PX_FORCE_INLINE const Sc::StaticCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::StaticCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpRigidStatic, mCore); } static PX_FORCE_INLINE size_t getNpShapeManagerOffset() { return PX_OFFSET_OF_RT(NpRigidStatic, mShapeManager); } #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif private: Sc::StaticCore mCore; }; } #endif
3,761
C
38.1875
117
0.744483
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidActorTemplateInternal.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_RIGID_ACTOR_TEMPLATE_INTERNAL_H #define NP_RIGID_ACTOR_TEMPLATE_INTERNAL_H // PT: TODO: what is not internal about NpRigidActorTemplate.h ? Just merge the two files namespace physx { template<class APIClass, class T> static PX_FORCE_INLINE void removeRigidActorT(T& rigidActor) { NpScene* s = rigidActor.getNpScene(); NP_WRITE_CHECK(s); //Remove constraints (if any constraint is attached to the actor). rigidActor.NpRigidActorTemplate<APIClass>::removeConstraints(rigidActor); //Remove from aggregate (if it is in an aggregate). rigidActor.NpActorTemplate<APIClass>::removeFromAggregate(rigidActor); //Remove from scene (if it is in a scene). PxSceneQuerySystem* sqManager = NULL; if(s) { sqManager = &s->getSQAPI(); const bool noSim = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION); s->scRemoveActor(rigidActor, true, noSim); } //Remove associated shapes. rigidActor.NpRigidActorTemplate<APIClass>::removeShapes(sqManager); } template<class APIClass, class T> static PX_FORCE_INLINE bool releaseRigidActorT(T& rigidActor) { NpScene* s = rigidActor.getNpScene(); NP_WRITE_CHECK(s); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(s, "PxActor::release() not allowed while simulation is running. Call will be ignored.", false) const bool noSim = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION); if(s && noSim) { // need to do it here because the Np-shape buffer will not be valid anymore after the removal below // and unlike simulation objects, there is no shape buffer in the simulation controller rigidActor.getShapeManager().clearShapesOnRelease(*s, rigidActor); } NpPhysics::getInstance().notifyDeletionListenersUserRelease(&rigidActor, rigidActor.userData); //Remove constraints, aggregates, scene, shapes. removeRigidActorT<APIClass, T>(rigidActor); if (s) { s->removeFromRigidActorList(rigidActor); } return true; } } #endif
3,642
C
36.947916
145
0.763591
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterialManager.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_MATERIALMANAGER #define NP_MATERIALMANAGER #include "foundation/PxMemory.h" #include "CmIDPool.h" namespace physx { template<class Material> class NpMaterialManager { public: NpMaterialManager() { const PxU32 matCount = 128; mMaterials = reinterpret_cast<Material**>(PX_ALLOC(sizeof(Material*) * matCount, "NpMaterialManager::initialise")); mMaxMaterials = matCount; PxMemZero(mMaterials, sizeof(Material*)*mMaxMaterials); } ~NpMaterialManager() {} void releaseMaterials() { for(PxU32 i=0; i<mMaxMaterials; ++i) { if(mMaterials[i]) { const PxU32 handle(mMaterials[i]->mMaterial.mMaterialIndex); mHandleManager.freeID(handle); mMaterials[i]->release(); mMaterials[i] = NULL; } } PX_FREE(mMaterials); } bool setMaterial(Material& mat) { const PxU32 poolID = mHandleManager.getNewID(); if (poolID >= MATERIAL_INVALID_HANDLE) return false; const PxU16 materialIndex = PxTo16(poolID); if(materialIndex >= mMaxMaterials) resize(); mMaterials[materialIndex] = &mat; mat.mMaterial.mMaterialIndex = materialIndex; return true; } void updateMaterial(Material& mat) { mMaterials[mat.mMaterial.mMaterialIndex] = &mat; } PX_FORCE_INLINE PxU32 getNumMaterials() const { return mHandleManager.getNumUsedID(); } void removeMaterial(Material& mat) { const PxU16 handle = mat.mMaterial.mMaterialIndex; if(handle != MATERIAL_INVALID_HANDLE) { mMaterials[handle] = NULL; mHandleManager.freeID(PxU32(handle)); } } PX_FORCE_INLINE Material* getMaterial(const PxU32 index) const { PX_ASSERT(index < mMaxMaterials); return mMaterials[index]; } PX_FORCE_INLINE PxU32 getMaxSize() const { return mMaxMaterials; } PX_FORCE_INLINE Material** getMaterials() const { return mMaterials; } private: void resize() { const PxU32 numMaterials = mMaxMaterials; mMaxMaterials = PxMin(mMaxMaterials*2, PxU32(MATERIAL_INVALID_HANDLE)); Material** mat = reinterpret_cast<Material**>(PX_ALLOC(sizeof(Material*)*mMaxMaterials, "NpMaterialManager::resize")); PxMemZero(mat, sizeof(Material*)*mMaxMaterials); for(PxU32 i=0; i<numMaterials; ++i) mat[i] = mMaterials[i]; PX_FREE(mMaterials); mMaterials = mat; } Cm::IDPool mHandleManager; Material** mMaterials; PxU32 mMaxMaterials; }; template<class Material> class NpMaterialManagerIterator { public: NpMaterialManagerIterator(const NpMaterialManager<Material>& manager) : mManager(manager), mIndex(0) { } bool getNextMaterial(Material*& np) { const PxU32 maxSize = mManager.getMaxSize(); PxU32 index = mIndex; while(index < maxSize && mManager.getMaterial(index)==NULL) index++; np = NULL; if(index < maxSize) np = mManager.getMaterial(index++); mIndex = index; return np!=NULL; } private: NpMaterialManagerIterator& operator=(const NpMaterialManagerIterator&); const NpMaterialManager<Material>& mManager; PxU32 mIndex; }; } #endif
4,764
C
27.195266
122
0.717464
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterial.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "NpMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; using namespace Cm; NpMaterial::NpMaterial(const PxsMaterialCore& desc) : PxMaterial(PxConcreteType::eMATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpMaterial::~NpMaterial() { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, static_cast<PxMaterial &>(*this)) NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. NpPhysics::getInstance().addMaterial(this); } void NpMaterial::onRefCountZero() { void* ud = userData; if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) NpFactory::getInstance().releaseMaterialToPool(*this); else this->~NpMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpMaterial* NpMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpMaterial* obj = PX_PLACEMENT_NEW(address, NpMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpMaterial::release() { RefCountable_decRefCount(*this); } void NpMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setDynamicFriction(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setDynamicFriction: invalid float"); mMaterial.dynamicFriction = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, dynamicFriction, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getDynamicFriction() const { return mMaterial.dynamicFriction; } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setStaticFriction(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setStaticFriction: invalid float"); mMaterial.staticFriction = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, staticFriction, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getStaticFriction() const { return mMaterial.staticFriction; } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setRestitution(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setRestitution: invalid float"); PX_CHECK_MSG(((mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT || x >= 0.0f) && (x <= 1.0f)), "PxMaterial::setRestitution: Restitution value has to be in [0,1]!"); if ((!(mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x < 0.0f) || (x > 1.0f)) { PxClamp(x, 0.0f, 1.0f); PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMaterial::setRestitution: Invalid value %f was clamped to [0,1]!", PxF64(x)); } mMaterial.restitution = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitution, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getRestitution() const { return mMaterial.restitution; } ///////////////////////////////////////////////////////////////////////////////// void NpMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x) && x >= 0.f, "PxMaterial::setDamping: invalid float. Must be >= 0"); PX_CHECK_MSG((((mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x >= 0.f) || x == 0.f), "PxMaterial::setDamping: Damping value has to be in [0,INF] and PxMaterialFlag::eCOMPLIANT_CONTACT should be raised!"); if ((!(mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x != 0.0f)) { x = 0.f; PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMaterial::setDamping: Attempting to set a non-zero damping coefficient without raising PxMaterialFlag::eCOMPLIANT_CONTACT first!"); } mMaterial.damping = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, damping, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getDamping() const { return mMaterial.damping; } ///////////////////////////////////////////////////////////////////////////////// void NpMaterial::setFlag(PxMaterialFlag::Enum flag, bool value) { if (value) mMaterial.flags |= flag; else mMaterial.flags &= ~PxMaterialFlags(flag); updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, static_cast<PxMaterial &>(*this), mMaterial.flags) } void NpMaterial::setFlags(PxMaterialFlags inFlags) { mMaterial.flags = inFlags; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, static_cast<PxMaterial &>(*this), mMaterial.flags) } PxMaterialFlags NpMaterial::getFlags() const { return mMaterial.flags; } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setFrictionCombineMode(PxCombineMode::Enum x) { mMaterial.setFrictionCombineMode(x); updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, frictionCombineMode, static_cast<PxMaterial &>(*this), x) } PxCombineMode::Enum NpMaterial::getFrictionCombineMode() const { return mMaterial.getFrictionCombineMode(); } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setRestitutionCombineMode(PxCombineMode::Enum x) { mMaterial.setRestitutionCombineMode(x); updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitutionCombineMode, static_cast<PxMaterial &>(*this), x) } PxCombineMode::Enum NpMaterial::getRestitutionCombineMode() const { return mMaterial.getRestitutionCombineMode(); } ///////////////////////////////////////////////////////////////////////////////
8,101
C++
34.073593
217
0.695346
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMCloth.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NP_FEMCLOTH #define PX_PHYSICS_NP_FEMCLOTH #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxFEMCloth.h" #endif #include "ScFEMClothCore.h" #include "NpActorTemplate.h" namespace physx { class NpShape; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION class NpFEMCloth : public NpActorTemplate<PxFEMCloth> { public: NpFEMCloth(PxCudaContextManager& cudaContextManager); NpFEMCloth(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager); virtual ~NpFEMCloth() {} void exportData(PxSerializationContext& /*context*/) const {} //external API virtual PxActorType::Enum getType() const { return PxActorType::eFEMCLOTH; } virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const; virtual void setFEMClothFlag(PxFEMClothFlag::Enum flag, bool val); virtual void setFEMClothFlags(PxFEMClothFlags flags); virtual PxFEMClothFlags getFEMClothFlag() const; #if 0 // disabled until future use. virtual void setDrag(const PxReal drag); virtual PxReal getDrag() const; virtual void setLift(const PxReal lift); virtual PxReal getLift() const; virtual void setWind(const PxVec3& wind); virtual PxVec3 getWind() const; virtual void setAirDensity(const PxReal wind); virtual PxReal getAirDensity() const; virtual void setBendingActivationAngle(const PxReal angle); virtual PxReal getBendingActivationAngle() const; #endif virtual void setParameter(const PxFEMParameters& paramters); virtual PxFEMParameters getParameter() const; virtual void setBendingScales(const PxReal* const bendingScale, PxU32 nbElements); virtual const PxReal* getBendingScales() const; virtual PxU32 getNbBendingScales() const; virtual void setMaxVelocity(const PxReal v); virtual PxReal getMaxVelocity() const; virtual void setMaxDepenetrationVelocity(const PxReal v); virtual PxReal getMaxDepenetrationVelocity() const; virtual void setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency); virtual PxU32 getNbCollisionPairUpdatesPerTimestep() const; virtual void setNbCollisionSubsteps(const PxU32 frequency); virtual PxU32 getNbCollisionSubsteps() const; virtual PxVec4* getPositionInvMassBufferD(); virtual PxVec4* getVelocityBufferD(); virtual PxVec4* getRestPositionBufferD(); virtual void markDirty(PxFEMClothDataFlags flags); virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle); virtual void addTriRigidFilter(PxRigidActor* actor, PxU32 triangleId); virtual void removeTriRigidFilter(PxRigidActor* actor, PxU32 triangleId); virtual PxU32 addTriRigidAttachment(PxRigidActor* actor, PxU32 triangleId, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void removeTriRigidAttachment(PxRigidActor* actor, PxU32 handle); virtual void addClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx); virtual void removeClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx); virtual PxU32 addClothAttachment(PxFEMCloth* otherCloth, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric); virtual void removeClothAttachment(PxFEMCloth* otherCloth, PxU32 handle); virtual PxCudaContextManager* getCudaContextManager() const; virtual void setCudaContextManager(PxCudaContextManager*); virtual void setSolverIterationCounts(PxU32 minPositionIters); virtual void getSolverIterationCounts(PxU32& minPositionIters) const; virtual PxShape* getShape(); virtual bool attachShape(PxShape& shape); virtual void detachShape(); virtual void release(); PX_FORCE_INLINE const Sc::FEMClothCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::FEMClothCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpFEMCloth, mCore); } virtual bool isSleeping() const; // Debug name void setName(const char*); const char* getName() const; void updateMaterials(); private: NpShape* mShape; Sc::FEMClothCore mCore; PxCudaContextManager* mCudaContextManager; }; #endif } #endif #endif
6,406
C
37.830303
175
0.753512
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationLink.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_ARTICULATION_LINK_H #define NP_ARTICULATION_LINK_H #include "NpRigidBodyTemplate.h" #include "PxArticulationLink.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif namespace physx { class NpArticulationLink; class NpArticulationJointReducedCoordinate; class PxConstraintVisualizer; typedef NpRigidBodyTemplate<PxArticulationLink> NpArticulationLinkT; class NpArticulationLinkArray : public PxInlineArray<NpArticulationLink*, 4> //!!!AL TODO: check if default of 4 elements makes sense { public: // PX_SERIALIZATION NpArticulationLinkArray(const PxEMPTY) : PxInlineArray<NpArticulationLink*, 4> (PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationLinkArray() : PxInlineArray<NpArticulationLink*, 4>("articulationLinkArray") {} }; class NpArticulationLink : public NpArticulationLinkT { public: // PX_SERIALIZATION NpArticulationLink(PxBaseFlags baseFlags) : NpArticulationLinkT(baseFlags), mChildLinks(PxEmpty) {} void preExportDataReset() { NpArticulationLinkT::preExportDataReset(); } virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); virtual bool isSubordinate() const { return true; } static NpArticulationLink* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION virtual ~NpArticulationLink(); //--------------------------------------------------------------------------------- // PxArticulationLink implementation //--------------------------------------------------------------------------------- virtual void release(); virtual PxActorType::Enum getType() const { return PxActorType::eARTICULATION_LINK; } // Pose virtual void setGlobalPose(const PxTransform& /*pose*/, bool /*wake*/) { /*return false; */} virtual PxTransform getGlobalPose() const; virtual bool attachShape(PxShape& shape); virtual void detachShape(PxShape& shape, bool wakeOnLostTouch = true); virtual PxArticulationReducedCoordinate& getArticulation() const; virtual PxArticulationJointReducedCoordinate* getInboundJoint() const; virtual PxU32 getInboundJointDof() const; virtual PxU32 getNbChildren() const; virtual PxU32 getChildren(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getLinkIndex() const; virtual void setCMassLocalPose(const PxTransform& pose); virtual void addForce(const PxVec3& force, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true); virtual void addTorque(const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true); virtual void setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE); virtual void clearForce(PxForceMode::Enum mode = PxForceMode::eFORCE); virtual void clearTorque(PxForceMode::Enum mode = PxForceMode::eFORCE); virtual void setCfmScale(const PxReal cfmScale); virtual PxReal getCfmScale() const; //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpArticulationLink(const PxTransform& bodyPose, PxArticulationReducedCoordinate& root, NpArticulationLink* parent); void releaseInternal(); PX_INLINE PxArticulationReducedCoordinate& getRoot() { return *mRoot; } PX_INLINE NpArticulationLink* getParent() { return mParent; } PX_INLINE const NpArticulationLink* getParent() const { return mParent; } PX_INLINE void setInboundJoint(PxArticulationJointReducedCoordinate& joint) { mInboundJoint = &joint; } void setGlobalPoseInternal(const PxTransform& pose, bool autowake); void setLLIndex(const PxU32 index) { mLLIndex = index; } void setInboundJointDof(const PxU32 index); static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpArticulationLink, mCore); } private: PX_INLINE void addToChildList(NpArticulationLink& link) { mChildLinks.pushBack(&link); } PX_INLINE void removeFromChildList(NpArticulationLink& link) { PX_ASSERT(mChildLinks.find(&link) != mChildLinks.end()); mChildLinks.findAndReplaceWithLast(&link); } public: PX_INLINE NpArticulationLink* const* getChildren() { return mChildLinks.empty() ? NULL : &mChildLinks.front(); } void setFixedBaseLink(bool value); #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; void visualizeJoint(PxConstraintVisualizer& jointViz) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif private: PxArticulationReducedCoordinate* mRoot; //!!!AL TODO: Revisit: Could probably be avoided if registration and deregistration in root is handled differently PxArticulationJointReducedCoordinate* mInboundJoint; NpArticulationLink* mParent; //!!!AL TODO: Revisit: Some memory waste but makes things faster NpArticulationLinkArray mChildLinks; PxU32 mLLIndex; PxU32 mInboundJointDof; }; } #endif
7,266
C
46.496732
170
0.715662
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneQueryCollector.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_PVD_SCENEQUERYCOLLECTOR_H #define NP_PVD_SCENEQUERYCOLLECTOR_H #include "geometry/PxGeometryHelpers.h" #include "PxFiltering.h" #include "PxQueryReport.h" #include "PxQueryFiltering.h" #include "foundation/PxArray.h" #include "foundation/PxMutex.h" #if PX_SUPPORT_PVD namespace physx { namespace Vd { class PvdSceneClient; struct QueryID { enum Enum { QUERY_RAYCAST_ANY_OBJECT, QUERY_RAYCAST_CLOSEST_OBJECT, QUERY_RAYCAST_ALL_OBJECTS, QUERY_OVERLAP_SPHERE_ALL_OBJECTS, QUERY_OVERLAP_AABB_ALL_OBJECTS, QUERY_OVERLAP_OBB_ALL_OBJECTS, QUERY_OVERLAP_CAPSULE_ALL_OBJECTS, QUERY_OVERLAP_CONVEX_ALL_OBJECTS, QUERY_LINEAR_OBB_SWEEP_CLOSEST_OBJECT, QUERY_LINEAR_CAPSULE_SWEEP_CLOSEST_OBJECT, QUERY_LINEAR_CONVEX_SWEEP_CLOSEST_OBJECT }; }; struct PvdReference { PX_FORCE_INLINE PvdReference() {} PX_FORCE_INLINE PvdReference(const char* arrayName, PxU32 baseIndex, PxU32 count) : mArrayName(arrayName), mBaseIndex(baseIndex), mCount(count) {} const char* mArrayName; PxU32 mBaseIndex; PxU32 mCount; }; struct PvdRaycast { PxU32 mType; PxFilterData mFilterData; PxU32 mFilterFlags; PxVec3 mOrigin; PxVec3 mUnitDir; PxReal mDistance; PvdReference mHits; }; struct PvdOverlap { PxU32 mType; PxFilterData mFilterData; PxU32 mFilterFlags; PxTransform mPose; PvdReference mGeometries; PvdReference mHits; }; struct PvdSweep { PxU32 mType; PxU32 mFilterFlags; PxVec3 mUnitDir; PxReal mDistance; PvdReference mGeometries; PvdReference mPoses; PvdReference mFilterData; PvdReference mHits; }; struct PvdSqHit { const void* mShape; const void* mActor; PxU32 mFaceIndex; PxU32 mFlags; PxVec3 mImpact; PxVec3 mNormal; PxF32 mDistance; PxF32 mU; PxF32 mV; PvdSqHit() { setDefaults(0xFFFFffff, NULL, NULL); } explicit PvdSqHit(const PxOverlapHit& hit) { setDefaults(hit.faceIndex, hit.shape, hit.actor); } explicit PvdSqHit(const PxRaycastHit& hit) { setDefaults(hit.faceIndex, hit.shape, hit.actor); mImpact = hit.position; mNormal = hit.normal; mDistance = hit.distance; mFlags = hit.flags; mU = hit.u; mV = hit.v; } explicit PvdSqHit(const PxSweepHit& hit) { setDefaults(hit.faceIndex, hit.shape, hit.actor); mImpact = hit.position; mNormal = hit.normal; mDistance = hit.distance; mFlags = hit.flags; } private: void setDefaults(PxU32 faceIndex, const void* shape, const void* actor) { mShape = shape; mActor = actor; mFaceIndex = faceIndex; mFlags = 0; mImpact = mNormal = PxVec3(0.0f); mDistance = mU = mV = 0.0f; } }; template <class T> class NamedArray : public PxArray<T> { public: NamedArray(const char* names[2]) { mNames[0] = names[0]; mNames[1] = names[1]; } const char* mNames[2]; }; class PvdSceneQueryCollector { PX_NOCOPY(PvdSceneQueryCollector) public: PvdSceneQueryCollector(Vd::PvdSceneClient* pvd, bool isBatched); ~PvdSceneQueryCollector() {} void clear() { PxMutex::ScopedLock lock(mMutex); mAccumulatedRaycastQueries.clear(); mAccumulatedOverlapQueries.clear(); mAccumulatedSweepQueries.clear(); mPvdSqHits.clear(); mPoses.clear(); mFilterData.clear(); } void clearGeometryArrays() { mGeometries0.clear(); mGeometries1.clear(); } void release(); void raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits); void sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits); void overlapMultiple(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData); PX_FORCE_INLINE PxMutex& getLock() { return mMutex; } template <class T> PX_FORCE_INLINE const char* getArrayName(const NamedArray<T>& namedArray) const { return namedArray.mNames[mIsBatched]; } PX_FORCE_INLINE const NamedArray<PxGeometryHolder>& getGeometries(PxU32 index) const { return index ? mGeometries1 : mGeometries0; } PX_FORCE_INLINE NamedArray<PxGeometryHolder>& getGeometries(PxU32 index) { return index ? mGeometries1 : mGeometries0; } PX_FORCE_INLINE const NamedArray<PxGeometryHolder>& getCurrentFrameGeometries() const { return getGeometries(mInUse); } PX_FORCE_INLINE const NamedArray<PxGeometryHolder>& getPrevFrameGeometries() const { return getGeometries(mInUse ^ 1); } void prepareNextFrameGeometries() { mInUse ^= 1; getGeometries(mInUse).clear(); } NamedArray<PvdRaycast> mAccumulatedRaycastQueries; NamedArray<PvdSweep> mAccumulatedSweepQueries; NamedArray<PvdOverlap> mAccumulatedOverlapQueries; NamedArray<PvdSqHit> mPvdSqHits; NamedArray<PxTransform> mPoses; NamedArray<PxFilterData> mFilterData; private: Vd::PvdSceneClient* mPVD; PxMutex mMutex; NamedArray<PxGeometryHolder>mGeometries0; NamedArray<PxGeometryHolder>mGeometries1; PxU32 mInUse; const bool mIsBatched; }; } } #endif // PX_SUPPORT_PVD #endif // NP_PVD_SCENEQUERYCOLLECTOR_H
6,912
C
27.684647
199
0.741753
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneQueryCollector.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 "NpPvdSceneQueryCollector.h" #include "NpPvdSceneClient.h" #if PX_SUPPORT_PVD using namespace physx; using namespace Vd; static const char* gName_PvdRaycast[2] = { "SceneQueries.Raycasts", "BatchedQueries.Raycasts" }; static const char* gName_PvdSweep[2] = { "SceneQueries.Sweeps", "BatchedQueries.Sweeps" }; static const char* gName_PvdOverlap[2] = { "SceneQueries.Overlaps", "BatchedQueries.Overlaps" }; static const char* gName_PvdSqHit[2] = { "SceneQueries.Hits", "BatchedQueries.Hits" }; static const char* gName_PxTransform[2] = { "SceneQueries.PoseList", "BatchedQueries.PoseList" }; static const char* gName_PxFilterData[2] = { "SceneQueries.FilterDataList", "BatchedQueries.FilterDataList" }; static const char* gName_PxGeometryHolder[2] = { "SceneQueries.GeometryList", "BatchedQueries.GeometryList" }; PvdSceneQueryCollector::PvdSceneQueryCollector(Vd::PvdSceneClient* pvd, bool isBatched) : mAccumulatedRaycastQueries (gName_PvdRaycast), mAccumulatedSweepQueries (gName_PvdSweep), mAccumulatedOverlapQueries (gName_PvdOverlap), mPvdSqHits (gName_PvdSqHit), mPoses (gName_PxTransform), mFilterData (gName_PxFilterData), mPVD (pvd), mGeometries0 (gName_PxGeometryHolder), mGeometries1 (gName_PxGeometryHolder), mInUse (0), mIsBatched (isBatched) { } void PvdSceneQueryCollector::release() { physx::pvdsdk::PvdDataStream* stream = mPVD->getDataStream(); if(stream && stream->isConnected()) { const PxArray<PxGeometryHolder>& geoms = getPrevFrameGeometries(); for(PxU32 k=0; k<geoms.size(); ++k) stream->destroyInstance(&geoms[k]); clearGeometryArrays(); } } template<class SDKHitType, class PvdHitType> static void accumulate(PvdHitType& query, PxArray<PvdHitType>& accumulated, const char* arrayName, PxArray<PvdSqHit>& dst, const SDKHitType* src, PxU32 nb, const PxQueryFilterData& fd) { query.mFilterFlags = fd.flags; query.mHits = PvdReference(arrayName, dst.size(), nb); PX_ASSERT(PxU32(-1) != nb); for(PxU32 i=0; i<nb; i++) dst.pushBack(PvdSqHit(src[i])); accumulated.pushBack(query); } static PX_FORCE_INLINE void clampNbHits(PxU32& hitsNum, const PxQueryFilterData& fd, bool multipleHits) { if((fd.flags & PxQueryFlag::eANY_HIT) || !multipleHits) hitsNum = hitsNum > 0 ? 1u : 0; } template<class Type> static void pushBackT(PxArray<Type>& array, const Type& item, PvdReference& ref, const char* arrayName) { ref = PvdReference(arrayName, array.size(), 1); array.pushBack(item); } void PvdSceneQueryCollector::raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& fd, bool multipleHits) { PxMutex::ScopedLock lock(mMutex); PvdRaycast raycastQuery; raycastQuery.mOrigin = origin; raycastQuery.mUnitDir = unitDir; raycastQuery.mDistance = distance; raycastQuery.mFilterData = fd.data; if(fd.flags & PxQueryFlag::eANY_HIT) raycastQuery.mType = QueryID::QUERY_RAYCAST_ANY_OBJECT; else if(multipleHits) raycastQuery.mType = QueryID::QUERY_RAYCAST_ALL_OBJECTS; else raycastQuery.mType = QueryID::QUERY_RAYCAST_CLOSEST_OBJECT; clampNbHits(hitsNum, fd, multipleHits); accumulate(raycastQuery, mAccumulatedRaycastQueries, getArrayName(mPvdSqHits), mPvdSqHits, hit, hitsNum, fd); } void PvdSceneQueryCollector::sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& fd, bool multipleHits) { PxMutex::ScopedLock lock(mMutex); PvdSweep sweepQuery; pushBackT(getGeometries(mInUse), PxGeometryHolder(geometry), sweepQuery.mGeometries, getArrayName(getGeometries(mInUse))); // PT: TODO: optimize this. We memcopy once to the stack, then again to the array.... pushBackT(mPoses, pose, sweepQuery.mPoses, getArrayName(mPoses)); pushBackT(mFilterData, fd.data, sweepQuery.mFilterData, getArrayName(mFilterData)); const PxGeometryType::Enum type = geometry.getType(); // PT: TODO: QueryID::QUERY_LINEAR_xxx_SWEEP_ALL_OBJECTS are never used! if(type==PxGeometryType::eBOX) sweepQuery.mType = QueryID::QUERY_LINEAR_OBB_SWEEP_CLOSEST_OBJECT; else if(type==PxGeometryType::eSPHERE || type==PxGeometryType::eCAPSULE) sweepQuery.mType = QueryID::QUERY_LINEAR_CAPSULE_SWEEP_CLOSEST_OBJECT; else if(type==PxGeometryType::eCONVEXMESH) sweepQuery.mType = QueryID::QUERY_LINEAR_CONVEX_SWEEP_CLOSEST_OBJECT; else PX_ASSERT(0); sweepQuery.mUnitDir = unitDir; sweepQuery.mDistance = distance; clampNbHits(hitsNum, fd, multipleHits); accumulate(sweepQuery, mAccumulatedSweepQueries, getArrayName(mPvdSqHits), mPvdSqHits, hit, hitsNum, fd); } void PvdSceneQueryCollector::overlapMultiple(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& fd) { PxMutex::ScopedLock lock(mMutex); PvdOverlap overlapQuery; pushBackT(getGeometries(mInUse), PxGeometryHolder(geometry), overlapQuery.mGeometries, getArrayName(getGeometries(mInUse))); // PT: TODO: optimize this. We memcopy once to the stack, then again to the array.... const PxGeometryType::Enum type = geometry.getType(); if(type==PxGeometryType::eBOX) overlapQuery.mType = pose.q.isIdentity() ? QueryID::QUERY_OVERLAP_AABB_ALL_OBJECTS : QueryID::QUERY_OVERLAP_OBB_ALL_OBJECTS; else if(type==PxGeometryType::eSPHERE) overlapQuery.mType = QueryID::QUERY_OVERLAP_SPHERE_ALL_OBJECTS; else if(type==PxGeometryType::eCAPSULE) overlapQuery.mType = QueryID::QUERY_OVERLAP_CAPSULE_ALL_OBJECTS; else if(type==PxGeometryType::eCONVEXMESH) overlapQuery.mType = QueryID::QUERY_OVERLAP_CONVEX_ALL_OBJECTS; else PX_ASSERT(0); overlapQuery.mPose = pose; overlapQuery.mFilterData = fd.data; accumulate(overlapQuery, mAccumulatedOverlapQueries, getArrayName(mPvdSqHits), mPvdSqHits, hit, hitsNum, fd); } #endif
7,595
C++
48.324675
213
0.7605
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdMetaDataBindingData.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 PVD_META_DATA_BINDING_DATA_H #define PVD_META_DATA_BINDING_DATA_H #if PX_SUPPORT_PVD #include "foundation/PxSimpleTypes.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "foundation/PxArray.h" namespace physx { namespace Vd { typedef PxHashSet<const PxRigidActor*> OwnerActorsValueType; typedef PxHashMap<const PxShape*, OwnerActorsValueType*> OwnerActorsMap; struct PvdMetaDataBindingData : public PxUserAllocated { PxArray<PxU8> mTempU8Array; PxArray<PxActor*> mActors; PxArray<PxArticulationReducedCoordinate*> mArticulations; PxArray<PxArticulationLink*> mArticulationLinks; PxHashSet<PxActor*> mSleepingActors; OwnerActorsMap mOwnerActorsMap; PvdMetaDataBindingData() : mTempU8Array("TempU8Array") , mActors("PxActor") , mArticulations("Articulations") , mArticulationLinks("ArticulationLinks") , mSleepingActors("SleepingActors") { } template <typename TDataType> TDataType* allocateTemp(PxU32 numItems) { mTempU8Array.resize(numItems * sizeof(TDataType)); if(numItems) return reinterpret_cast<TDataType*>(mTempU8Array.begin()); else return NULL; } DataRef<const PxU8> tempToRef() { return DataRef<const PxU8>(mTempU8Array.begin(), mTempU8Array.size()); } }; } } #endif // PX_SUPPORT_PVD #endif
2,978
C
34.464285
74
0.770316
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationTendon.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 "NpArticulationTendon.h" #include "NpArticulationLink.h" #include "NpArticulationReducedCoordinate.h" #include "ScArticulationTendonSim.h" #include "CmUtils.h" using namespace physx; // PX_SERIALIZATION void NpArticulationAttachment::requiresObjects(PxProcessPxBaseCallback& c) { // Collect articulation links const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) c.process(*mChildren[i]); } void NpArticulationAttachment::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mChildren, stream); } void NpArticulationAttachment::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mChildren, context); } void NpArticulationAttachment::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mLink); context.translatePxBase(mParent); const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) { NpArticulationAttachment*& attachment = mChildren[i]; context.translatePxBase(attachment); } context.translatePxBase(mTendon); mCore.mParent = mParent ? &static_cast<NpArticulationAttachment*>(mParent)->mCore : NULL; } NpArticulationAttachment* NpArticulationAttachment::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationAttachment* obj = PX_PLACEMENT_NEW(address, NpArticulationAttachment(PxBaseFlags(0))); address += sizeof(NpArticulationAttachment); obj->importExtraData(context); obj->resolveReferences(context); return obj; } // ~PX_SERIALIZATION NpArticulationAttachment::NpArticulationAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link): PxArticulationAttachment(PxConcreteType::eARTICULATION_ATTACHMENT, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_ATTACHMENT), mLink(link), mParent(parent) { NpArticulationAttachment* npParent = static_cast<NpArticulationAttachment*>(parent); mCore.mRelativeOffset = link->getCMassLocalPose().transform(relativeOffset); mCore.mParent = npParent ? &npParent->getCore() : NULL; mCore.mLowLimit = PX_MAX_F32; mCore.mHighLimit = -PX_MAX_F32; mCore.mRestLength = 0.f; mCore.mCoefficient = coefficient; mCore.mTendonSim = NULL; mCore.mAttachmentIndex = 0xffffffff; } NpArticulationAttachment::~NpArticulationAttachment() { } void NpArticulationAttachment::setRestLength(const PxReal restLength) { PX_CHECK_AND_RETURN(PxIsFinite(restLength), "PxArticulationAttachment::setRestLength(): restLength must have valid value."); PX_CHECK_AND_RETURN(isLeaf(), "PxArticulationAttachment::setRestLength(): Setting rest length on a non-leaf attachment has no effect."); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setRestLength(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mRestLength = restLength; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentRestLength(mCore, restLength); } PxReal NpArticulationAttachment::getRestLength() const { return mCore.mRestLength; } void NpArticulationAttachment::setLimitParameters(const PxArticulationTendonLimit& parameter) { PX_CHECK_AND_RETURN(PxIsFinite(parameter.lowLimit) && PxIsFinite(parameter.highLimit) && (parameter.lowLimit <= parameter.highLimit), "NpArticulationAttachment::setLimitParameters(): lowLimit and highLimit must have valid values and lowLimit must be less than highLimit!"); PX_CHECK_AND_RETURN(isLeaf(), "PxArticulationAttachment::setLimitParameters(): Setting limits on a non-leaf attachment has no effect."); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setLimitParameters(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mLowLimit = parameter.lowLimit; mCore.mHighLimit = parameter.highLimit; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentLimits(mCore, parameter.lowLimit, parameter.highLimit); } PxArticulationTendonLimit NpArticulationAttachment::getLimitParameters()const { PxArticulationTendonLimit parameter; parameter.lowLimit = mCore.mLowLimit; parameter.highLimit = mCore.mHighLimit; return parameter; } void NpArticulationAttachment::setRelativeOffset(const PxVec3& offset) { NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setRelativeOffset(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mRelativeOffset = offset; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentRelativeOffset(mCore, offset); } PxVec3 NpArticulationAttachment::getRelativeOffset() const { return mCore.mRelativeOffset; } void NpArticulationAttachment::setCoefficient(const PxReal coefficient) { PX_CHECK_AND_RETURN(PxIsFinite(coefficient), "PxArticulationAttachment::setCoefficient :: Error: NaN or Inf joint coefficient provided!"); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setCoefficient(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mCoefficient = coefficient; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentCoefficient(mCore, coefficient); } PxReal NpArticulationAttachment::getCoefficient() const { return mCore.mCoefficient; } PxArticulationSpatialTendon* NpArticulationAttachment::getTendon() const { return mTendon; } void NpArticulationAttachment::release() { if (mTendon->getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::release() not allowed while the articulation is in the scene. Call will be ignored."); return; } PX_CHECK_AND_RETURN(getNumChildren() == 0, "PxArticulationAttachment:release() can only release leaf attachments, i.e. attachments with zero children."); NpArticulationAttachmentArray& attachments = mTendon->getAttachments(); NpArticulationAttachment* npParentAttachment = static_cast<NpArticulationAttachment*>(mParent); //remove this attachment from the parent if (npParentAttachment) npParentAttachment->removeChild(this); attachments.back()->mHandle = mHandle; attachments.replaceWithLast(mHandle); this->~NpArticulationAttachment(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } void NpArticulationAttachment::removeChild(NpArticulationAttachment* child) { const PxU32 size = mChildren.size(); PxU32 index = 0; for (PxU32 i = 0; i < size; ++i) { NpArticulationAttachment* otherChild = mChildren[i]; if (otherChild == child) { index = i; break; } } const PxU32 lastIndex = size - 1; mChildren[index] = mChildren[lastIndex]; mChildren.forceSize_Unsafe(lastIndex); } // PX_SERIALIZATION void NpArticulationSpatialTendon::requiresObjects(PxProcessPxBaseCallback& c) { const PxU32 nbAttachments = mAttachments.size(); for (PxU32 i = 0; i < nbAttachments; i++) c.process(*mAttachments[i]); } void NpArticulationSpatialTendon::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mAttachments, stream); } void NpArticulationSpatialTendon::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mAttachments, context); } void NpArticulationSpatialTendon::resolveReferences(PxDeserializationContext& context) { const PxU32 nbAttachments = mAttachments.size(); for (PxU32 i = 0; i < nbAttachments; i++) { NpArticulationAttachment*& attachment = mAttachments[i]; context.translatePxBase(attachment); } context.translatePxBase(mArticulation); } NpArticulationSpatialTendon* NpArticulationSpatialTendon::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationSpatialTendon* obj = PX_PLACEMENT_NEW(address, NpArticulationSpatialTendon(PxBaseFlags(0))); address += sizeof(NpArticulationSpatialTendon); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationSpatialTendon::NpArticulationSpatialTendon(NpArticulationReducedCoordinate* articulation) : PxArticulationSpatialTendon(PxConcreteType::eARTICULATION_SPATIAL_TENDON, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_SPATIAL_TENDON), mArticulation(articulation) { mLLIndex = 0xffffffff; mHandle = 0xffffffff; } NpArticulationSpatialTendon::~NpArticulationSpatialTendon() { for (PxU32 i = 0; i < mAttachments.size(); ++i) { if (mAttachments[i]) { mAttachments[i]->~NpArticulationAttachment(); if(mAttachments[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(mAttachments[i]); } } } PxArticulationAttachment* NpArticulationSpatialTendon::createAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::createAttachment() not allowed while the articulation is in the scene. Call will be ignored."); return NULL; } PX_CHECK_AND_RETURN_NULL(link, "PxArticulationSpatialTendon::createAttachment: Null pointer link provided. Need valid link."); PX_CHECK_AND_RETURN_NULL(&link->getArticulation() == getArticulation(), "PxArticulationSpatialTendon::createAttachment: Link from another articulation provided. Need valid link from same articulation."); #if PX_CHECKED if(parent) PX_CHECK_AND_RETURN_NULL(parent->getTendon() == this, "PxArticulationSpatialTendon::createAttachment: Parent attachment from another tendon provided. Need valid parent from same tendon."); #endif void* npAttachmentMem = PX_ALLOC(sizeof(NpArticulationAttachment), "NpArticulationAttachment"); PxMarkSerializedMemory(npAttachmentMem, sizeof(NpArticulationAttachment)); NpArticulationAttachment* npAttachment = PX_PLACEMENT_NEW(npAttachmentMem, NpArticulationAttachment)(parent, coefficient, relativeOffset, link); if (npAttachment) { npAttachment->setTendon(this); NpArticulationAttachment* parentAttachment = static_cast<NpArticulationAttachment*>(parent); ArticulationAttachmentHandle handle = mAttachments.size(); npAttachment->mHandle = handle; mAttachments.pushBack(npAttachment); if (parentAttachment) { parentAttachment->mChildren.pushBack(npAttachment); npAttachment->mParent = parent; } else { npAttachment->mParent = NULL; } } return npAttachment; } PxU32 NpArticulationSpatialTendon::getAttachments(PxArticulationAttachment** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(mArticulation->getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mAttachments.begin(), mAttachments.size()); } void NpArticulationSpatialTendon::setStiffness(const PxReal stiffness) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >= 0.0f, "PxArticulationTendon::setStiffness: spring coefficient must be >= 0!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationTendon::setStiffness() not allowed while simulation is running. Call will be ignored.") if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getStiffness(); } void NpArticulationSpatialTendon::setDamping(const PxReal damping) { PX_CHECK_AND_RETURN(PxIsFinite(damping) && damping >= 0.0f, "PxArticulationTendon::setDamping: damping coefficient must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setDamping(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setDamping(damping); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getDamping() const { NP_READ_CHECK(getNpScene()); return mCore.getDamping(); } void NpArticulationSpatialTendon::setLimitStiffness(const PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >= 0.0f, "PxArticulationTendon::setLimitStiffness: stiffness must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setLimitStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimitStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getLimitStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getLimitStiffness(); } void NpArticulationSpatialTendon::setOffset(const PxReal offset, bool autowake) { PX_CHECK_AND_RETURN(PxIsFinite(offset), "PxArticulationTendon::setOffset(): invalid value provided!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setOffset(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); if (autowake && getNpScene()) mArticulation->autoWakeInternal(); mCore.setOffset(offset); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getOffset(); } PxArticulationReducedCoordinate* physx::NpArticulationSpatialTendon::getArticulation() const { return mArticulation; } void NpArticulationSpatialTendon::release() { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::release() not allowed while the articulation is in a scene. Call will be ignored."); return; } PxArray<NpArticulationSpatialTendon*>& spatialTendons = mArticulation->getSpatialTendons(); spatialTendons.back()->setHandle(mHandle); spatialTendons.replaceWithLast(mHandle); this->~NpArticulationSpatialTendon(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } NpArticulationAttachment* NpArticulationSpatialTendon::getAttachment(const PxU32 index) { return mAttachments[index]; } PxU32 NpArticulationSpatialTendon::getNbAttachments() const { return mAttachments.size(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PX_SERIALIZATION void NpArticulationTendonJoint::requiresObjects(PxProcessPxBaseCallback& c) { // Collect articulation links const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) c.process(*mChildren[i]); } void NpArticulationTendonJoint::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mChildren, stream); } void NpArticulationTendonJoint::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mChildren, context); } void NpArticulationTendonJoint::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mLink); context.translatePxBase(mParent); const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) { NpArticulationTendonJoint*& tendonJoint = mChildren[i]; context.translatePxBase(tendonJoint); } context.translatePxBase(mTendon); mCore.mParent = mParent ? &static_cast<NpArticulationTendonJoint*>(mParent)->mCore : NULL; } NpArticulationTendonJoint* NpArticulationTendonJoint::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationTendonJoint* obj = PX_PLACEMENT_NEW(address, NpArticulationTendonJoint(PxBaseFlags(0))); address += sizeof(NpArticulationTendonJoint); obj->importExtraData(context); obj->resolveReferences(context); return obj; } // ~PX_SERIALIZATION NpArticulationTendonJoint::NpArticulationTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) : PxArticulationTendonJoint(PxConcreteType::eARTICULATION_TENDON_JOINT, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_TENDON_JOINT) { NpArticulationTendonJoint* npParent = static_cast<NpArticulationTendonJoint*>(parent); mCore.mParent = parent ? &npParent->getCore() : NULL; mCore.mLLTendonJointIndex = 0xffffffff; mCore.coefficient = coefficient; mCore.recipCoefficient = recipCoefficient; mCore.axis = axis; mCore.mTendonSim = NULL; mLink = link; mParent = parent; mTendon = NULL; mHandle = 0xffffffff; } PxArticulationFixedTendon* physx::NpArticulationTendonJoint::getTendon() const { return mTendon; } void NpArticulationTendonJoint::setCoefficient(const PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient) { PX_CHECK_AND_RETURN(PxIsFinite(coefficient), "PxArticulationTendonJoint::setCoefficient :: Error: NaN or Inf joint coefficient provided!"); PX_CHECK_AND_RETURN(PxIsFinite(recipCoefficient), "PxArticulationTendonJoint::setCoefficient :: Error: NaN or Inf joint recipCoefficient provided!"); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationTendonJoint::setCoefficient(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.coefficient = coefficient; mCore.recipCoefficient = recipCoefficient; if (mCore.mTendonSim) { mCore.mTendonSim->setTendonJointCoefficient(mCore, axis, coefficient, recipCoefficient); } } void NpArticulationTendonJoint::getCoefficient(PxArticulationAxis::Enum& axis, PxReal& coefficient, PxReal& recipCoefficient) const { mCore.getCoefficient(axis, coefficient, recipCoefficient); } void NpArticulationTendonJoint::release() { if (mTendon->getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationTendonJoint::release() not allowed while the articulation is in the scene. Call will be ignored."); return; } PX_CHECK_AND_RETURN(getNumChildren() == 0, "PxArticulationTendonJoint::release() can only release leaf tendon joints, i.e. joints with zero children."); NpArticulationTendonJointArray& tendonJoints = mTendon->getTendonJoints(); //remove this joint from the parent NpArticulationTendonJoint* npParentJoint = static_cast<NpArticulationTendonJoint*>(mParent); if (npParentJoint) npParentJoint->removeChild(this); tendonJoints.back()->mHandle = mHandle; tendonJoints.replaceWithLast(mHandle); this->~NpArticulationTendonJoint(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } // PX_SERIALIZATION void NpArticulationFixedTendon::requiresObjects(PxProcessPxBaseCallback& c) { const PxU32 nbTendonJoints = mTendonJoints.size(); for (PxU32 i = 0; i < nbTendonJoints; i++) c.process(*mTendonJoints[i]); } void NpArticulationFixedTendon::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mTendonJoints, stream); } void NpArticulationFixedTendon::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mTendonJoints, context); } void NpArticulationFixedTendon::resolveReferences(PxDeserializationContext& context) { const PxU32 nbTendonJoints = mTendonJoints.size(); for (PxU32 i = 0; i < nbTendonJoints; i++) { NpArticulationTendonJoint*& tendonJoint = mTendonJoints[i]; context.translatePxBase(tendonJoint); } context.translatePxBase(mArticulation); } NpArticulationFixedTendon* NpArticulationFixedTendon::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationFixedTendon* obj = PX_PLACEMENT_NEW(address, NpArticulationFixedTendon(PxBaseFlags(0))); address += sizeof(NpArticulationFixedTendon); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationFixedTendon::NpArticulationFixedTendon(NpArticulationReducedCoordinate* articulation) : PxArticulationFixedTendon(PxConcreteType::eARTICULATION_FIXED_TENDON, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_FIXED_TENDON), mArticulation(articulation) { mLLIndex = 0xffffffff; mHandle = 0xffffffff; } NpArticulationFixedTendon::~NpArticulationFixedTendon() { for (PxU32 i = 0; i < mTendonJoints.size(); ++i) { if (mTendonJoints[i]) { mTendonJoints[i]->~NpArticulationTendonJoint(); if (mTendonJoints[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { PX_FREE(mTendonJoints[i]); } } } } void NpArticulationFixedTendon::release() { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::release() not allowed while the articulation is in a scene. Call will be ignored."); return; } PxArray<NpArticulationFixedTendon*>& fixedTendons = mArticulation->getFixedTendons(); fixedTendons.back()->setHandle(mHandle); fixedTendons.replaceWithLast(mHandle); this->~NpArticulationFixedTendon(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } PxArticulationTendonJoint* NpArticulationFixedTendon::createTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::createTendonJoint() not allowed while the articulation is in the scene. Call will be ignored."); return NULL; } PX_CHECK_AND_RETURN_NULL(link, "PxArticulationFixedTendon::createTendonJoint: Null pointer link provided. Need valid link."); PX_CHECK_AND_RETURN_NULL(&link->getArticulation() == getArticulation(), "PxArticulationFixedTendon::createTendonJoint: Link from another articulation provided. Need valid link from same articulation."); #if PX_CHECKED if (parent) { PX_CHECK_AND_RETURN_NULL(parent->getTendon() == this, "PxArticulationFixedTendon::createTendonJoint: Parent tendon joint from another tendon provided. Need valid parent from same tendon."); PX_CHECK_AND_RETURN_NULL(parent->getLink() != link, "PxArticulationFixedTendon::createTendonJoint :: Error: Parent link and child link are the same link!"); PX_CHECK_AND_RETURN_NULL(parent->getLink()== (&link->getInboundJoint()->getParentArticulationLink()), "PxArticulationFixedTendon::createTendonJoint :: Error: Link referenced by parent tendon joint must be the parent of the child link!"); } #endif void* npTendonJointtMem = PX_ALLOC(sizeof(NpArticulationTendonJoint), "NpArticulationTendonJoint"); PxMarkSerializedMemory(npTendonJointtMem, sizeof(NpArticulationTendonJoint)); NpArticulationTendonJoint* npTendonJoint = PX_PLACEMENT_NEW(npTendonJointtMem, NpArticulationTendonJoint)(parent, axis, coefficient, recipCoefficient, link); if (npTendonJoint) { NpArticulationTendonJoint* parentTendonJoint = static_cast<NpArticulationTendonJoint*>(parent); npTendonJoint->setTendon(this); if (parentTendonJoint) { parentTendonJoint->mChildren.pushBack(npTendonJoint); npTendonJoint->mParent = parent; } else { npTendonJoint->mParent = NULL; } npTendonJoint->mHandle = mTendonJoints.size(); mTendonJoints.pushBack(npTendonJoint); } return npTendonJoint; } PxU32 NpArticulationFixedTendon::getTendonJoints(PxArticulationTendonJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(mArticulation->getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mTendonJoints.begin(), mTendonJoints.size()); } void NpArticulationFixedTendon::setStiffness(const PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >= 0.0f, "PxArticulationTendon::setStiffness: spring coefficient must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getStiffness(); } void NpArticulationFixedTendon::setDamping(const PxReal damping) { PX_CHECK_AND_RETURN(PxIsFinite(damping) && damping >= 0.0f, "PxArticulationTendon::setDamping: damping coefficient must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setDamping(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setDamping(damping); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getDamping() const { NP_READ_CHECK(getNpScene()); return mCore.getDamping(); } void NpArticulationFixedTendon::setLimitStiffness(const PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >=0.f , "PxArticulationTendon::setLimitStiffness: stiffness must have valid value!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setLimitStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimitStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getLimitStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getLimitStiffness(); } void NpArticulationFixedTendon::setRestLength(const PxReal restLength) { PX_CHECK_AND_RETURN(PxIsFinite(restLength) , "PxArticulationTendon::setRestLength: restLength must have valid value!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setRestLength(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setSpringRestLength(restLength); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getRestLength() const { NP_READ_CHECK(getNpScene()); return mCore.getSpringRestLength(); } void NpArticulationFixedTendon::setLimitParameters(const PxArticulationTendonLimit& parameter) { PX_CHECK_AND_RETURN(PxIsFinite(parameter.lowLimit) && PxIsFinite(parameter.highLimit) && (parameter.lowLimit <= parameter.highLimit), "PxArticulationFixedTendon::setLimitParameters: lowLimit and highLimit must have valid values and lowLimit must be less than highLimit!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setLimitParameters(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimitRange(parameter.lowLimit, parameter.highLimit); UPDATE_PVD_PROPERTY } PxArticulationTendonLimit NpArticulationFixedTendon::getLimitParameters() const { NP_READ_CHECK(getNpScene()); PxArticulationTendonLimit parameter; mCore.getLimitRange(parameter.lowLimit, parameter.highLimit); return parameter; } NpArticulationTendonJoint* NpArticulationFixedTendon::getTendonJoint(const PxU32 index) { return mTendonJoints[index]; } PxU32 NpArticulationFixedTendon::getNbTendonJoints() const { return mTendonJoints.size(); } void NpArticulationFixedTendon::setOffset(const PxReal offset, bool autowake) { PX_CHECK_AND_RETURN(PxIsFinite(offset), "PxArticulationTendon::setOffset(): invalid value provided!"); PX_ASSERT(!isAPIWriteForbidden()); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setOffset(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } if (autowake && getNpScene()) mArticulation->autoWakeInternal(); mCore.setOffset(offset); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getOffset(); } PxArticulationReducedCoordinate* physx::NpArticulationFixedTendon::getArticulation() const { return mArticulation; } void NpArticulationTendonJoint::removeChild(NpArticulationTendonJoint* child) { for(PxU32 i = 0; i < mChildren.size(); ++i) { if(mChildren[i] == child) { mChildren.replaceWithLast(i); break; } } }
32,073
C++
34.717149
273
0.775356
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpCheck.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_CHECK_H #define NP_CHECK_H #include "foundation/PxSimpleTypes.h" namespace physx { class NpScene; // RAII wrapper around the PxScene::startRead() method, note that this // object does not acquire any scene locks, it is an error checking only mechanism class NpReadCheck { public: NpReadCheck(const NpScene* scene, const char* functionName); ~NpReadCheck(); private: const NpScene* mScene; const char* mName; PxU32 mErrorCount; }; // RAII wrapper around the PxScene::startWrite() method, note that this // object does not acquire any scene locks, it is an error checking only mechanism class NpWriteCheck { public: NpWriteCheck(NpScene* scene, const char* functionName, bool allowReentry=true); ~NpWriteCheck(); private: NpScene* mScene; const char* mName; bool mAllowReentry; PxU32 mErrorCount; }; #if (PX_DEBUG || PX_CHECKED) // Creates a scoped read check object that detects whether appropriate scene locks // have been acquired and checks if reads/writes overlap, this macro should typically // be placed at the beginning of any const API methods that are not multi-thread safe, // the error conditions checked can be summarized as: // 1. PxSceneFlag::eREQUIRE_RW_LOCK was specified but PxScene::lockRead() was not yet called // 2. Other threads were already writing, or began writing during the object lifetime #define NP_READ_CHECK(npScenePtr) NpReadCheck npReadCheck(static_cast<const NpScene*>(npScenePtr), __FUNCTION__); // Creates a scoped write check object that detects whether appropriate scene locks // have been acquired and checks if reads/writes overlap, this macro should typically // be placed at the beginning of any non-const API methods that are not multi-thread safe. // By default re-entrant write calls by the same thread are allowed, the error conditions // checked can be summarized as: // 1. PxSceneFlag::eREQUIRE_RW_LOCK was specified but PxScene::lockWrite() was not yet called // 2. Other threads were already reading, or began reading during the object lifetime // 3. Other threads were already writing, or began writing during the object lifetime #define NP_WRITE_CHECK(npScenePtr) NpWriteCheck npWriteCheck(npScenePtr, __FUNCTION__); // Creates a scoped write check object that disallows re-entrant writes, this is used by // the NpScene::simulate method to detect when callbacks make write calls to the API #define NP_WRITE_CHECK_NOREENTRY(npScenePtr) NpWriteCheck npWriteCheck(npScenePtr, __FUNCTION__, false); #else #define NP_READ_CHECK(npScenePtr) #define NP_WRITE_CHECK(npScenePtr) #define NP_WRITE_CHECK_NOREENTRY(npScenePtr) #endif /* PT: suggested ordering for Np-level checks & macros: PX_PROFILE_ZONE(...); NP_WRITE_CHECK(...); PX_CHECK_AND_RETURN_XXX(...); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(...); PX_SIMD_GUARD; Current rationale: - profile zone first to include the cost of the checks in the profiling results. - NP_WRITE_CHECK before PX_CHECK macros. I tried both and the DLL size is smaller with NP_WRITE_CHECK macros first. - PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL after PX_CHECK_AND_RETURN macros, because contrary to the others these macros don't vanish in Release builds. So we want to group together NP_WRITE_CHECK and PX_CHECK_AND_RETURN macros (the ones that do vanish). That way we can eventually skip them with a runtime flag. - PX_SIMD_GUARD last. No need to take the guard before the PX_CHECK_SCENE_API are done, it would only generate more guard dtor code when the macro eary exits. */ } #endif
5,267
C
41.829268
120
0.762104
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationJointReducedCoordinate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_ARTICULATION_JOINT_RC_H #define NP_ARTICULATION_JOINT_RC_H #include "PxArticulationJointReducedCoordinate.h" #include "ScArticulationJointCore.h" #include "NpArticulationLink.h" #include "NpBase.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif namespace physx { class NpScene; class NpArticulationLink; class NpArticulationJointReducedCoordinate : public PxArticulationJointReducedCoordinate, public NpBase { public: // PX_SERIALIZATION NpArticulationJointReducedCoordinate(PxBaseFlags baseFlags) : PxArticulationJointReducedCoordinate(baseFlags), NpBase(PxEmpty), mCore(PxEmpty) {} void preExportDataReset() { mCore.preExportDataReset(); } virtual void resolveReferences(PxDeserializationContext& context); static NpArticulationJointReducedCoordinate* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&) {} virtual bool isSubordinate() const { return true; } //~PX_SERIALIZATION NpArticulationJointReducedCoordinate(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame); virtual ~NpArticulationJointReducedCoordinate(); //--------------------------------------------------------------------------------- // PxArticulationJoint implementation //--------------------------------------------------------------------------------- virtual void setJointType(PxArticulationJointType::Enum jointType); virtual PxArticulationJointType::Enum getJointType() const; virtual void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion); virtual PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const; virtual void setFrictionCoefficient(const PxReal coefficient); virtual PxReal getFrictionCoefficient() const; virtual void setMaxJointVelocity(const PxReal maxJointV); virtual PxReal getMaxJointVelocity() const; virtual void setLimitParams(PxArticulationAxis::Enum axis, const PxArticulationLimit& pair); virtual PxArticulationLimit getLimitParams(PxArticulationAxis::Enum axis) const; virtual void setDriveParams(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive); virtual PxArticulationDrive getDriveParams(PxArticulationAxis::Enum axis) const; virtual void setDriveTarget(PxArticulationAxis::Enum axis, const PxReal target, bool autowake = true); virtual PxReal getDriveTarget(PxArticulationAxis::Enum axis) const; virtual void setDriveVelocity(PxArticulationAxis::Enum axis, const PxReal targetVel, bool autowake = true); virtual PxReal getDriveVelocity(PxArticulationAxis::Enum axis) const; virtual void setArmature(PxArticulationAxis::Enum axis, const PxReal armature); virtual PxReal getArmature(PxArticulationAxis::Enum axis) const; virtual void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos); virtual PxReal getJointPosition(PxArticulationAxis::Enum axis) const; virtual void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel); virtual PxReal getJointVelocity(PxArticulationAxis::Enum axis) const; void release(); PX_FORCE_INLINE Sc::ArticulationJointCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpArticulationJointReducedCoordinate, mCore); } PX_INLINE void scSetParentPose(const PxTransform& v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setParentPose(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetChildPose(const PxTransform& v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setChildPose(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetJointType(PxArticulationJointType::Enum v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setJointType(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetFrictionCoefficient(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setFrictionCoefficient(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetMaxJointVelocity(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMaxJointVelocity(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& pair) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimit(axis, pair); UPDATE_PVD_PROPERTY } PX_INLINE void scSetDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setDrive(axis, drive); UPDATE_PVD_PROPERTY } PX_INLINE void scSetDriveTarget(PxArticulationAxis::Enum axis, PxReal targetP) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setTargetP(axis, targetP); UPDATE_PVD_PROPERTY } PX_INLINE void scSetDriveVelocity(PxArticulationAxis::Enum axis, PxReal targetP) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setTargetV(axis, targetP); UPDATE_PVD_PROPERTY } PX_INLINE void scSetArmature(PxArticulationAxis::Enum axis, PxReal armature) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setArmature(axis, armature); UPDATE_PVD_PROPERTY } PX_INLINE void scSetMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMotion(axis, motion); UPDATE_PVD_PROPERTY } PX_INLINE void scSetJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setJointPosition(axis, jointPos); UPDATE_PVD_PROPERTY } PX_INLINE void scSetJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setJointVelocity(axis, jointVel); UPDATE_PVD_PROPERTY } virtual PxArticulationLink& getParentArticulationLink() const { return *mParent; } virtual PxArticulationLink& getChildArticulationLink() const { return *mChild; } virtual PxTransform getParentPose() const; virtual void setParentPose(const PxTransform& t); virtual PxTransform getChildPose() const; virtual void setChildPose(const PxTransform& t); PX_INLINE const NpArticulationLink& getParent() const { return *mParent; } PX_INLINE NpArticulationLink& getParent() { return *mParent; } PX_INLINE const NpArticulationLink& getChild() const { return *mChild; } PX_INLINE NpArticulationLink& getChild() { return *mChild; } Sc::ArticulationJointCore mCore; NpArticulationLink* mParent; NpArticulationLink* mChild; #if PX_CHECKED private: bool isValidMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion); #endif }; } #endif
8,893
C
38.353982
168
0.727988
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneClient.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_SCENE_PVD_CLIENT_H #define NP_SCENE_PVD_CLIENT_H #include "PxPhysXConfig.h" #if PX_SUPPORT_PVD #include "foundation/PxStrideIterator.h" #include "pvd/PxPvdTransport.h" #include "pvd/PxPvdSceneClient.h" #include "PvdMetaDataPvdBinding.h" #include "foundation/PxBitMap.h" #include "PxPvdClient.h" #include "PxPvdUserRenderer.h" #include "PsPvd.h" #include "PxsMaterialCore.h" #include "PxsFEMSoftBodyMaterialCore.h" #include "PxsFEMClothMaterialCore.h" #include "PxsPBDMaterialCore.h" #include "PxsFLIPMaterialCore.h" #include "PxsMPMMaterialCore.h" namespace physx { class PxActor; class PxArticulationLink; class PxRenderBuffer; class NpConstraint; class NpShape; class NpAggregate; class NpRigidStatic; class NpRigidDynamic; class NpArticulationLink; class NpArticulationJointReducedCoordinate; class NpArticulationReducedCoordinate; class NpArticulationSpatialTendon; class NpArticulationFixedTendon; class NpArticulationSensor; class NpActor; class NpScene; #if PX_SUPPORT_GPU_PHYSX class NpSoftBody; class NpFEMCloth; class NpPBDParticleSystem; class NpFLIPParticleSystem; class NpMPMParticleSystem; class NpHairSystem; #endif namespace Sc { class ConstraintCore; } namespace Vd { class PvdSceneClient : public PxPvdSceneClient, public PvdClient, public PvdVisualizer { PX_NOCOPY(PvdSceneClient) public: PvdSceneClient(NpScene& scene); virtual ~PvdSceneClient(); // PxPvdSceneClient virtual void setScenePvdFlag(PxPvdSceneFlag::Enum flag, bool value); virtual void setScenePvdFlags(PxPvdSceneFlags flags) { mFlags = flags; } virtual PxPvdSceneFlags getScenePvdFlags() const { return mFlags; } virtual void updateCamera(const char* name, const PxVec3& origin, const PxVec3& up, const PxVec3& target); virtual void drawPoints(const PxDebugPoint* points, PxU32 count); virtual void drawLines(const PxDebugLine* lines, PxU32 count); virtual void drawTriangles(const PxDebugTriangle* triangles, PxU32 count); virtual void drawText(const PxDebugText& text); virtual PvdClient* getClientInternal() { return this; } //~PxPvdSceneClient // pvdClient virtual PvdDataStream* getDataStream() { return mPvdDataStream; } virtual bool isConnected() const { return mIsConnected; } virtual void onPvdConnected(); virtual void onPvdDisconnected(); virtual void flush() {} //~pvdClient PX_FORCE_INLINE bool checkPvdDebugFlag() const { return mIsConnected && (mPvd->getInstrumentationFlags() & PxPvdInstrumentationFlag::eDEBUG); } PX_FORCE_INLINE PxPvdSceneFlags getScenePvdFlagsFast() const { return mFlags; } PX_FORCE_INLINE void setPsPvd(PsPvd* pvd) { mPvd = pvd; } void frameStart(PxReal simulateElapsedTime); void frameEnd(); void updatePvdProperties(); void releasePvdInstance(); void createPvdInstance (const PxActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void updatePvdProperties(const PxActor* actor); void releasePvdInstance (const PxActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void createPvdInstance (const NpActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void updatePvdProperties(const NpActor* actor); void releasePvdInstance (const NpActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void createPvdInstance (const NpRigidDynamic* body); void createPvdInstance (const NpArticulationLink* body); void updatePvdProperties (const NpRigidDynamic* body); void updatePvdProperties (const NpArticulationLink* body); void releasePvdInstance (const NpRigidDynamic* body); void releasePvdInstance (const NpArticulationLink* body); void updateBodyPvdProperties(const NpActor* body); void updateKinematicTarget (const NpActor* body, const PxTransform& p); void createPvdInstance (const NpRigidStatic* rigidStatic); void updatePvdProperties (const NpRigidStatic* rigidStatic); void releasePvdInstance (const NpRigidStatic* rigidStatic); void createPvdInstance (const NpConstraint* constraint); void updatePvdProperties(const NpConstraint* constraint); void releasePvdInstance (const NpConstraint* constraint); void createPvdInstance (const NpArticulationReducedCoordinate* articulation); void updatePvdProperties(const NpArticulationReducedCoordinate* articulation); void releasePvdInstance (const NpArticulationReducedCoordinate* articulation); void createPvdInstance (const NpArticulationJointReducedCoordinate* articulationJoint); void updatePvdProperties(const NpArticulationJointReducedCoordinate* articulationJoint); void releasePvdInstance (const NpArticulationJointReducedCoordinate* articulationJoint); void createPvdInstance(const NpArticulationSpatialTendon* articulationTendon); void updatePvdProperties(const NpArticulationSpatialTendon* articulationTendon); void releasePvdInstance(const NpArticulationSpatialTendon* articulationTendon); void createPvdInstance(const NpArticulationFixedTendon* articulationTendon); void updatePvdProperties(const NpArticulationFixedTendon* articulationTendon); void releasePvdInstance(const NpArticulationFixedTendon* articulationTendon); void createPvdInstance(const NpArticulationSensor* sensor); void updatePvdProperties(const NpArticulationSensor* sensor); void releasePvdInstance(const NpArticulationSensor* sensor); /////////////////////////////////////////////////////////////////////////// void createPvdInstance (const PxsMaterialCore* materialCore); void updatePvdProperties(const PxsMaterialCore* materialCore); void releasePvdInstance (const PxsMaterialCore* materialCore); void createPvdInstance (const PxsFEMSoftBodyMaterialCore* materialCore); void updatePvdProperties(const PxsFEMSoftBodyMaterialCore* materialCore); void releasePvdInstance (const PxsFEMSoftBodyMaterialCore* materialCore); void createPvdInstance (const PxsFEMClothMaterialCore* materialCore); void updatePvdProperties(const PxsFEMClothMaterialCore* materialCore); void releasePvdInstance (const PxsFEMClothMaterialCore* materialCore); void createPvdInstance (const PxsPBDMaterialCore* materialCore); void updatePvdProperties(const PxsPBDMaterialCore* materialCore); void releasePvdInstance (const PxsPBDMaterialCore* materialCore); void createPvdInstance (const PxsFLIPMaterialCore* materialCore); void updatePvdProperties(const PxsFLIPMaterialCore* materialCore); void releasePvdInstance (const PxsFLIPMaterialCore* materialCore); void createPvdInstance (const PxsMPMMaterialCore* materialCore); void updatePvdProperties(const PxsMPMMaterialCore* materialCore); void releasePvdInstance (const PxsMPMMaterialCore* materialCore); /////////////////////////////////////////////////////////////////////////// void createPvdInstance (const NpShape* shape, PxActor& owner); void updateMaterials (const NpShape* shape); void updatePvdProperties (const NpShape* shape); void releaseAndRecreateGeometry (const NpShape* shape); void releasePvdInstance (const NpShape* shape, PxActor& owner); void addBodyAndShapesToPvd (NpRigidDynamic& b); void addStaticAndShapesToPvd (NpRigidStatic& s); void createPvdInstance (const NpAggregate* aggregate); void updatePvdProperties (const NpAggregate* aggregate); void attachAggregateActor (const NpAggregate* aggregate, NpActor* actor); void detachAggregateActor (const NpAggregate* aggregate, NpActor* actor); void releasePvdInstance (const NpAggregate* aggregate); #if PX_SUPPORT_GPU_PHYSX void createPvdInstance(const NpSoftBody* softBody); void updatePvdProperties(const NpSoftBody* softBody); void attachAggregateActor(const NpSoftBody* softBody, NpActor* actor); void detachAggregateActor(const NpSoftBody* softBody, NpActor* actor); void releasePvdInstance(const NpSoftBody* softBody); void createPvdInstance(const NpFEMCloth* femCloth); void updatePvdProperties(const NpFEMCloth* femCloth); void attachAggregateActor(const NpFEMCloth* femCloth, NpActor* actor); void detachAggregateActor(const NpFEMCloth* femCloth, NpActor* actor); void releasePvdInstance(const NpFEMCloth* femCloth); void createPvdInstance(const NpPBDParticleSystem* particleSystem); void updatePvdProperties(const NpPBDParticleSystem* particleSystem); void attachAggregateActor(const NpPBDParticleSystem* particleSystem, NpActor* actor); void detachAggregateActor(const NpPBDParticleSystem* particleSystem, NpActor* actor); void releasePvdInstance(const NpPBDParticleSystem* particleSystem); void createPvdInstance(const NpFLIPParticleSystem* particleSystem); void updatePvdProperties(const NpFLIPParticleSystem* particleSystem); void attachAggregateActor(const NpFLIPParticleSystem* particleSystem, NpActor* actor); void detachAggregateActor(const NpFLIPParticleSystem* particleSystem, NpActor* actor); void releasePvdInstance(const NpFLIPParticleSystem* particleSystem); void createPvdInstance(const NpMPMParticleSystem* particleSystem); void updatePvdProperties(const NpMPMParticleSystem* particleSystem); void attachAggregateActor(const NpMPMParticleSystem* particleSystem, NpActor* actor); void detachAggregateActor(const NpMPMParticleSystem* particleSystem, NpActor* actor); void releasePvdInstance(const NpMPMParticleSystem* particleSystem); void createPvdInstance(const NpHairSystem* hairSystem); void updatePvdProperties(const NpHairSystem* hairSystem); void attachAggregateActor(const NpHairSystem* hairSystem, NpActor* actor); void detachAggregateActor(const NpHairSystem* hairSystem, NpActor* actor); void releasePvdInstance(const NpHairSystem* hairSystem); #endif void originShift(PxVec3 shift); void updateJoints(); void updateContacts(); void updateSceneQueries(); // PvdVisualizer void visualize(PxArticulationLink& link); void visualize(const PxRenderBuffer& debugRenderable); private: void sendEntireScene(); void updateConstraint(const Sc::ConstraintCore& scConstraint, PxU32 updateType); PxPvdSceneFlags mFlags; PsPvd* mPvd; NpScene& mScene; PvdDataStream* mPvdDataStream; PvdMetaDataBinding mMetaDataBinding; PvdUserRenderer* mUserRender; RendererEventClient* mRenderClient; bool mIsConnected; }; } // pvd } // physx #endif // PX_SUPPORT_PVD #endif // NP_SCENE_PVD_CLIENT_H
12,161
C
41.673684
147
0.794096
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpScene.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_SCENE_H #define NP_SCENE_H #define NEW_DIRTY_SHADERS_CODE #include "foundation/PxUserAllocated.h" #include "foundation/PxHashSet.h" #include "foundation/PxSync.h" #include "foundation/PxArray.h" #include "foundation/PxThread.h" #include "PxPhysXConfig.h" #include "CmRenderBuffer.h" #include "CmIDPool.h" #if PX_SUPPORT_GPU_PHYSX #include "device/PhysXIndicator.h" #endif #include "NpSceneQueries.h" #include "NpSceneAccessor.h" #include "NpPruningStructure.h" #if PX_SUPPORT_PVD #include "PxPhysics.h" #include "NpPvdSceneClient.h" #endif #include "ScScene.h" namespace physx { namespace Sc { class Joint; class ConstraintBreakEvent; } namespace Sq { class PrunerManager; } class PhysicsThread; class NpMaterial; class NpScene; class NpArticulationReducedCoordinate; class NpAggregate; class NpObjectFactory; class NpRigidStatic; class NpRigidDynamic; class NpConstraint; class NpArticulationLink; class NpArticulationJointReducedCoordinate; class NpArticulationAttachment; class NpArticulationTendonJoint; class NpArticulationSpatialTendon; class NpArticulationFixedTendon; class NpArticulationSensor; class NpShapeManager; class NpBatchQuery; class NpActor; class NpShape; class NpPhysics; #if PX_SUPPORT_GPU_PHYSX class NpSoftBody; class NpFEMCloth; class NpHairSystem; class NpPBDParticleSystem; class NpFLIPParticleSystem; class NpMPMParticleSystem; class NpFEMSoftBodyMaterial; class NpFEMClothMaterial; class NpPBDMaterial; class NpFLIPMaterial; class NpMPMMaterial; #endif class NpContactCallbackTask : public physx::PxLightCpuTask { NpScene* mScene; const PxContactPairHeader* mContactPairHeaders; uint32_t mNbContactPairHeaders; public: void setData(NpScene* scene, const PxContactPairHeader* contactPairHeaders, const uint32_t nbContactPairHeaders); virtual void run(); virtual const char* getName() const { return "NpContactCallbackTask"; } }; class NpScene : public NpSceneAccessor, public PxUserAllocated { //virtual interfaces: PX_NOCOPY(NpScene) public: virtual void release(); virtual void setFlag(PxSceneFlag::Enum flag, bool value); virtual PxSceneFlags getFlags() const; virtual void setName(const char* name); virtual const char* getName() const; // implement PxScene: virtual void setGravity(const PxVec3&); virtual PxVec3 getGravity() const; virtual void setBounceThresholdVelocity(const PxReal t); virtual PxReal getBounceThresholdVelocity() const; virtual void setMaxBiasCoefficient(const PxReal t); virtual PxReal getMaxBiasCoefficient() const; virtual void setFrictionOffsetThreshold(const PxReal t); virtual PxReal getFrictionOffsetThreshold() const; virtual void setFrictionCorrelationDistance(const PxReal t); virtual PxReal getFrictionCorrelationDistance() const; virtual void setLimits(const PxSceneLimits& limits); virtual PxSceneLimits getLimits() const; virtual bool addActor(PxActor& actor, const PxBVH* bvh); virtual void removeActor(PxActor& actor, bool wakeOnLostTouch); virtual PxU32 getNbConstraints() const; virtual PxU32 getConstraints(PxConstraint** buffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual bool addArticulation(PxArticulationReducedCoordinate&); virtual void removeArticulation(PxArticulationReducedCoordinate&, bool wakeOnLostTouch); virtual PxU32 getNbArticulations() const; virtual PxU32 getArticulations(PxArticulationReducedCoordinate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxU32 getNbSoftBodies() const; virtual PxU32 getSoftBodies(PxSoftBody** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getNbParticleSystems(PxParticleSolverType::Enum type) const; virtual PxU32 getParticleSystems(PxParticleSolverType::Enum type, PxParticleSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getNbFEMCloths() const; virtual PxU32 getFEMCloths(PxFEMCloth** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getNbHairSystems() const; virtual PxU32 getHairSystems(PxHairSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; // Aggregates virtual bool addAggregate(PxAggregate&); virtual void removeAggregate(PxAggregate&, bool wakeOnLostTouch); virtual PxU32 getNbAggregates() const; virtual PxU32 getAggregates(PxAggregate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual bool addCollection(const PxCollection& collection); // Groups virtual void setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance); virtual PxDominanceGroupPair getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const; // Actors virtual PxU32 getNbActors(PxActorTypeFlags types) const; virtual PxU32 getActors(PxActorTypeFlags types, PxActor** buffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxActor** getActiveActors(PxU32& nbActorsOut); // Run virtual void getSimulationStatistics(PxSimulationStatistics& s) const; // Multiclient virtual PxClientID createClient(); // FrictionModel virtual PxFrictionType::Enum getFrictionType() const; // Callbacks virtual void setSimulationEventCallback(PxSimulationEventCallback* callback); virtual PxSimulationEventCallback* getSimulationEventCallback() const; virtual void setContactModifyCallback(PxContactModifyCallback* callback); virtual PxContactModifyCallback* getContactModifyCallback() const; virtual void setCCDContactModifyCallback(PxCCDContactModifyCallback* callback); virtual PxCCDContactModifyCallback* getCCDContactModifyCallback() const; virtual void setBroadPhaseCallback(PxBroadPhaseCallback* callback); virtual PxBroadPhaseCallback* getBroadPhaseCallback() const; //CCD virtual void setCCDMaxPasses(PxU32 ccdMaxPasses); virtual PxU32 getCCDMaxPasses() const; virtual void setCCDMaxSeparation(const PxReal t); virtual PxReal getCCDMaxSeparation() const; virtual void setCCDThreshold(const PxReal t); virtual PxReal getCCDThreshold() const; // Collision filtering virtual void setFilterShaderData(const void* data, PxU32 dataSize); virtual const void* getFilterShaderData() const; virtual PxU32 getFilterShaderDataSize() const; virtual PxSimulationFilterShader getFilterShader() const; virtual PxSimulationFilterCallback* getFilterCallback() const; virtual bool resetFiltering(PxActor& actor); virtual bool resetFiltering(PxRigidActor& actor, PxShape*const* shapes, PxU32 shapeCount); virtual PxPairFilteringMode::Enum getKinematicKinematicFilteringMode() const; virtual PxPairFilteringMode::Enum getStaticKinematicFilteringMode() const; // Get Physics SDK virtual PxPhysics& getPhysics(); // new API methods virtual bool simulate(PxReal elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation); virtual bool advance(physx::PxBaseTask* completionTask); virtual bool collide(PxReal elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation = true); virtual bool checkResults(bool block); virtual bool checkCollision(bool block); virtual bool fetchCollision(bool block); virtual bool fetchResults(bool block, PxU32* errorState); virtual bool fetchResultsStart(const PxContactPairHeader*& contactPairs, PxU32& nbContactPairs, bool block = false); virtual void processCallbacks(physx::PxBaseTask* continuation); virtual void fetchResultsFinish(PxU32* errorState = 0); virtual void flush(bool sendPendingReports) { flushSimulation(sendPendingReports); } virtual void flushSimulation(bool sendPendingReports); virtual const PxRenderBuffer& getRenderBuffer(); virtual void setSolverBatchSize(PxU32 solverBatchSize); virtual PxU32 getSolverBatchSize(void) const; virtual void setSolverArticulationBatchSize(PxU32 solverBatchSize); virtual PxU32 getSolverArticulationBatchSize(void) const; virtual bool setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value); virtual PxReal getVisualizationParameter(PxVisualizationParameter::Enum param) const; virtual void setVisualizationCullingBox(const PxBounds3& box); virtual PxBounds3 getVisualizationCullingBox() const; virtual PxTaskManager* getTaskManager() const { return mTaskManager; } void checkBeginWrite() const {} virtual PxCudaContextManager* getCudaContextManager() { return mCudaContextManager; } virtual void setNbContactDataBlocks(PxU32 numBlocks); virtual PxU32 getNbContactDataBlocksUsed() const; virtual PxU32 getMaxNbContactDataBlocksUsed() const; virtual PxU32 getContactReportStreamBufferSize() const; virtual PxU32 getTimestamp() const; virtual PxCpuDispatcher* getCpuDispatcher() const; virtual PxCudaContextManager* getCudaContextManager() const; virtual PxBroadPhaseType::Enum getBroadPhaseType() const; virtual bool getBroadPhaseCaps(PxBroadPhaseCaps& caps) const; virtual PxU32 getNbBroadPhaseRegions() const; virtual PxU32 getBroadPhaseRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxU32 addBroadPhaseRegion(const PxBroadPhaseRegion& region, bool populateRegion); virtual bool removeBroadPhaseRegion(PxU32 handle); virtual bool addActors(PxActor*const* actors, PxU32 nbActors); virtual bool addActors(const PxPruningStructure& prunerStructure); virtual void removeActors(PxActor*const* actors, PxU32 nbActors, bool wakeOnLostTouch); virtual void lockRead(const char* file=NULL, PxU32 line=0); virtual void unlockRead(); virtual void lockWrite(const char* file=NULL, PxU32 line=0); virtual void unlockWrite(); virtual PxReal getWakeCounterResetValue() const; virtual void shiftOrigin(const PxVec3& shift); virtual PxPvdSceneClient* getScenePvdClient(); virtual void copyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbCopyArticulations, CUevent copyEvent); virtual void applyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbUpdatedArticulations, CUevent waitEvent, CUevent signalEvent); virtual void updateArticulationsKinematic(CUevent signalEvent); virtual void copyContactData(void* data, const PxU32 numContactPatches, void* numContactPairs, CUevent copyEvent); virtual void copySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbCopySoftBodies, const PxU32 maxSize, CUevent copyEvent); virtual void applySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbUpdatedSoftBodies, const PxU32 maxSize, CUevent applyEvent, CUevent signalEvent); virtual void copyBodyData(PxGpuBodyData* data, PxGpuActorPair* index, const PxU32 nbCopyActors, CUevent copyEvent); virtual void applyActorData(void* data, PxGpuActorPair* index, PxActorCacheFlag::Enum flag, const PxU32 nbUpdatedActors, CUevent waitEvent, CUevent signalEvent); virtual void evaluateSDFDistances(const PxU32* sdfShapeIds, const PxU32 nbShapes, const PxVec4* samplePointsConcatenated, const PxU32* samplePointCountPerShape, const PxU32 maxPointCount, PxVec4* localGradientAndSDFConcatenated, CUevent event); virtual void computeDenseJacobians(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void computeGeneralizedMassMatrices(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void computeGeneralizedGravityForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void computeCoriolisAndCentrifugalForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void applyParticleBufferData(const PxU32* indices, const PxGpuParticleBufferIndexPair* bufferIndexPairs, const PxParticleBufferFlags* flags, PxU32 nbUpdatedBuffers, CUevent waitEvent, CUevent signalEvent); virtual PxSolverType::Enum getSolverType() const; // NpSceneAccessor virtual PxsSimulationController* getSimulationController(); virtual void setActiveActors(PxActor** actors, PxU32 nbActors); virtual PxActor** getFrozenActors(PxU32& nbActorsOut); virtual void setFrozenActorFlag(const bool buildFrozenActors); virtual void forceSceneQueryRebuild(); virtual void frameEnd(); //~NpSceneAccessor // PxSceneQuerySystemBase virtual void setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint); virtual PxU32 getDynamicTreeRebuildRateHint() const; virtual void forceRebuildDynamicTree(PxU32 prunerIndex); virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode); virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const; virtual PxU32 getStaticTimestamp() const; virtual void flushUpdates(); virtual bool raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, // Ray data PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, // GeomObject data const PxVec3& unitDir, const PxReal distance, // Ray data PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const; virtual bool overlap( const PxGeometry& geometry, const PxTransform& transform, // GeomObject data PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; //~PxSceneQuerySystemBase // PxSceneSQSystem virtual PxPruningStructureType::Enum getStaticStructure() const; virtual PxPruningStructureType::Enum getDynamicStructure() const; virtual void sceneQueriesUpdate(physx::PxBaseTask* completionTask, bool controlSimulation); virtual bool checkQueries(bool block); virtual bool fetchQueries(bool block); //~PxSceneSQSystem public: NpScene(const PxSceneDesc& desc, NpPhysics&); ~NpScene(); PX_FORCE_INLINE NpSceneQueries& getNpSQ() { return mNpSQ; } PX_FORCE_INLINE const NpSceneQueries& getNpSQ() const { return mNpSQ; } PX_FORCE_INLINE PxSceneQuerySystem& getSQAPI() { return mNpSQ.getSQAPI(); } PX_FORCE_INLINE const PxSceneQuerySystem& getSQAPI() const { return mNpSQ.getSQAPI(); } PX_FORCE_INLINE PxU64 getContextId() const { return PxU64(this); } PX_FORCE_INLINE PxTaskManager* getTaskManagerFast() const { return mTaskManager; } PX_FORCE_INLINE Sc::SimulationStage::Enum getSimulationStage() const { return mScene.getSimulationStage(); } PX_FORCE_INLINE void setSimulationStage(Sc::SimulationStage::Enum stage) { mScene.setSimulationStage(stage); } bool addActorInternal(PxActor& actor, const PxBVH* bvh); void removeActorInternal(PxActor& actor, bool wakeOnLostTouch, bool removeFromAggregate); bool addActorsInternal(PxActor*const* PX_RESTRICT actors, PxU32 nbActors, const Sq::PruningStructure* ps = NULL); bool addArticulationInternal(PxArticulationReducedCoordinate&); void removeArticulationInternal(PxArticulationReducedCoordinate&, bool wakeOnLostTouch, bool removeFromAggregate); // materials void addMaterial(const NpMaterial& mat); void updateMaterial(const NpMaterial& mat); void removeMaterial(const NpMaterial& mat); #if PX_SUPPORT_GPU_PHYSX void addMaterial(const NpFEMSoftBodyMaterial& mat); void updateMaterial(const NpFEMSoftBodyMaterial& mat); void removeMaterial(const NpFEMSoftBodyMaterial& mat); void addMaterial(const NpFEMClothMaterial& mat); void updateMaterial(const NpFEMClothMaterial& mat); void removeMaterial(const NpFEMClothMaterial& mat); void addMaterial(const NpPBDMaterial& mat); void updateMaterial(const NpPBDMaterial& mat); void removeMaterial(const NpPBDMaterial& mat); void addMaterial(const NpFLIPMaterial& mat); void updateMaterial(const NpFLIPMaterial& mat); void removeMaterial(const NpFLIPMaterial& mat); void addMaterial(const NpMPMMaterial& mat); void updateMaterial(const NpMPMMaterial& mat); void removeMaterial(const NpMPMMaterial& mat); #endif void executeScene(PxBaseTask* continuation); void executeCollide(PxBaseTask* continuation); void executeAdvance(PxBaseTask* continuation); void constraintBreakEventNotify(PxConstraint *const *constraints, PxU32 count); bool loadFromDesc(const PxSceneDesc&); template<typename T> void removeFromRigidActorList(T&); void removeFromRigidDynamicList(NpRigidDynamic&); void removeFromRigidStaticList(NpRigidStatic&); PX_FORCE_INLINE void removeFromArticulationList(PxArticulationReducedCoordinate&); PX_FORCE_INLINE void removeFromSoftBodyList(PxSoftBody&); PX_FORCE_INLINE void removeFromFEMClothList(PxFEMCloth&); PX_FORCE_INLINE void removeFromParticleSystemList(PxPBDParticleSystem&); PX_FORCE_INLINE void removeFromParticleSystemList(PxFLIPParticleSystem&); PX_FORCE_INLINE void removeFromParticleSystemList(PxMPMParticleSystem&); PX_FORCE_INLINE void removeFromHairSystemList(PxHairSystem&); PX_FORCE_INLINE void removeFromAggregateList(PxAggregate&); #ifdef NEW_DIRTY_SHADERS_CODE void addDirtyConstraint(NpConstraint* constraint); #endif void addToConstraintList(PxConstraint&); void removeFromConstraintList(PxConstraint&); void addArticulationLink(NpArticulationLink& link); void addArticulationLinkBody(NpArticulationLink& link); void addArticulationLinkConstraint(NpArticulationLink& link); void removeArticulationLink(NpArticulationLink& link, bool wakeOnLostTouch); void addArticulationAttachment(NpArticulationAttachment& attachment); void removeArticulationAttachment(NpArticulationAttachment& attachment); void addArticulationTendonJoint(NpArticulationTendonJoint& joint); void removeArticulationTendonJoint(NpArticulationTendonJoint& joint); void removeArticulationTendons(PxArticulationReducedCoordinate& articulation); void removeArticulationSensors(PxArticulationReducedCoordinate& articulation); struct StartWriteResult { enum Enum { eOK, eNO_LOCK, eIN_FETCHRESULTS, eRACE_DETECTED }; }; StartWriteResult::Enum startWrite(bool allowReentry); void stopWrite(bool allowReentry); bool startRead() const; void stopRead() const; PxU32 getReadWriteErrorCount() const { return PxU32(mConcurrentErrorCount); } #if PX_CHECKED void checkPositionSanity(const PxRigidActor& a, const PxTransform& pose, const char* fnName) const; #endif #if PX_SUPPORT_GPU_PHYSX void updatePhysXIndicator(); #else PX_FORCE_INLINE void updatePhysXIndicator() {} #endif void scAddAggregate(NpAggregate&); void scRemoveAggregate(NpAggregate&); void scSwitchRigidToNoSim(NpActor&); void scSwitchRigidFromNoSim(NpActor&); #if PX_SUPPORT_PVD PX_FORCE_INLINE Vd::PvdSceneClient& getScenePvdClientInternal() { return mScenePvdClient; } PX_FORCE_INLINE const Vd::PvdSceneClient& getScenePvdClientInternal() const { return mScenePvdClient; } #endif PX_FORCE_INLINE bool isAPIReadForbidden() const { return mIsAPIReadForbidden; } PX_FORCE_INLINE void setAPIReadToForbidden() { mIsAPIReadForbidden = true; } PX_FORCE_INLINE void setAPIReadToAllowed() { mIsAPIReadForbidden = false; } PX_FORCE_INLINE bool isCollisionPhaseActive() const { return mScene.isCollisionPhaseActive(); } PX_FORCE_INLINE bool isAPIWriteForbidden() const { return mIsAPIWriteForbidden; } PX_FORCE_INLINE void setAPIWriteToForbidden() { mIsAPIWriteForbidden = true; } PX_FORCE_INLINE void setAPIWriteToAllowed() { mIsAPIWriteForbidden = false; } PX_FORCE_INLINE const Sc::Scene& getScScene() const { return mScene; } PX_FORCE_INLINE Sc::Scene& getScScene() { return mScene; } PX_FORCE_INLINE PxU32 getFlagsFast() const { return mScene.getFlags(); } PX_FORCE_INLINE PxReal getWakeCounterResetValueInternal() const { return mWakeCounterResetValue; } PX_FORCE_INLINE bool isDirectGPUAPIInitialized() { return mScene.isDirectGPUAPIInitialized(); } // PT: TODO: consider merging the "sc" methods with the np ones, as we did for constraints void scAddActor(NpRigidStatic&, bool noSim, PxBounds3* uninflatedBounds, const Gu::BVH* bvh); void scRemoveActor(NpRigidStatic&, bool wakeOnLostTouch, bool noSim); void scAddActor(NpRigidDynamic&, bool noSim, PxBounds3* uninflatedBounds, const Gu::BVH* bvh); void scRemoveActor(NpRigidDynamic&, bool wakeOnLostTouch, bool noSim); void scAddActor(NpArticulationLink&, bool noSim, PxBounds3* uninflatedBounds, const Gu::BVH* bvh); void scRemoveActor(NpArticulationLink&, bool wakeOnLostTouch, bool noSim); #if PX_SUPPORT_GPU_PHYSX void scAddSoftBody(NpSoftBody&); void scRemoveSoftBody(NpSoftBody&); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void scAddFEMCloth(NpScene* npScene, NpFEMCloth&); void scRemoveFEMCloth(NpFEMCloth&); #endif void scAddParticleSystem(NpPBDParticleSystem&); void scRemoveParticleSystem(NpPBDParticleSystem&); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void scAddParticleSystem(NpFLIPParticleSystem&); void scRemoveParticleSystem(NpFLIPParticleSystem&); void scAddParticleSystem(NpMPMParticleSystem&); void scRemoveParticleSystem(NpMPMParticleSystem&); #endif void scAddHairSystem(NpHairSystem&); void scRemoveHairSystem(NpHairSystem&); #endif void scAddArticulation(NpArticulationReducedCoordinate&); void scRemoveArticulation(NpArticulationReducedCoordinate&); void scAddArticulationJoint(NpArticulationJointReducedCoordinate&); void scRemoveArticulationJoint(NpArticulationJointReducedCoordinate&); void scAddArticulationSpatialTendon(NpArticulationSpatialTendon&); void scRemoveArticulationSpatialTendon(NpArticulationSpatialTendon&); void scAddArticulationFixedTendon(NpArticulationFixedTendon&); void scRemoveArticulationFixedTendon(NpArticulationFixedTendon&); void scAddArticulationSensor(NpArticulationSensor&); void scRemoveArticulationSensor(NpArticulationSensor&); void createInOmniPVD(const PxSceneDesc& desc); PX_FORCE_INLINE void updatePvdProperties() { #if PX_SUPPORT_PVD // PT: TODO: shouldn't we test PxPvdInstrumentationFlag::eDEBUG here? if(mScenePvdClient.isConnected()) mScenePvdClient.updatePvdProperties(); #endif } void updateConstants(const PxArray<NpConstraint*>& constraints); virtual PxgDynamicsMemoryConfig getGpuDynamicsConfig() const { return mGpuDynamicsConfig; } private: bool checkResultsInternal(bool block); bool checkCollisionInternal(bool block); bool checkSceneQueriesInternal(bool block); bool simulateOrCollide(PxReal elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation, const char* invalidCallMsg, Sc::SimulationStage::Enum simStage); bool addRigidStatic(NpRigidStatic& , const Gu::BVH* bvh, const Sq::PruningStructure* ps = NULL); void removeRigidStatic(NpRigidStatic&, bool wakeOnLostTouch, bool removeFromAggregate); bool addRigidDynamic(NpRigidDynamic& , const Gu::BVH* bvh, const Sq::PruningStructure* ps = NULL); void removeRigidDynamic(NpRigidDynamic&, bool wakeOnLostTouch, bool removeFromAggregate); bool addSoftBody(PxSoftBody&); void removeSoftBody(PxSoftBody&, bool wakeOnLostTouch); bool addParticleSystem(PxParticleSystem& particleSystem); void removeParticleSystem(PxParticleSystem& particleSystem, bool wakeOnLostTouch); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION bool addFEMCloth(PxFEMCloth&); void removeFEMCloth(PxFEMCloth&, bool wakeOnLostTouch); bool addHairSystem(PxHairSystem&); void removeHairSystem(PxHairSystem&, bool wakeOnLostTouch); #endif void visualize(); void updateDirtyShaders(); void fetchResultsPreContactCallbacks(); void fetchResultsPostContactCallbacks(); void fetchResultsParticleSystem(); bool addSpatialTendonInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim); bool addFixedTendonInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim); bool addArticulationSensorInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim); void syncSQ(); void sceneQueriesStaticPrunerUpdate(PxBaseTask* continuation); void sceneQueriesDynamicPrunerUpdate(PxBaseTask* continuation); void syncMaterialEvents(); NpSceneQueries mNpSQ; PxPruningStructureType::Enum mPrunerType[2]; typedef Cm::DelegateTask<NpScene, &NpScene::sceneQueriesStaticPrunerUpdate> SceneQueriesStaticPrunerUpdate; typedef Cm::DelegateTask<NpScene, &NpScene::sceneQueriesDynamicPrunerUpdate> SceneQueriesDynamicPrunerUpdate; SceneQueriesStaticPrunerUpdate mSceneQueriesStaticPrunerUpdate; SceneQueriesDynamicPrunerUpdate mSceneQueriesDynamicPrunerUpdate; Cm::RenderBuffer mRenderBuffer; public: Cm::IDPool mRigidActorIndexPool; private: PxArray<NpRigidDynamic*> mRigidDynamics; // no hash set used because it would be quite a bit slower when adding a large number of actors PxArray<NpRigidStatic*> mRigidStatics; // no hash set used because it would be quite a bit slower when adding a large number of actors PxCoalescedHashSet<PxArticulationReducedCoordinate*> mArticulations; PxCoalescedHashSet<PxSoftBody*> mSoftBodies; PxCoalescedHashSet<PxFEMCloth*> mFEMCloths; PxCoalescedHashSet<PxPBDParticleSystem*> mPBDParticleSystems; PxCoalescedHashSet<PxFLIPParticleSystem*> mFLIPParticleSystems; PxCoalescedHashSet<PxMPMParticleSystem*> mMPMParticleSystems; PxCoalescedHashSet<PxHairSystem*> mHairSystems; PxCoalescedHashSet<PxAggregate*> mAggregates; #ifdef NEW_DIRTY_SHADERS_CODE PxArray<NpConstraint*> mAlwaysUpdatedConstraints; PxArray<NpConstraint*> mDirtyConstraints; PxMutex mDirtyConstraintsLock; #endif PxBounds3 mSanityBounds; #if PX_SUPPORT_GPU_PHYSX PhysXIndicator mPhysXIndicator; #endif PxSync mPhysicsDone; // physics thread signals this when update ready PxSync mCollisionDone; // physics thread signals this when all collisions ready PxSync mSceneQueriesDone; // physics thread signals this when all scene queries update ready //legacy timing settings: PxReal mElapsedTime; //needed to transfer the elapsed time param from the user to the sim thread. PxU32 mNbClients; // Tracks reserved clients for multiclient support. struct SceneCompletion : public Cm::Task { SceneCompletion(PxU64 contextId, PxSync& sync) : Cm::Task(contextId), mSync(sync){} virtual void runInternal() {} //ML: As soon as mSync.set is called, and the scene is shutting down, //the scene may be deleted. That means this running task may also be deleted. //As such, we call mSync.set() inside release() to avoid a crash because the v-table on this //task might be deleted between the call to runInternal() and release() in the worker thread. virtual void release() { //We cache the continuation pointer because this class may be deleted //as soon as mSync.set() is called if the application releases the scene. PxBaseTask* c = mCont; //once mSync.set(), fetchResults() will be allowed to run. mSync.set(); //Call the continuation task that we cached above. If we use mCont or //any other member variable of this class, there is a small chance //that the variables might have become corrupted if the class //was deleted. if(c) c->removeReference(); } virtual const char* getName() const { return "NpScene.completion"; } // //This method just is called in the split sim approach as a way to set continuation after the task has been initialized void setDependent(PxBaseTask* task){PX_ASSERT(mCont == NULL); mCont = task; if(task)task->addReference();} PxSync& mSync; private: SceneCompletion& operator=(const SceneCompletion&); }; typedef Cm::DelegateTask<NpScene, &NpScene::executeScene> SceneExecution; typedef Cm::DelegateTask<NpScene, &NpScene::executeCollide> SceneCollide; typedef Cm::DelegateTask<NpScene, &NpScene::executeAdvance> SceneAdvance; PxTaskManager* mTaskManager; PxCudaContextManager* mCudaContextManager; SceneCompletion mSceneCompletion; SceneCompletion mCollisionCompletion; SceneCompletion mSceneQueriesCompletion; SceneExecution mSceneExecution; SceneCollide mSceneCollide; SceneAdvance mSceneAdvance; PxSQBuildStepHandle mStaticBuildStepHandle; PxSQBuildStepHandle mDynamicBuildStepHandle; bool mControllingSimulation; bool mIsAPIReadForbidden; // Set to true when the user is not allowed to call certain read APIs // (properties that get written to during the simulation. Search the macros PX_CHECK_SCENE_API_READ_FORBIDDEN... // to see which calls) bool mIsAPIWriteForbidden; // Set to true when the user is not allowed to do API write calls PxU32 mSimThreadStackSize; volatile PxI32 mConcurrentWriteCount; mutable volatile PxI32 mConcurrentReadCount; mutable volatile PxI32 mConcurrentErrorCount; // TLS slot index, keeps track of re-entry depth for this thread PxU32 mThreadReadWriteDepth; PxThread::Id mCurrentWriter; PxReadWriteLock mRWLock; bool mSQUpdateRunning; bool mBetweenFetchResults; bool mBuildFrozenActors; // public: enum MATERIAL_EVENT { MATERIAL_ADD, MATERIAL_UPDATE, MATERIAL_REMOVE }; class MaterialEvent { public: PX_FORCE_INLINE MaterialEvent(PxU16 handle, MATERIAL_EVENT type) : mHandle(handle), mType(type) {} PX_FORCE_INLINE MaterialEvent() {} PxU16 mHandle;//handle to the master material table MATERIAL_EVENT mType; }; private: PxArray<MaterialEvent> mSceneMaterialBuffer; PxArray<MaterialEvent> mSceneFEMSoftBodyMaterialBuffer; PxArray<MaterialEvent> mSceneFEMClothMaterialBuffer; PxArray<MaterialEvent> mScenePBDMaterialBuffer; PxArray<MaterialEvent> mSceneFLIPMaterialBuffer; PxArray<MaterialEvent> mSceneMPMMaterialBuffer; PxMutex mSceneMaterialBufferLock; PxMutex mSceneFEMSoftBodyMaterialBufferLock; PxMutex mSceneFEMClothMaterialBufferLock; PxMutex mScenePBDMaterialBufferLock; PxMutex mSceneFLIPMaterialBufferLock; PxMutex mSceneMPMMaterialBufferLock; Sc::Scene mScene; #if PX_SUPPORT_PVD Vd::PvdSceneClient mScenePvdClient; #endif const PxReal mWakeCounterResetValue; PxgDynamicsMemoryConfig mGpuDynamicsConfig; NpPhysics& mPhysics; const char* mName; }; template<> PX_FORCE_INLINE void NpScene::removeFromRigidActorList<NpRigidDynamic>(NpRigidDynamic& rigidDynamic) { removeFromRigidDynamicList(rigidDynamic); } template<> PX_FORCE_INLINE void NpScene::removeFromRigidActorList<NpRigidStatic>(NpRigidStatic& rigidStatic) { removeFromRigidStaticList(rigidStatic); } PX_FORCE_INLINE void NpScene::removeFromArticulationList(PxArticulationReducedCoordinate& articulation) { const bool exists = mArticulations.erase(&articulation); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromSoftBodyList(PxSoftBody& softBody) { const bool exists = mSoftBodies.erase(&softBody); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromFEMClothList(PxFEMCloth& femCloth) { const bool exists = mFEMCloths.erase(&femCloth); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromParticleSystemList(PxPBDParticleSystem& particleSystem) { const bool exists = mPBDParticleSystems.erase(&particleSystem); PX_ASSERT(exists); PX_UNUSED(exists); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PX_FORCE_INLINE void NpScene::removeFromParticleSystemList(PxFLIPParticleSystem& particleSystem) { const bool exists = mFLIPParticleSystems.erase(&particleSystem); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromParticleSystemList(PxMPMParticleSystem& particleSystem) { const bool exists = mMPMParticleSystems.erase(&particleSystem); PX_ASSERT(exists); PX_UNUSED(exists); } #endif PX_FORCE_INLINE void NpScene::removeFromHairSystemList(PxHairSystem& hairSystem) { const bool exists = mHairSystems.erase(&hairSystem); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromAggregateList(PxAggregate& aggregate) { const bool exists = mAggregates.erase(&aggregate); PX_ASSERT(exists); PX_UNUSED(exists); } PxU32 NpRigidStaticGetShapes(NpRigidStatic& rigid, NpShape* const *& shapes); PxU32 NpRigidDynamicGetShapes(NpRigidDynamic& actor, NpShape* const *& shapes, bool* isCompound = NULL); PxU32 NpArticulationGetShapes(NpArticulationLink& actor, NpShape* const *& shapes, bool* isCompound = NULL); } #endif
37,619
C
43.679335
253
0.730987
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSceneFetchResults.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 "NpScene.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationTendon.h" #include "NpArticulationSensor.h" #include "NpAggregate.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #include "NpFEMCloth.h" #include "NpHairSystem.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #endif #include "ScArticulationSim.h" #include "ScArticulationTendonSim.h" #include "CmCollection.h" #include "PxsSimulationController.h" #include "common/PxProfileZone.h" #include "BpBroadPhase.h" #include "BpAABBManagerBase.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// using namespace physx; bool NpScene::checkResultsInternal(bool block) { PX_PROFILE_ZONE("Basic.checkResults", getContextId()); /*if(0 && block) { PxCpuDispatcher* d = mTaskManager->getCpuDispatcher(); while(!mPhysicsDone.wait(0)) { PxBaseTask* nextTask = d->fetchNextTask(); if(nextTask) { PX_PROFILE_ZONE(nextTask->getName(), getContextId()); nextTask->run(); nextTask->release(); } } }*/ return mPhysicsDone.wait(block ? PxSync::waitForever : 0); } bool NpScene::checkResults(bool block) { return checkResultsInternal(block); } void NpScene::fetchResultsParticleSystem() { mScene.getSimulationController()->syncParticleData(); } // The order of the following operations is important! // 1. Mark the simulation as not running internally to allow reading data which should not be read otherwise // 2. Fire callbacks with latest state. void NpScene::fetchResultsPreContactCallbacks() { #if PX_SUPPORT_PVD mScenePvdClient.updateContacts(); #endif mScene.endSimulation(); setAPIReadToAllowed(); { PX_PROFILE_ZONE("Sim.fireCallbacksPreSync", getContextId()); { PX_PROFILE_ZONE("Sim.fireOutOfBoundsCallbacks", getContextId()); if(mScene.fireOutOfBoundsCallbacks()) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "At least one object is out of the broadphase bounds. To manage those objects, define a PxBroadPhaseCallback for each used client."); } mScene.fireBrokenConstraintCallbacks(); mScene.fireTriggerCallbacks(); } } void NpScene::fetchResultsPostContactCallbacks() { mScene.postCallbacksPreSync(); syncSQ(); #if PX_SUPPORT_PVD mScenePvdClient.updateSceneQueries(); mNpSQ.getSingleSqCollector().clear(); #endif // fire sleep and wake-up events { PX_PROFILE_ZONE("Sim.fireCallbacksPostSync", getContextId()); mScene.fireCallbacksPostSync(); } mScene.postReportsCleanup(); // build the list of active actors { PX_PROFILE_ZONE("Sim.buildActiveActors", getContextId()); const bool buildActiveActors = (mScene.getFlags() & PxSceneFlag::eENABLE_ACTIVE_ACTORS) || OMNI_PVD_ACTIVE; if (buildActiveActors && mBuildFrozenActors) mScene.buildActiveAndFrozenActors(); else if (buildActiveActors) mScene.buildActiveActors(); } mRenderBuffer.append(mScene.getRenderBuffer()); PX_ASSERT(getSimulationStage() != Sc::SimulationStage::eCOMPLETE); if (mControllingSimulation) mTaskManager->stopSimulation(); setSimulationStage(Sc::SimulationStage::eCOMPLETE); setAPIWriteToAllowed(); mPhysicsDone.reset(); // allow Physics to run again mCollisionDone.reset(); } bool NpScene::fetchResults(bool block, PxU32* errorState) { if(getSimulationStage() != Sc::SimulationStage::eADVANCE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchResults: fetchResults() called illegally! It must be called after advance() or simulate()"); if(!checkResultsInternal(block)) return false; #if PX_SUPPORT_GPU_PHYSX if (mCudaContextManager) { if (mScene.isUsingGpuDynamicsOrBp()) { PxCUresult res = mCudaContextManager->getCudaContext()->getLastError(); if (res) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PhysX Internal CUDA error. Simulation can not continue! Error code %i!\n", PxI32(res)); //outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "PhysX Internal CUDA error. Simulation can not continue!"); if(errorState) *errorState = res; } } } #endif PX_SIMD_GUARD; { // take write check *after* simulation has finished, otherwise // we will block simulation callbacks from using the API // disallow re-entry to detect callbacks making write calls NP_WRITE_CHECK_NOREENTRY(this); // we use cross thread profile here, to show the event in cross thread view // PT: TODO: why do we want to show it in the cross thread view? PX_PROFILE_START_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_ZONE("Sim.fetchResults", getContextId()); fetchResultsPreContactCallbacks(); { // PT: TODO: why a cross-thread event here? PX_PROFILE_START_CROSSTHREAD("Basic.processCallbacks", getContextId()); mScene.fireQueuedContactCallbacks(); PX_PROFILE_STOP_CROSSTHREAD("Basic.processCallbacks", getContextId()); } fetchResultsPostContactCallbacks(); PX_PROFILE_STOP_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_STOP_CROSSTHREAD("Basic.simulate", getContextId()); if(errorState) *errorState = 0; #if PX_SUPPORT_OMNI_PVD OmniPvdPxSampler* omniPvdSampler = NpPhysics::getInstance().mOmniPvdSampler; if (omniPvdSampler && omniPvdSampler->isSampling()) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) //send all xforms updated by the sim: PxU32 nActiveActors; PxActor ** activeActors = mScene.getActiveActors(nActiveActors); while (nActiveActors--) { PxActor * a = *activeActors++; if ((a->getType() == PxActorType::eRIGID_STATIC) || (a->getType() == PxActorType::eRIGID_DYNAMIC)) { PxRigidActor* ra = static_cast<PxRigidActor*>(a); PxTransform t = ra->getGlobalPose(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, *ra, t.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, *ra, t.q) if (a->getType() == PxActorType::eRIGID_DYNAMIC) { PxRigidDynamic* rdyn = static_cast<PxRigidDynamic*>(a); PxRigidBody& rb = *static_cast<PxRigidBody*>(a); const PxVec3 linVel = rdyn->getLinearVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, rb, linVel) const PxVec3 angVel = rdyn->getAngularVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, rb, angVel) const PxRigidBodyFlags rFlags = rdyn->getRigidBodyFlags(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, rb, rFlags) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, wakeCounter, *rdyn, rdyn->getWakeCounter()); } } else if (a->getType() == PxActorType::eARTICULATION_LINK) { PxArticulationLink* pxArticulationParentLink = 0; PxArticulationLink* pxArticulationLink = static_cast<PxArticulationLink*>(a); PxArticulationJointReducedCoordinate* pxArticulationJoint = pxArticulationLink->getInboundJoint(); if (pxArticulationJoint) { pxArticulationParentLink = &(pxArticulationJoint->getParentArticulationLink()); PxArticulationJointReducedCoordinate& jcord = *pxArticulationJoint; PxReal vals[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) vals[ax] = jcord.getJointPosition(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointPosition, jcord, vals, PxArticulationAxis::eCOUNT); for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) vals[ax] = jcord.getJointVelocity(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointVelocity, jcord, vals, PxArticulationAxis::eCOUNT); } physx::PxTransform TArtLinkLocal; if (pxArticulationParentLink) { // TGlobal = TFatherGlobal * TLocal // Inv(TFatherGlobal)* TGlobal = Inv(TFatherGlobal)*TFatherGlobal * TLocal // Inv(TFatherGlobal)* TGlobal = TLocal // TLocal = Inv(TFatherGlobal) * TGlobal //physx::PxTransform TParentGlobal = pxArticulationParentLink->getGlobalPose(); physx::PxTransform TParentGlobalInv = pxArticulationParentLink->getGlobalPose().getInverse(); physx::PxTransform TArtLinkGlobal = pxArticulationLink->getGlobalPose(); // PT:: tag: scalar transform*transform TArtLinkLocal = TParentGlobalInv * TArtLinkGlobal; } else { TArtLinkLocal = pxArticulationLink->getGlobalPose(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, worldBounds, pxArticulationLink->getArticulation(), pxArticulationLink->getArticulation().getWorldBounds()); } OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, static_cast<PxRigidActor&>(*a), TArtLinkLocal.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, static_cast<PxRigidActor&>(*a), TArtLinkLocal.q) const PxVec3 linVel = pxArticulationLink->getLinearVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, static_cast<PxRigidBody&>(*a), linVel) const PxVec3 angVel = pxArticulationLink->getAngularVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, static_cast<PxRigidBody&>(*a), angVel) const PxRigidBodyFlags rFlags = pxArticulationLink->getRigidBodyFlags(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, static_cast<PxRigidBody&>(*a), rFlags) } const PxBounds3 worldBounds = a->getWorldBounds(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, worldBounds, *a, worldBounds) // update active actors' joints const PxRigidActor* ra = a->is<PxRigidActor>(); if (ra) { static const PxU32 MAX_CONSTRAINTS = 32; PxConstraint* constraints[MAX_CONSTRAINTS]; PxU32 index = 0; while (true) { PxU32 count = ra->getConstraints(constraints, MAX_CONSTRAINTS, index); for (PxU32 i = 0; i < count; ++i) { const NpConstraint& c = static_cast<const NpConstraint&>(*constraints[i]); PxRigidActor *ra0, *ra1; c.getActors(ra0, ra1); bool ra0static = !ra0 || !!ra0->is<PxRigidStatic>(), ra1static = !ra1 || !!ra1->is<PxRigidStatic>(); // this check is to not update a joint twice if ((ra == ra0 && (ra1static || ra0 > ra1)) || (ra == ra1 && (ra0static || ra1 > ra0))) c.getCore().getPxConnector()->updateOmniPvdProperties(); } if (count == MAX_CONSTRAINTS) { index += MAX_CONSTRAINTS; continue; } break; } } } // send contacts info omniPvdSampler->streamSceneContacts(*this); //end frame omniPvdSampler->sampleScene(this); OMNI_PVD_WRITE_SCOPE_END } #endif } #if PX_SUPPORT_PVD mScenePvdClient.frameEnd(); #endif return true; } bool NpScene::fetchResultsStart(const PxContactPairHeader*& contactPairs, PxU32& nbContactPairs, bool block) { if (getSimulationStage() != Sc::SimulationStage::eADVANCE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchResultsStart: fetchResultsStart() called illegally! It must be called after advance() or simulate()"); if (!checkResultsInternal(block)) return false; PX_SIMD_GUARD; NP_WRITE_CHECK(this); // we use cross thread profile here, to show the event in cross thread view PX_PROFILE_START_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_ZONE("Sim.fetchResultsStart", getContextId()); fetchResultsPreContactCallbacks(); const PxArray<PxContactPairHeader>& pairs = mScene.getQueuedContactPairHeaders(); nbContactPairs = pairs.size(); contactPairs = pairs.begin(); mBetweenFetchResults = true; return true; } void NpContactCallbackTask::setData(NpScene* scene, const PxContactPairHeader* contactPairHeaders, const uint32_t nbContactPairHeaders) { mScene = scene; mContactPairHeaders = contactPairHeaders; mNbContactPairHeaders = nbContactPairHeaders; } void NpContactCallbackTask::run() { PxSimulationEventCallback* callback = mScene->getSimulationEventCallback(); if (!callback) return; mScene->lockRead(); for (uint32_t i = 0; i<mNbContactPairHeaders; ++i) { const PxContactPairHeader& pairHeader = mContactPairHeaders[i]; callback->onContact(pairHeader, pairHeader.pairs, pairHeader.nbPairs); } mScene->unlockRead(); } void NpScene::processCallbacks(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.processCallbacks", getContextId()); PX_PROFILE_ZONE("Sim.processCallbacks", getContextId()); //ML: because Apex destruction callback isn't thread safe so that we make this run single thread first const PxArray<PxContactPairHeader>& pairs = mScene.getQueuedContactPairHeaders(); const PxU32 nbPairs = pairs.size(); const PxContactPairHeader* contactPairs = pairs.begin(); const PxU32 nbToProcess = 256; Cm::FlushPool* flushPool = mScene.getFlushPool(); for (PxU32 i = 0; i < nbPairs; i += nbToProcess) { NpContactCallbackTask* task = PX_PLACEMENT_NEW(flushPool->allocate(sizeof(NpContactCallbackTask)), NpContactCallbackTask)(); task->setData(this, contactPairs+i, PxMin(nbToProcess, nbPairs - i)); task->setContinuation(continuation); task->removeReference(); } } void NpScene::fetchResultsFinish(PxU32* errorState) { #if PX_SUPPORT_GPU_PHYSX if (mCudaContextManager) { if (mScene.isUsingGpuDynamicsOrBp()) { PxCUresult res = mCudaContextManager->getCudaContext()->getLastError(); if (res) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PhysX Internal CUDA error. Simulation can not continue! Error code %i!\n", PxI32(res)); //outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "PhysX Internal CUDA error. Simulation can not continue!"); if (errorState) *errorState = mCudaContextManager->getCudaContext()->getLastError(); } } } #endif { PX_SIMD_GUARD; PX_PROFILE_STOP_CROSSTHREAD("Basic.processCallbacks", getContextId()); PX_PROFILE_ZONE("Basic.fetchResultsFinish", getContextId()); mBetweenFetchResults = false; NP_WRITE_CHECK(this); fetchResultsPostContactCallbacks(); if (errorState) *errorState = 0; PX_PROFILE_STOP_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_STOP_CROSSTHREAD("Basic.simulate", getContextId()); #if PX_SUPPORT_OMNI_PVD OmniPvdPxSampler* omniPvdSampler = NpPhysics::getInstance().mOmniPvdSampler; if (omniPvdSampler && omniPvdSampler->isSampling()) { omniPvdSampler->sampleScene(this); } #endif } #if PX_SUPPORT_PVD mScenePvdClient.frameEnd(); #endif }
17,040
C++
35.027484
217
0.726232
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMPMMaterial.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 "NpMPMMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION using namespace physx; using namespace Cm; NpMPMMaterial::NpMPMMaterial(const PxsMPMMaterialCore& desc) : PxMPMMaterial(PxConcreteType::eMPM_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpMPMMaterial::~NpMPMMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpMPMMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: missing line here? } void NpMPMMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseMPMMaterialToPool(*this); } else this->~NpMPMMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpMPMMaterial* NpMPMMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpMPMMaterial* obj = PX_PLACEMENT_NEW(address, NpMPMMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpMPMMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpMPMMaterial::release() { RefCountable_decRefCount(*this); } void NpMPMMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpMPMMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpMPMMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setFriction: invalid float"); mMaterial.friction = x; updateMaterial(); } PxReal NpMPMMaterial::getFriction() const { return mMaterial.friction; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpMPMMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setStretchAndShearDamping(PxReal stretchAndShearDamping) { mMaterial.stretchAndShearDamping = stretchAndShearDamping; updateMaterial(); } PxReal NpMPMMaterial::getStretchAndShearDamping() const { return mMaterial.stretchAndShearDamping; } void NpMPMMaterial::setRotationalDamping(PxReal rotationalDamping) { mMaterial.rotationalDamping = rotationalDamping; updateMaterial(); } PxReal NpMPMMaterial::getRotationalDamping() const { return mMaterial.rotationalDamping; } void NpMPMMaterial::setDensity(PxReal density) { mMaterial.density = density; updateMaterial(); } PxReal NpMPMMaterial::getDensity() const { return mMaterial.density; } void NpMPMMaterial::setMaterialModel(PxMPMMaterialModel::Enum materialModel) { mMaterial.materialModel = materialModel; updateMaterial(); } PxMPMMaterialModel::Enum NpMPMMaterial::getMaterialModel() const { return mMaterial.materialModel; } void NpMPMMaterial::setCuttingFlags(PxMPMCuttingFlags cuttingFlags) { mMaterial.cuttingFlags = cuttingFlags; updateMaterial(); } PxMPMCuttingFlags NpMPMMaterial::getCuttingFlags() const { return mMaterial.cuttingFlags; } void NpMPMMaterial::setSandFrictionAngle(PxReal sandFrictionAngle) { mMaterial.sandFrictionAngle = sandFrictionAngle; updateMaterial(); } PxReal NpMPMMaterial::getSandFrictionAngle() const { return mMaterial.sandFrictionAngle; } void NpMPMMaterial::setYieldStress(PxReal yieldStress) { mMaterial.yieldStress = yieldStress; updateMaterial(); } PxReal NpMPMMaterial::getYieldStress() const { return mMaterial.yieldStress; } void NpMPMMaterial::setIsPlastic(bool x) { mMaterial.isPlastic = x; updateMaterial(); } bool NpMPMMaterial::getIsPlastic() const { return mMaterial.isPlastic != 0; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setYoungsModulus(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setYoungsModulus: invalid float"); mMaterial.youngsModulus = x; updateMaterial(); } PxReal NpMPMMaterial::getYoungsModulus() const { return mMaterial.youngsModulus; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setPoissons(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x <= 0.5f, "PxMPMMaterial::setPoissons: invalid float"); mMaterial.poissonsRatio = x; updateMaterial(); } PxReal NpMPMMaterial::getPoissons() const { return mMaterial.poissonsRatio; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setHardening(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setPoissons: invalid float"); mMaterial.hardening = x; updateMaterial(); } PxReal NpMPMMaterial::getHardening() const { return mMaterial.hardening; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setCriticalCompression(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setCriticalCompression: invalid float"); mMaterial.criticalCompression = x; updateMaterial(); } PxReal NpMPMMaterial::getCriticalCompression() const { return mMaterial.criticalCompression; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setCriticalStretch(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setCriticalStretch: invalid float"); mMaterial.criticalStretch = x; updateMaterial(); } PxReal NpMPMMaterial::getCriticalStretch() const { return mMaterial.criticalStretch; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setTensileDamageSensitivity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setTensileDamageSensitivity: invalid float"); mMaterial.tensileDamageSensitivity = x; updateMaterial(); } PxReal NpMPMMaterial::getTensileDamageSensitivity() const { return mMaterial.tensileDamageSensitivity; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setCompressiveDamageSensitivity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setCompressiveDamageSensitivity: invalid float"); mMaterial.compressiveDamageSensitivity = x; updateMaterial(); } PxReal NpMPMMaterial::getCompressiveDamageSensitivity() const { return mMaterial.compressiveDamageSensitivity; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setAttractiveForceResidual(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setAttractiveForceResidual: invalid float"); mMaterial.attractiveForceResidual = x; updateMaterial(); } PxReal NpMPMMaterial::getAttractiveForceResidual() const { return mMaterial.attractiveForceResidual; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setAdhesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setAdhesion: invalid float"); mMaterial.adhesion = x; updateMaterial(); } PxReal NpMPMMaterial::getAdhesion() const { return mMaterial.adhesion; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setGravityScale(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMPMMaterial::setAdhesion: invalid float"); mMaterial.gravityScale = x; updateMaterial(); } PxReal NpMPMMaterial::getGravityScale() const { return mMaterial.gravityScale; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setAdhesionRadiusScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setAdhesionRadiusScale: scale must be positive"); mMaterial.adhesionRadiusScale = x; updateMaterial(); } PxReal NpMPMMaterial::getAdhesionRadiusScale() const { return mMaterial.adhesionRadiusScale; } ////////////////////////////////////////////////////////////////////////////// #endif #endif
10,389
C++
24.218447
102
0.683415
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpActor.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 "NpActor.h" #include "PxRigidActor.h" #include "NpConstraint.h" #include "NpFactory.h" #include "NpShape.h" #include "NpPhysics.h" #include "NpAggregate.h" #include "NpScene.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "CmTransformUtils.h" #include "omnipvd/NpOmniPvdSetData.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "NpHairSystem.h" #include "NpFEMCloth.h" #endif #endif using namespace physx; /////////////////////////////////////////////////////////////////////////////// const Sc::BodyCore* physx::getBodyCore(const PxRigidActor* actor) { const Sc::BodyCore* core = NULL; if(actor) { const PxType type = actor->getConcreteType(); if(type == PxConcreteType::eRIGID_DYNAMIC) { const NpRigidDynamic* dyn = static_cast<const NpRigidDynamic*>(actor); core = &dyn->getCore(); } else if(type == PxConcreteType::eARTICULATION_LINK) { const NpArticulationLink* link = static_cast<const NpArticulationLink*>(actor); core = &link->getCore(); } } return core; } /////////////////////////////////////////////////////////////////////////////// NpActor::NpActor(NpType::Enum type) : NpBase (type), mName (NULL), mConnectorArray (NULL) { } typedef PxHashMap<NpActor*, NpConnectorArray*> ConnectorMap; struct NpActorUserData { PxU32 referenceCount; ConnectorMap* tmpOriginalConnectors; }; void NpActor::exportExtraData(PxSerializationContext& stream) { const PxCollection& collection = stream.getCollection(); if(mConnectorArray) { PxU32 connectorSize = mConnectorArray->size(); PxU32 missedCount = 0; for(PxU32 i = 0; i < connectorSize; ++i) { NpConnector& c = (*mConnectorArray)[i]; PxBase* object = c.mObject; if(!collection.contains(*object)) { ++missedCount; } } NpConnectorArray* exportConnectorArray = mConnectorArray; if(missedCount > 0) { exportConnectorArray = NpFactory::getInstance().acquireConnectorArray(); if(missedCount < connectorSize) { exportConnectorArray->reserve(connectorSize - missedCount); for(PxU32 i = 0; i < connectorSize; ++i) { NpConnector& c = (*mConnectorArray)[i]; PxBase* object = c.mObject; if(collection.contains(*object)) { exportConnectorArray->pushBack(c); } } } } stream.alignData(PX_SERIAL_ALIGN); stream.writeData(exportConnectorArray, sizeof(NpConnectorArray)); Cm::exportInlineArray(*exportConnectorArray, stream); if(missedCount > 0) NpFactory::getInstance().releaseConnectorArray(exportConnectorArray); } stream.writeName(mName); } void NpActor::importExtraData(PxDeserializationContext& context) { if(mConnectorArray) { mConnectorArray = context.readExtraData<NpConnectorArray, PX_SERIAL_ALIGN>(); PX_PLACEMENT_NEW(mConnectorArray, NpConnectorArray(PxEmpty)); if(mConnectorArray->size() == 0) mConnectorArray = NULL; else Cm::importInlineArray(*mConnectorArray, context); } context.readName(mName); } void NpActor::resolveReferences(PxDeserializationContext& context) { // Resolve connector pointers if needed if(mConnectorArray) { const PxU32 nbConnectors = mConnectorArray->size(); for(PxU32 i=0; i<nbConnectors; i++) { NpConnector& c = (*mConnectorArray)[i]; context.translatePxBase(c.mObject); } } } /////////////////////////////////////////////////////////////////////////////// void NpActor::removeConstraints(PxRigidActor& owner) { if(mConnectorArray) { PxU32 nbConnectors = mConnectorArray->size(); PxU32 currentIndex = 0; while(nbConnectors--) { NpConnector& connector = (*mConnectorArray)[currentIndex]; if (connector.mType == NpConnectorType::eConstraint) { NpConstraint* c = static_cast<NpConstraint*>(connector.mObject); c->actorDeleted(&owner); NpScene* s = c->getNpScene(); if(s) s->removeFromConstraintList(*c); removeConnector(owner, currentIndex); } else currentIndex++; } } } void NpActor::removeFromAggregate(PxActor& owner) { if(mConnectorArray) // Need to test again because the code above might purge the connector array if no element remains { PX_ASSERT(mConnectorArray->size() == 1); // At this point only the aggregate should remain PX_ASSERT((*mConnectorArray)[0].mType == NpConnectorType::eAggregate); NpAggregate* a = static_cast<NpAggregate*>((*mConnectorArray)[0].mObject); bool status = a->removeActorAndReinsert(owner, false); PX_ASSERT(status); PX_UNUSED(status); PX_ASSERT(!mConnectorArray); // Remove should happen in aggregate code } PX_ASSERT(!mConnectorArray); // All the connector objects should have been removed at this point } /////////////////////////////////////////////////////////////////////////////// PxU32 NpActor::findConnector(NpConnectorType::Enum type, PxBase* object) const { if(!mConnectorArray) return 0xffffffff; for(PxU32 i=0; i < mConnectorArray->size(); i++) { NpConnector& c = (*mConnectorArray)[i]; if (c.mType == type && c.mObject == object) return i; } return 0xffffffff; } void NpActor::addConnector(NpConnectorType::Enum type, PxBase* object, const char* errMsg) { if(!mConnectorArray) mConnectorArray = NpFactory::getInstance().acquireConnectorArray(); PX_CHECK_MSG(findConnector(type, object) == 0xffffffff, errMsg); PX_UNUSED(errMsg); if(mConnectorArray->isInUserMemory() && mConnectorArray->size() == mConnectorArray->capacity()) { NpConnectorArray* newConnectorArray = NpFactory::getInstance().acquireConnectorArray(); newConnectorArray->assign(mConnectorArray->begin(), mConnectorArray->end()); mConnectorArray->~NpConnectorArray(); mConnectorArray = newConnectorArray; } NpConnector c(type, object); mConnectorArray->pushBack(c); } void NpActor::removeConnector(PxActor& /*owner*/, PxU32 index) { PX_ASSERT(mConnectorArray); PX_ASSERT(index < mConnectorArray->size()); mConnectorArray->replaceWithLast(index); if(mConnectorArray->size() == 0) { if(!mConnectorArray->isInUserMemory()) NpFactory::getInstance().releaseConnectorArray(mConnectorArray); else mConnectorArray->~NpConnectorArray(); mConnectorArray = NULL; } } void NpActor::removeConnector(PxActor& owner, NpConnectorType::Enum type, PxBase* object, const char* errorMsg) { PX_CHECK_MSG(mConnectorArray, errorMsg); PX_UNUSED(errorMsg); if(mConnectorArray) { PxU32 index = findConnector(type, object); PX_CHECK_MSG(index != 0xffffffff, errorMsg); removeConnector(owner, index); } } PxU32 NpActor::getNbConnectors(NpConnectorType::Enum type) const { PxU32 nbConnectors = 0; if(mConnectorArray) { for(PxU32 i=0; i < mConnectorArray->size(); i++) { if ((*mConnectorArray)[i].mType == type) nbConnectors++; } } return nbConnectors; } /////////////////////////////////////////////////////////////////////////////// NpAggregate* NpActor::getNpAggregate(PxU32& index) const { PX_ASSERT(getNbConnectors(NpConnectorType::eAggregate) <= 1); if(mConnectorArray) { // PT: TODO: sort by type to optimize this... for(PxU32 i=0; i < mConnectorArray->size(); i++) { NpConnector& c = (*mConnectorArray)[i]; if (c.mType == NpConnectorType::eAggregate) { index = i; return static_cast<NpAggregate*>(c.mObject); } } } return NULL; } void NpActor::setAggregate(NpAggregate* np, PxActor& owner) { PxU32 index = 0xffffffff; NpAggregate* a = getNpAggregate(index); if (!a) { PX_ASSERT(np); addConnector(NpConnectorType::eAggregate, np, "NpActor::setAggregate() failed"); } else { PX_ASSERT(mConnectorArray); PX_ASSERT(index != 0xffffffff); if (!np) removeConnector(owner, index); else (*mConnectorArray)[index].mObject = np; } } PxAggregate* NpActor::getAggregate() const { PxU32 index = 0xffffffff; NpAggregate* a = getNpAggregate(index); return static_cast<PxAggregate*>(a); } /////////////////////////////////////////////////////////////////////////////// void NpActor::removeConstraintsFromScene() { NpConnectorIterator iter = getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); NpScene* s = c->getNpScene(); if(s) s->removeFromConstraintList(*c); } } void NpActor::addConstraintsToSceneInternal() { if(!mConnectorArray) return; NpConnectorIterator iter = getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); PX_ASSERT(c->getNpScene() == NULL); c->markDirty(); // PT: "temp" fix for crash when removing/re-adding jointed actor from/to a scene NpScene* s = c->getSceneFromActors(); if(s) s->addToConstraintList(*c); } } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE const NpShapeManager* getShapeManager(const PxRigidActor& actor) { // DS: if the performance here becomes an issue we can use the same kind of offset hack as below const PxType actorType = actor.getConcreteType(); if (actorType == PxConcreteType::eRIGID_DYNAMIC) return &static_cast<const NpRigidDynamic&>(actor).getShapeManager(); else if(actorType == PxConcreteType::eRIGID_STATIC) return &static_cast<const NpRigidStatic&>(actor).getShapeManager(); else if (actorType == PxConcreteType::eARTICULATION_LINK) return &static_cast<const NpArticulationLink&>(actor).getShapeManager(); else { PX_ASSERT(0); return NULL; } } NpShapeManager* NpActor::getShapeManager_(PxRigidActor& actor) { return const_cast<NpShapeManager*>(getShapeManager(actor)); } const NpShapeManager* NpActor::getShapeManager_(const PxRigidActor& actor) { return getShapeManager(actor); } void NpActor::onActorRelease(PxActor* actor) { NpFactory::getInstance().onActorRelease(actor); } void NpActor::scSetDominanceGroup(PxDominanceGroup v) { PX_ASSERT(!isAPIWriteForbidden()); getActorCore().setDominanceGroup(v); UPDATE_PVD_PROPERTY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, dominance, *getPxActor(), v) } void NpActor::scSetOwnerClient(PxClientID inId) { //This call is only valid if we aren't in a scene. PX_ASSERT(!isAPIWriteForbidden()); getActorCore().setOwnerClient(inId); UPDATE_PVD_PROPERTY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, ownerClient, *getPxActor(), inId) } const PxActor* NpActor::getPxActor() const { const PxActorType::Enum type = getActorCore().getActorCoreType(); if(type == PxActorType::eRIGID_DYNAMIC) return static_cast<const NpRigidDynamic*>(this); else if(type == PxActorType::eRIGID_STATIC) return static_cast<const NpRigidStatic*>(this); else if(type == PxActorType::eARTICULATION_LINK) return static_cast<const NpArticulationLink*>(this); PX_ASSERT(0); return NULL; } namespace { template <typename N> NpActor* pxToNpActor(PxActor *p) { return static_cast<NpActor*>(static_cast<N*>(p)); } } NpActor::Offsets::Offsets() { for(PxU32 i=0;i<PxConcreteType::ePHYSX_CORE_COUNT;i++) pxActorToNpActor[i] = 0; size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want PxActor* n = reinterpret_cast<PxActor*>(addr); pxActorToNpActor[PxConcreteType::eRIGID_STATIC] = size_t(pxToNpActor<NpRigidStatic>(n)) - addr; pxActorToNpActor[PxConcreteType::eRIGID_DYNAMIC] = size_t(pxToNpActor<NpRigidDynamic>(n)) - addr; pxActorToNpActor[PxConcreteType::eARTICULATION_LINK] = size_t(pxToNpActor<NpArticulationLink>(n)) - addr; #if PX_SUPPORT_GPU_PHYSX pxActorToNpActor[PxConcreteType::eSOFT_BODY] = size_t(pxToNpActor<NpSoftBody>(n)) - addr; pxActorToNpActor[PxConcreteType::ePBD_PARTICLESYSTEM] = size_t(pxToNpActor<NpPBDParticleSystem>(n)) - addr; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION pxActorToNpActor[PxConcreteType::eFLIP_PARTICLESYSTEM] = size_t(pxToNpActor<NpFLIPParticleSystem>(n)) - addr; pxActorToNpActor[PxConcreteType::eMPM_PARTICLESYSTEM] = size_t(pxToNpActor<NpMPMParticleSystem>(n)) - addr; pxActorToNpActor[PxConcreteType::eFEM_CLOTH] = size_t(pxToNpActor<NpFEMCloth>(n)) - addr; pxActorToNpActor[PxConcreteType::eHAIR_SYSTEM] = size_t(pxToNpActor<NpHairSystem>(n)) - addr; #endif #endif } const NpActor::Offsets NpActor::sOffsets; NpActor::NpOffsets::NpOffsets() { // PT: ..... { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpRigidStatic* n = reinterpret_cast<NpRigidStatic*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t staticOffset = NpRigidStatic::getCoreOffset() - npOffset; npToSc[NpType::eRIGID_STATIC] = staticOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpRigidDynamic* n = reinterpret_cast<NpRigidDynamic*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpRigidDynamic::getCoreOffset() - npOffset; npToSc[NpType::eBODY] = bodyOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpArticulationLink* n = reinterpret_cast<NpArticulationLink*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpArticulationLink::getCoreOffset() - npOffset; npToSc[NpType::eBODY_FROM_ARTICULATION_LINK] = bodyOffset; } #if PX_SUPPORT_GPU_PHYSX { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpSoftBody* n = reinterpret_cast<NpSoftBody*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpSoftBody::getCoreOffset() - npOffset; npToSc[NpType::eSOFTBODY] = bodyOffset; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpFEMCloth* n = reinterpret_cast<NpFEMCloth*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpFEMCloth::getCoreOffset() - npOffset; npToSc[NpType::eFEMCLOTH] = bodyOffset; } #endif { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpPBDParticleSystem* n = reinterpret_cast<NpPBDParticleSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpPBDParticleSystem::getCoreOffset() - npOffset; npToSc[NpType::ePBD_PARTICLESYSTEM] = bodyOffset; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpFLIPParticleSystem* n = reinterpret_cast<NpFLIPParticleSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpFLIPParticleSystem::getCoreOffset() - npOffset; npToSc[NpType::eFLIP_PARTICLESYSTEM] = bodyOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpMPMParticleSystem* n = reinterpret_cast<NpMPMParticleSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpMPMParticleSystem::getCoreOffset() - npOffset; npToSc[NpType::eMPM_PARTICLESYSTEM] = bodyOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpHairSystem* n = reinterpret_cast<NpHairSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpHairSystem::getCoreOffset() - npOffset; npToSc[NpType::eHAIRSYSTEM] = bodyOffset; } #endif #endif } const NpActor::NpOffsets NpActor::sNpOffsets;
17,524
C++
30.633574
129
0.702751
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationSensor.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 "NpArticulationSensor.h" #include "PxArticulationLink.h" #include "NpArticulationLink.h" #include "ScArticulationSensorSim.h" #include "NpArticulationReducedCoordinate.h" using namespace physx; namespace physx { // PX_SERIALIZATION void NpArticulationSensor::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mLink); } NpArticulationSensor* NpArticulationSensor::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationSensor* obj = PX_PLACEMENT_NEW(address, NpArticulationSensor(PxBaseFlags(0))); address += sizeof(NpArticulationSensor); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationSensor::NpArticulationSensor(PxArticulationLink* link, const PxTransform& relativePose) : PxArticulationSensor(PxConcreteType::eARTICULATION_SENSOR, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_SENSOR) { mLink = link; mCore.mRelativePose = relativePose; mCore.mSim = NULL; mCore.mFlags = 0; } void NpArticulationSensor::release() { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSensor::release() not allowed while the articulation is in a scene. Call will be ignored."); return; } NpArticulationReducedCoordinate* articulation = static_cast<NpArticulationReducedCoordinate*>(&mLink->getArticulation()); PxArray<NpArticulationSensor*>& sensors = articulation->getSensors(); PX_CHECK_AND_RETURN(mHandle < sensors.size() && sensors[mHandle] == this, "PxArticulationSensor::release() attempt to release sensor that is not part of this articulation."); sensors.back()->setHandle(mHandle); sensors.replaceWithLast(mHandle); this->~NpArticulationSensor(); if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } PxSpatialForce NpArticulationSensor::getForces() const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationSensor::getForces() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxSpatialForce()); if (mCore.getSim()) return mCore.getSim()->getForces(); PxSpatialForce zero; zero.force = PxVec3(0.f); zero.torque = PxVec3(0.f); return zero; } PxTransform NpArticulationSensor::getRelativePose() const { return mCore.mRelativePose; } void NpArticulationSensor::setRelativePose(const PxTransform& pose) { mCore.mRelativePose = pose; if (mCore.getSim()) { mCore.getSim()->setRelativePose(pose); } } PxArticulationLink* NpArticulationSensor::getLink() const { return mLink; } PxU32 NpArticulationSensor::getIndex() const { NP_READ_CHECK(getNpScene()); if(mCore.getSim()) return mCore.getSim()->getLowLevelIndex(); return 0xFFFFFFFFu; } PxArticulationReducedCoordinate* NpArticulationSensor::getArticulation() const { return &mLink->getArticulation(); } PxArticulationSensorFlags NpArticulationSensor::getFlags() const { return PxArticulationSensorFlags(PxU8(mCore.mFlags)); } void NpArticulationSensor::setFlag(PxArticulationSensorFlag::Enum flag, bool enabled) { if(enabled) mCore.mFlags |= flag; else mCore.mFlags &= (~flag); if (mCore.getSim()) { mCore.getSim()->setFlag(mCore.mFlags); } } }
5,021
C++
30.78481
260
0.767975
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFLIPMaterial.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 "NpFLIPMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION using namespace physx; using namespace Cm; NpFLIPMaterial::NpFLIPMaterial(const PxsFLIPMaterialCore& desc) : PxFLIPMaterial(PxConcreteType::eFLIP_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpFLIPMaterial::~NpFLIPMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpFLIPMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: missing line here? } void NpFLIPMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseFLIPMaterialToPool(*this); } else this->~NpFLIPMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpFLIPMaterial* NpFLIPMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpFLIPMaterial* obj = PX_PLACEMENT_NEW(address, NpFLIPMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpFLIPMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpFLIPMaterial::release() { RefCountable_decRefCount(*this); } void NpFLIPMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpFLIPMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpFLIPMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setFriction: invalid float"); mMaterial.friction = x; updateMaterial(); } PxReal NpFLIPMaterial::getFriction() const { return mMaterial.friction; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setViscosity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setViscosity: invalid float"); mMaterial.viscosity = x; updateMaterial(); } PxReal NpFLIPMaterial::getViscosity() const { return mMaterial.viscosity; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpFLIPMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setAdhesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.adhesion = x; updateMaterial(); } PxReal NpFLIPMaterial::getAdhesion() const { return mMaterial.adhesion; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setGravityScale(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.gravityScale = x; updateMaterial(); } PxReal NpFLIPMaterial::getGravityScale() const { return mMaterial.gravityScale; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setAdhesionRadiusScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setAdhesionRadiusScale: scale must be positive"); mMaterial.adhesionRadiusScale = x; updateMaterial(); } PxReal NpFLIPMaterial::getAdhesionRadiusScale() const { return mMaterial.adhesionRadiusScale; } /////////////////////////////////////////////////////////////////////////////// #endif #endif
5,918
C++
28.447761
103
0.690267
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFactory.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/PxGeometryQuery.h" #include "NpFactory.h" #include "NpPhysics.h" #include "ScPhysics.h" #include "GuHeightField.h" #include "GuTriangleMesh.h" #include "GuConvexMesh.h" #include "NpConnector.h" #include "NpPtrTableStorageManager.h" #include "CmCollection.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationTendon.h" #include "NpAggregate.h" #include "PxvGlobals.h" #if PX_SUPPORT_GPU_PHYSX #include "NpParticleSystem.h" #include "NpSoftBody.h" #include "NpFEMCloth.h" #include "NpHairSystem.h" #include "PxPhysXGpu.h" #endif #if PX_SUPPORT_OMNI_PVD # define OMNI_PVD_NOTIFY_ADD(OBJECT) notifyListenersAdd(OBJECT) # define OMNI_PVD_NOTIFY_REMOVE(OBJECT) notifyListenersRemove(OBJECT) #else # define OMNI_PVD_NOTIFY_ADD(OBJECT) # define OMNI_PVD_NOTIFY_REMOVE(OBJECT) #endif using namespace physx; using namespace Cm; NpFactory::NpFactory() : Gu::MeshFactory() , mConnectorArrayPool("connectorArrayPool") , mPtrTableStorageManager(PX_NEW(NpPtrTableStorageManager)) , mMaterialPool("MaterialPool") , mGpuMemStat(0) #if PX_SUPPORT_PVD , mNpFactoryListener(NULL) #endif { } template <typename T> static void releaseAll(PxHashSet<T*>& container) { // a bit tricky: release will call the factory back to remove the object from // the tracking array, immediately invalidating the iterator. Reconstructing the // iterator per delete can be expensive. So, we use a temporary object. // // a coalesced hash would be efficient too, but we only ever iterate over it // here so it's not worth the 2x remove penalty over the normal hash. PxArray<T*, PxReflectionAllocator<T*> > tmp; tmp.reserve(container.size()); for(typename PxHashSet<T*>::Iterator iter = container.getIterator(); !iter.done(); ++iter) tmp.pushBack(*iter); PX_ASSERT(tmp.size() == container.size()); for(PxU32 i=0;i<tmp.size();i++) tmp[i]->release(); } NpFactory::~NpFactory() { PX_DELETE(mPtrTableStorageManager); } void NpFactory::release() { releaseAll(mAggregateTracking); releaseAll(mConstraintTracking); releaseAll(mArticulationTracking); releaseAll(mActorTracking); while(mShapeTracking.size()) static_cast<NpShape*>(mShapeTracking.getEntries()[0])->releaseInternal(); #if PX_SUPPORT_GPU_PHYSX releaseAll(mParticleBufferTracking); #endif Gu::MeshFactory::release(); // deletes the class } void NpFactory::createInstance() { PX_ASSERT(!mInstance); mInstance = PX_NEW(NpFactory)(); } void NpFactory::destroyInstance() { PX_ASSERT(mInstance); mInstance->release(); mInstance = NULL; } NpFactory* NpFactory::mInstance = NULL; /////////////////////////////////////////////////////////////////////////////// template <class T0, class T1> static void addToTracking(T1& set, T0* element, PxMutex& mutex, bool lock) { if(!element) return; if(lock) mutex.lock(); set.insert(element); if(lock) mutex.unlock(); } /////////////////////////////////////////////////////////////////////////////// Actors void NpFactory::addRigidStatic(PxRigidStatic* npActor, bool lock) { addToTracking(mActorTracking, npActor, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npActor); } void NpFactory::addRigidDynamic(PxRigidDynamic* npBody, bool lock) { addToTracking(mActorTracking, npBody, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npBody); } void NpFactory::addShape(PxShape* shape, bool lock) { addToTracking(mShapeTracking, shape, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(shape); } void NpFactory::onActorRelease(PxActor* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mActorTracking.erase(a); } void NpFactory::onShapeRelease(PxShape* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mShapeTracking.erase(a); } void NpFactory::addArticulation(PxArticulationReducedCoordinate* npArticulation, bool lock) { addToTracking(mArticulationTracking, npArticulation, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npArticulation); } #if PX_SUPPORT_GPU_PHYSX void NpFactory::addParticleBuffer(PxParticleBuffer* buffer, bool lock) { addToTracking(mParticleBufferTracking, buffer, mTrackingMutex, lock); } void NpFactory::onParticleBufferReleaseInternal(PxParticleBuffer* buffer) { PxMutex::ScopedLock lock(mTrackingMutex); mParticleBufferTracking.erase(buffer); } #endif void NpFactory::releaseArticulationToPool(PxArticulationReducedCoordinate& articulation) { PX_ASSERT(articulation.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PX_ASSERT(articulation.getConcreteType() == PxConcreteType::eARTICULATION_REDUCED_COORDINATE); PxMutex::ScopedLock lock(mArticulationRCPoolLock); mArticulationRCPool.destroy(static_cast<NpArticulationReducedCoordinate*>(&articulation)); } PxArticulationReducedCoordinate* NpFactory::createArticulationRC() { NpArticulationReducedCoordinate* npArticulation = NpFactory::getInstance().createNpArticulationRC(); if(npArticulation) addArticulation(npArticulation); else PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation initialization failed: returned NULL."); // OMNI_PVD_CREATE() return npArticulation; } NpArticulationReducedCoordinate* NpFactory::createNpArticulationRC() { PxMutex::ScopedLock lock(mArticulationRCPoolLock); return mArticulationRCPool.construct(); } void NpFactory::onArticulationRelease(PxArticulationReducedCoordinate* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mArticulationTracking.erase(a); } NpArticulationLink* NpFactory::createNpArticulationLink(NpArticulationReducedCoordinate& root, NpArticulationLink* parent, const PxTransform& pose) { NpArticulationLink* npArticulationLink; { PxMutex::ScopedLock lock(mArticulationLinkPoolLock); npArticulationLink = mArticulationLinkPool.construct(pose, root, parent); } return npArticulationLink; } void NpFactory::releaseArticulationLinkToPool(NpArticulationLink& articulationLink) { PX_ASSERT(articulationLink.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); OMNI_PVD_NOTIFY_REMOVE(&articulationLink); PxMutex::ScopedLock lock(mArticulationLinkPoolLock); mArticulationLinkPool.destroy(&articulationLink); } PxArticulationLink* NpFactory::createArticulationLink(NpArticulationReducedCoordinate& root, NpArticulationLink* parent, const PxTransform& pose) { PX_CHECK_AND_RETURN_NULL(pose.isValid(),"Supplied articulation link pose is not valid. Articulation link creation method returns NULL."); PX_CHECK_AND_RETURN_NULL((!parent || (&parent->getRoot() == &root)), "specified parent link is not part of the destination articulation. Articulation link creation method returns NULL."); NpArticulationLink* npArticulationLink = NpFactory::getInstance().createNpArticulationLink(root, parent, pose); if (!npArticulationLink) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation link initialization failed: returned NULL."); return NULL; } OMNI_PVD_NOTIFY_ADD(npArticulationLink); PxArticulationJointReducedCoordinate* npArticulationJoint = 0; if (parent) { PxTransform parentPose = parent->getCMassLocalPose().transformInv(pose); PxTransform childPose = PxTransform(PxIdentity); npArticulationJoint = root.createArticulationJoint(*parent, parentPose, *npArticulationLink, childPose); if (!npArticulationJoint) { PX_DELETE(npArticulationLink); PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation link initialization failed due to joint creation failure: returned NULL."); return NULL; } npArticulationLink->setInboundJoint(*npArticulationJoint); } return npArticulationLink; } NpArticulationJointReducedCoordinate* NpFactory::createNpArticulationJointRC(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame) { NpArticulationJointReducedCoordinate* npArticulationJoint; { PxMutex::ScopedLock lock(mArticulationJointRCPoolLock); npArticulationJoint = mArticulationRCJointPool.construct(parent, parentFrame, child, childFrame); } OMNI_PVD_NOTIFY_ADD(npArticulationJoint); return npArticulationJoint; } void NpFactory::releaseArticulationJointRCToPool(NpArticulationJointReducedCoordinate& articulationJoint) { PX_ASSERT(articulationJoint.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); OMNI_PVD_NOTIFY_REMOVE(&articulationJoint); PxMutex::ScopedLock lock(mArticulationJointRCPoolLock); mArticulationRCJointPool.destroy(&articulationJoint); } /////////////////////////////////////////////////////////////////////////////// soft body #if PX_SUPPORT_GPU_PHYSX PxSoftBody* NpFactory::createSoftBody(PxCudaContextManager& cudaContextManager) { NpSoftBody* sb; { PxMutex::ScopedLock lock(mSoftBodyPoolLock); sb = mSoftBodyPool.construct(cudaContextManager); } OMNI_PVD_NOTIFY_ADD(sb); return sb; } void NpFactory::releaseSoftBodyToPool(PxSoftBody& softBody) { PX_ASSERT(softBody.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); OMNI_PVD_NOTIFY_REMOVE(&softBody); PxMutex::ScopedLock lock(mSoftBodyPoolLock); mSoftBodyPool.destroy(static_cast<NpSoftBody*>(&softBody)); } /////////////////////////////////////////////////////////////////////////////// FEM cloth #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFEMCloth* NpFactory::createFEMCloth(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mFEMClothPoolLock); return mFEMClothPool.construct(cudaContextManager); } void NpFactory::releaseFEMClothToPool(PxFEMCloth& femCloth) { PX_ASSERT(femCloth.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFEMClothPoolLock); mFEMClothPool.destroy(static_cast<NpFEMCloth*>(&femCloth)); } #endif //////////////////////////////////////////////////////////////////////////////// particle system PxPBDParticleSystem* NpFactory::createPBDParticleSystem(PxU32 maxNeighborhood, PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mPBDParticleSystemPoolLock); //PX_CHECK_MSG(NpPBDParticleSystem::getNumAvailableSystems() > 0, "Max. number of concurrent PxParticleSystem is 256."); return mPBDParticleSystemPool.construct(maxNeighborhood, cudaContextManager); } void NpFactory::releasePBDParticleSystemToPool(PxPBDParticleSystem& particleSystem) { PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mPBDParticleSystemPoolLock); mPBDParticleSystemPool.destroy(static_cast<NpPBDParticleSystem*>(&particleSystem)); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFLIPParticleSystem* NpFactory::createFLIPParticleSystem(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mFLIPParticleSystemPoolLock); //PX_CHECK_MSG(NpFLIPParticleSystem::getNumAvailableSystems() > 0, "Max. number of concurrent PxParticleSystem is 256."); return mFLIPParticleSystemPool.construct(cudaContextManager); } void NpFactory::releaseFLIPParticleSystemToPool(PxFLIPParticleSystem& particleSystem) { PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFLIPParticleSystemPoolLock); mFLIPParticleSystemPool.destroy(static_cast<NpFLIPParticleSystem*>(&particleSystem)); } PxMPMParticleSystem* NpFactory::createMPMParticleSystem(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mMPMParticleSystemPoolLock); //PX_CHECK_MSG(NpMPMParticleSystem::getNumAvailableSystems() > 0, "Max. number of concurrent PxParticleSystem is 256."); return mMPMParticleSystemPool.construct(cudaContextManager); } void NpFactory::releaseMPMParticleSystemToPool(PxMPMParticleSystem& particleSystem) { PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mMPMParticleSystemPoolLock); mMPMParticleSystemPool.destroy(static_cast<NpMPMParticleSystem*>(&particleSystem)); } #endif /////////////////////////////////////////////////////////////////////////////// Particle Buffers PxParticleBuffer* NpFactory::createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleBuffer* buffer = physxGpu->createParticleBuffer(maxParticles, maxVolumes, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(buffer); return buffer; } PxParticleAndDiffuseBuffer* NpFactory::createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleAndDiffuseBuffer* diffuseBuffer = physxGpu->createParticleAndDiffuseBuffer(maxParticles, maxVolumes, maxDiffuseParticles, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(diffuseBuffer); return diffuseBuffer; } PxParticleClothBuffer* NpFactory::createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleClothBuffer* clothBuffer = physxGpu->createParticleClothBuffer(maxParticles, maxNumVolumes, maxNumCloths, maxNumTriangles, maxNumSprings, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(clothBuffer); return clothBuffer; } PxParticleRigidBuffer* NpFactory::createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleRigidBuffer* rigidBuffer = physxGpu->createParticleRigidBuffer(maxParticles, maxNumVolumes, maxNumRigids, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(rigidBuffer); return rigidBuffer; } void NpFactory::onParticleBufferRelease(PxParticleBuffer* buffer) { NpFactory::getInstance().onParticleBufferReleaseInternal(buffer); } /////////////////////////////////////////////////////////////////////////////// HairSystem #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxHairSystem* NpFactory::createHairSystem(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mHairSystemPoolLock); return mHairSystemPool.construct(cudaContextManager); } void NpFactory::releaseHairSystemToPool(PxHairSystem& hairSystem) { PX_ASSERT(hairSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mHairSystemPoolLock); mHairSystemPool.destroy(static_cast<NpHairSystem*>(&hairSystem)); } #endif #endif /////////////////////////////////////////////////////////////////////////////// constraint void NpFactory::addConstraint(PxConstraint* npConstraint, bool lock) { addToTracking(mConstraintTracking, npConstraint, mTrackingMutex, lock); } PxConstraint* NpFactory::createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) { PX_CHECK_AND_RETURN_NULL((actor0 && actor0->getConcreteType()!=PxConcreteType::eRIGID_STATIC) || (actor1 && actor1->getConcreteType()!=PxConcreteType::eRIGID_STATIC), "createConstraint: At least one actor must be dynamic or an articulation link"); NpConstraint* npConstraint; { PxMutex::ScopedLock lock(mConstraintPoolLock); npConstraint = mConstraintPool.construct(actor0, actor1, connector, shaders, dataSize); } addConstraint(npConstraint); connector.connectToConstraint(npConstraint); return npConstraint; } void NpFactory::releaseConstraintToPool(NpConstraint& constraint) { PX_ASSERT(constraint.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mConstraintPoolLock); mConstraintPool.destroy(&constraint); } void NpFactory::onConstraintRelease(PxConstraint* c) { PxMutex::ScopedLock lock(mTrackingMutex); mConstraintTracking.erase(c); } /////////////////////////////////////////////////////////////////////////////// aggregate void NpFactory::addAggregate(PxAggregate* npAggregate, bool lock) { addToTracking(mAggregateTracking, npAggregate, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npAggregate); } PxAggregate* NpFactory::createAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint) { NpAggregate* npAggregate; { PxMutex::ScopedLock lock(mAggregatePoolLock); npAggregate = mAggregatePool.construct(maxActors, maxShapes, filterHint); } addAggregate(npAggregate); return npAggregate; } void NpFactory::releaseAggregateToPool(NpAggregate& aggregate) { PX_ASSERT(aggregate.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mAggregatePoolLock); mAggregatePool.destroy(&aggregate); } void NpFactory::onAggregateRelease(PxAggregate* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mAggregateTracking.erase(a); } /////////////////////////////////////////////////////////////////////////////// PxMaterial* NpFactory::createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution) { PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0."); PX_CHECK_AND_RETURN_NULL(staticFriction >= 0.0f, "createMaterial: staticFriction must be >= 0."); PX_CHECK_AND_RETURN_NULL(restitution >= 0.0f || restitution <= 1.0f, "createMaterial: restitution must be between 0 and 1."); PxsMaterialData materialData; materialData.staticFriction = staticFriction; materialData.dynamicFriction = dynamicFriction; materialData.restitution = restitution; NpMaterial* npMaterial; { PxMutex::ScopedLock lock(mMaterialPoolLock); npMaterial = mMaterialPool.construct(materialData); } return npMaterial; } void NpFactory::releaseMaterialToPool(NpMaterial& material) { PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mMaterialPoolLock); mMaterialPool.destroy(&material); } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX PxFEMSoftBodyMaterial* NpFactory::createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction) { #if PX_SUPPORT_GPU_PHYSX PX_CHECK_AND_RETURN_NULL(youngs >= 0.0f, "createFEMSoftBodyMaterial: youngs must be >= 0."); PX_CHECK_AND_RETURN_NULL(poissons >= 0.0f && poissons < 0.5f, "createFEMSoftBodyMaterial: poissons must be in range[0.f, 0.5f)."); PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0."); PxsFEMSoftBodyMaterialData materialData; materialData.youngs = youngs; materialData.poissons = poissons; materialData.dynamicFriction = dynamicFriction; materialData.damping = 0.f; materialData.dampingScale = toUniformU16(1.f); materialData.materialModel = PxFEMSoftBodyMaterialModel::eCO_ROTATIONAL; materialData.deformThreshold = PX_MAX_F32; materialData.deformLowLimitRatio = 1.f; materialData.deformHighLimitRatio = 1.f; NpFEMSoftBodyMaterial* npMaterial; { PxMutex::ScopedLock lock(mFEMMaterialPoolLock); npMaterial = mFEMMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(youngs); PX_UNUSED(poissons); PX_UNUSED(dynamicFriction); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxFEMMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseFEMMaterialToPool(PxFEMSoftBodyMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpFEMSoftBodyMaterial& material = static_cast<NpFEMSoftBodyMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFEMMaterialPoolLock); mFEMMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFEMClothMaterial* NpFactory::createFEMClothMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal thickness) { #if PX_SUPPORT_GPU_PHYSX PX_CHECK_AND_RETURN_NULL(youngs >= 0.0f, "createFEMClothMaterial: youngs must be >= 0."); PX_CHECK_AND_RETURN_NULL(poissons >= 0.0f && poissons < 0.5f, "createFEMClothMaterial: poissons must be in range[0.f, 0.5f)."); PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0."); PX_CHECK_AND_RETURN_NULL(thickness >= 0.0f, "createMaterial: thickness must be > 0."); PxsFEMClothMaterialData materialData; materialData.youngs = youngs; materialData.poissons = poissons; materialData.dynamicFriction = dynamicFriction; materialData.thickness = thickness; NpFEMClothMaterial* npMaterial = NULL; { PxMutex::ScopedLock lock(mFEMClothMaterialPoolLock); npMaterial = mFEMClothMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(youngs); PX_UNUSED(poissons); PX_UNUSED(dynamicFriction); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxFEMClothMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseFEMClothMaterialToPool(PxFEMClothMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpFEMClothMaterial& material = static_cast<NpFEMClothMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFEMClothMaterialPoolLock); mFEMClothMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } #endif /////////////////////////////////////////////////////////////////////////////// PxPBDMaterial* NpFactory::createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient, PxReal gravityScale) { #if PX_SUPPORT_GPU_PHYSX PxsPBDMaterialData materialData; materialData.friction = friction; materialData.damping = damping; materialData.viscosity = viscosity; materialData.vorticityConfinement = vorticityConfinement; materialData.surfaceTension = surfaceTension; materialData.cohesion = cohesion; materialData.adhesion = adhesion; materialData.lift = lift; materialData.drag = drag; materialData.cflCoefficient = cflCoefficient; materialData.gravityScale = gravityScale; materialData.particleFrictionScale = 1.f; materialData.adhesionRadiusScale = 0.f; materialData.particleAdhesionScale = 1.f; NpPBDMaterial* npMaterial; { PxMutex::ScopedLock lock(mPBDMaterialPoolLock); npMaterial = mPBDMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(friction); PX_UNUSED(damping); PX_UNUSED(adhesion); PX_UNUSED(viscosity); PX_UNUSED(vorticityConfinement); PX_UNUSED(surfaceTension); PX_UNUSED(cohesion); PX_UNUSED(lift); PX_UNUSED(drag); PX_UNUSED(cflCoefficient); PX_UNUSED(gravityScale); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxPBDMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releasePBDMaterialToPool(PxPBDMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpPBDMaterial& material = static_cast<NpPBDMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mPBDMaterialPoolLock); mPBDMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFLIPMaterial* NpFactory::createFLIPMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal gravityScale) { #if PX_SUPPORT_GPU_PHYSX PxsFLIPMaterialData materialData; materialData.friction = friction; materialData.damping = damping; materialData.adhesion = adhesion; materialData.viscosity = viscosity; materialData.gravityScale = gravityScale; materialData.adhesionRadiusScale = 0.f; NpFLIPMaterial* npMaterial; { PxMutex::ScopedLock lock(mFLIPMaterialPoolLock); npMaterial = mFLIPMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(friction); PX_UNUSED(damping); PX_UNUSED(adhesion); PX_UNUSED(viscosity); PX_UNUSED(gravityScale); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxFLIPMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseFLIPMaterialToPool(PxFLIPMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpFLIPMaterial& material = static_cast<NpFLIPMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFLIPMaterialPoolLock); mFLIPMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } /////////////////////////////////////////////////////////////////////////////// PxMPMMaterial* NpFactory::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) { #if PX_SUPPORT_GPU_PHYSX PxsMPMMaterialData materialData; materialData.friction = friction; materialData.damping = damping; materialData.adhesion = adhesion; materialData.adhesionRadiusScale = 0.f; materialData.isPlastic = isPlastic; materialData.youngsModulus = youngsModulus; materialData.poissonsRatio = poissons; materialData.hardening = hardening; materialData.criticalCompression = criticalCompression; materialData.criticalStretch = criticalStretch; materialData.tensileDamageSensitivity = tensileDamageSensitivity; materialData.compressiveDamageSensitivity = compressiveDamageSensitivity; materialData.attractiveForceResidual = attractiveForceResidual; materialData.gravityScale = gravityScale; materialData.materialModel = PxMPMMaterialModel::eNEO_HOOKEAN; materialData.cuttingFlags = PxMPMCuttingFlag::eNONE; materialData.yieldStress = 30000; materialData.sandFrictionAngle = 3.1415926535898f * 0.25f; materialData.density = 500.0f; materialData.stretchAndShearDamping = 0.0f; materialData.rotationalDamping = 0.0f; NpMPMMaterial* npMaterial; { PxMutex::ScopedLock lock(mMPMMaterialPoolLock); npMaterial = mMPMMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(friction); PX_UNUSED(damping); PX_UNUSED(adhesion); PX_UNUSED(isPlastic); PX_UNUSED(youngsModulus); PX_UNUSED(poissons); PX_UNUSED(hardening); PX_UNUSED(criticalCompression); PX_UNUSED(criticalStretch); PX_UNUSED(tensileDamageSensitivity); PX_UNUSED(compressiveDamageSensitivity); PX_UNUSED(attractiveForceResidual); PX_UNUSED(gravityScale); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxMPMMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseMPMMaterialToPool(PxMPMMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpMPMMaterial& material = static_cast<NpMPMMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mMPMMaterialPoolLock); mMPMMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } #endif // PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #endif // PX_SUPPORT_GPU_PHYSX /////////////////////////////////////////////////////////////////////////////// NpConnectorArray* NpFactory::acquireConnectorArray() { PxMutexT<>::ScopedLock l(mConnectorArrayPoolLock); return mConnectorArrayPool.construct(); } void NpFactory::releaseConnectorArray(NpConnectorArray* array) { PxMutexT<>::ScopedLock l(mConnectorArrayPoolLock); mConnectorArrayPool.destroy(array); } /////////////////////////////////////////////////////////////////////////////// #if PX_CHECKED bool checkShape(const PxGeometry& g, const char* errorMsg) { const bool isValid = PxGeometryQuery::isValid(g); if(!isValid) PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, errorMsg); return isValid; } #endif template <typename PxMaterialType, typename NpMaterialType> NpShape* NpFactory::createShapeInternal(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxMaterialType*const* materials, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum flag) { #if PX_CHECKED if(!checkShape(geometry, "Supplied PxGeometry is not valid. Shape creation method returns NULL.")) return NULL; // Check for invalid material table setups if(!NpShape::checkMaterialSetup(geometry, "Shape creation", materials, materialCount)) return NULL; #endif PxInlineArray<PxU16, 4> materialIndices("NpFactory::TmpMaterialIndexBuffer"); materialIndices.resize(materialCount); if (materialCount == 1) materialIndices[0] = static_cast<NpMaterialType*>(materials[0])->mMaterial.mMaterialIndex; else NpMaterialType::getMaterialIndices(materials, materialIndices.begin(), materialCount); NpShape* npShape; { PxMutex::ScopedLock lock(mShapePoolLock); PxU16* mi = materialIndices.begin(); // required to placate pool constructor arg passing npShape = mShapePool.construct(geometry, shapeFlags, mi, materialCount, isExclusive, flag); } if (!npShape) return NULL; // PT: TODO: add material base class, move this to NpShape, drop getMaterial<> for (PxU32 i = 0; i < materialCount; i++) { PxMaterialType* mat = npShape->getMaterial<PxMaterialType, NpMaterialType>(i); RefCountable_incRefCount(*mat); } addShape(npShape); return npShape; } NpShape* NpFactory::createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxMaterial*const* materials, PxU16 materialCount, bool isExclusive) { return createShapeInternal<PxMaterial, NpMaterial>(geometry, shapeFlags, materials, materialCount, isExclusive, PxShapeCoreFlag::Enum(0)); } NpShape* NpFactory::createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxFEMSoftBodyMaterial*const* materials, PxU16 materialCount, bool isExclusive) { #if PX_SUPPORT_GPU_PHYSX return createShapeInternal<PxFEMSoftBodyMaterial, NpFEMSoftBodyMaterial>(geometry, shapeFlags, materials, materialCount, isExclusive, PxShapeCoreFlag::eSOFT_BODY_SHAPE); #else PX_UNUSED(geometry); PX_UNUSED(shapeFlags); PX_UNUSED(materials); PX_UNUSED(materialCount); PX_UNUSED(isExclusive); return NULL; #endif } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX NpShape* NpFactory::createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxFEMClothMaterial*const* materials, PxU16 materialCount, bool isExclusive) { return createShapeInternal<PxFEMClothMaterial, NpFEMClothMaterial>(geometry, shapeFlags, materials, materialCount, isExclusive, PxShapeCoreFlag::eCLOTH_SHAPE); } #endif void NpFactory::releaseShapeToPool(NpShape& shape) { PX_ASSERT(shape.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mShapePoolLock); mShapePool.destroy(&shape); } PxU32 NpFactory::getNbShapes() const { // PT: TODO: isn't there a lock missing here? See usage in MeshFactory return mShapeTracking.size(); } PxU32 NpFactory::getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { // PT: TODO: isn't there a lock missing here? See usage in MeshFactory return getArrayOfPointers(userBuffer, bufferSize, startIndex, mShapeTracking.getEntries(), mShapeTracking.size()); } /////////////////////////////////////////////////////////////////////////////// PxRigidStatic* NpFactory::createRigidStatic(const PxTransform& pose) { PX_CHECK_AND_RETURN_NULL(pose.isValid(), "pose is not valid. createRigidStatic returns NULL."); NpRigidStatic* npActor; { PxMutex::ScopedLock lock(mRigidStaticPoolLock); npActor = mRigidStaticPool.construct(pose); } addRigidStatic(npActor); return npActor; } void NpFactory::releaseRigidStaticToPool(NpRigidStatic& rigidStatic) { PX_ASSERT(rigidStatic.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mRigidStaticPoolLock); mRigidStaticPool.destroy(&rigidStatic); } /////////////////////////////////////////////////////////////////////////////// PxRigidDynamic* NpFactory::createRigidDynamic(const PxTransform& pose) { PX_CHECK_AND_RETURN_NULL(pose.isValid(), "pose is not valid. createRigidDynamic returns NULL."); NpRigidDynamic* npBody; { PxMutex::ScopedLock lock(mRigidDynamicPoolLock); npBody = mRigidDynamicPool.construct(pose); } addRigidDynamic(npBody); return npBody; } void NpFactory::releaseRigidDynamicToPool(NpRigidDynamic& rigidDynamic) { PX_ASSERT(rigidDynamic.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mRigidDynamicPoolLock); mRigidDynamicPool.destroy(&rigidDynamic); } /////////////////////////////////////////////////////////////////////////////// // PT: this function is here to minimize the amount of locks when deserializing a collection void NpFactory::addCollection(const Collection& collection) { PxU32 nb = collection.getNbObjects(); const PxPair<PxBase* const, PxSerialObjectId>* entries = collection.internalGetObjects(); // PT: we take the lock only once, here PxMutex::ScopedLock lock(mTrackingMutex); for(PxU32 i=0;i<nb;i++) { PxBase* s = entries[i].first; const PxType serialType = s->getConcreteType(); ////////////////////////// if(serialType==PxConcreteType::eHEIGHTFIELD) { Gu::HeightField* gu = static_cast<Gu::HeightField*>(s); gu->setMeshFactory(this); addHeightField(gu, false); } else if(serialType==PxConcreteType::eCONVEX_MESH) { Gu::ConvexMesh* gu = static_cast<Gu::ConvexMesh*>(s); gu->setMeshFactory(this); addConvexMesh(gu, false); } else if(serialType==PxConcreteType::eTRIANGLE_MESH_BVH33 || serialType==PxConcreteType::eTRIANGLE_MESH_BVH34) { Gu::TriangleMesh* gu = static_cast<Gu::TriangleMesh*>(s); gu->setMeshFactory(this); addTriangleMesh(gu, false); } else if(serialType==PxConcreteType::eRIGID_DYNAMIC) { NpRigidDynamic* np = static_cast<NpRigidDynamic*>(s); addRigidDynamic(np, false); } else if(serialType==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* np = static_cast<NpRigidStatic*>(s); addRigidStatic(np, false); } else if(serialType==PxConcreteType::eSHAPE) { NpShape* np = static_cast<NpShape*>(s); addShape(np, false); } else if(serialType==PxConcreteType::eMATERIAL) { } else if(serialType==PxConcreteType::eCONSTRAINT) { NpConstraint* np = static_cast<NpConstraint*>(s); addConstraint(np, false); } else if(serialType==PxConcreteType::eAGGREGATE) { NpAggregate* np = static_cast<NpAggregate*>(s); addAggregate(np, false); // PT: TODO: double-check this.... is it correct? for(PxU32 j=0;j<np->getCurrentSizeFast();j++) { PxBase* actor = np->getActorFast(j); const PxType serialType1 = actor->getConcreteType(); if(serialType1==PxConcreteType::eRIGID_STATIC) addRigidStatic(static_cast<NpRigidStatic*>(actor), false); else if(serialType1==PxConcreteType::eRIGID_DYNAMIC) addRigidDynamic(static_cast<NpRigidDynamic*>(actor), false); else if(serialType1==PxConcreteType::eARTICULATION_LINK) {} else PX_ASSERT(0); } } else if (serialType == PxConcreteType::eARTICULATION_REDUCED_COORDINATE) { NpArticulationReducedCoordinate* np = static_cast<NpArticulationReducedCoordinate*>(s); addArticulation(np, false); } else if(serialType==PxConcreteType::eARTICULATION_LINK) { // NpArticulationLink* np = static_cast<NpArticulationLink*>(s); } else if(serialType==PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { // NpArticulationJoint* np = static_cast<NpArticulationJoint*>(s); } else { // assert(0); } } } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_PVD void NpFactory::setNpFactoryListener( NpFactoryListener& inListener) { mNpFactoryListener = &inListener; addFactoryListener(inListener); } #endif /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE void releaseToPool(NpRigidStatic* np) { NpFactory::getInstance().releaseRigidStaticToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpRigidDynamic* np) { NpFactory::getInstance().releaseRigidDynamicToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpArticulationLink* np) { NpFactory::getInstance().releaseArticulationLinkToPool(*np); } static PX_FORCE_INLINE void releaseToPool(PxArticulationJointReducedCoordinate* np) { PX_ASSERT(np->getConcreteType() == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE); NpFactory::getInstance().releaseArticulationJointRCToPool(*static_cast<NpArticulationJointReducedCoordinate*>(np)); } static PX_FORCE_INLINE void releaseToPool(PxArticulationReducedCoordinate* np) { NpFactory::getInstance().releaseArticulationToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpAggregate* np) { NpFactory::getInstance().releaseAggregateToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpShape* np) { NpFactory::getInstance().releaseShapeToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpConstraint* np) { NpFactory::getInstance().releaseConstraintToPool(*np); } #if PX_SUPPORT_GPU_PHYSX static PX_FORCE_INLINE void releaseToPool(NpSoftBody* np) { NpFactory::getInstance().releaseSoftBodyToPool(*np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpFEMCloth* np) { NpFactory::getInstance().releaseFEMClothToPool(*np); } #endif static PX_FORCE_INLINE void releaseToPool(NpPBDParticleSystem* np) { NpFactory::getInstance().releasePBDParticleSystemToPool(*np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpFLIPParticleSystem* np) { NpFactory::getInstance().releaseFLIPParticleSystemToPool(*np); } #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpMPMParticleSystem* np) { NpFactory::getInstance().releaseMPMParticleSystemToPool(*np); } #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpHairSystem* np) { NpFactory::getInstance().releaseHairSystemToPool(*np); } #endif #endif template<class T> static PX_FORCE_INLINE void NpDestroy(T* np) { void* ud = np->userData; if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) releaseToPool(np); else np->~T(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud); } void physx::NpDestroyRigidActor(NpRigidStatic* np) { NpDestroy(np); } void physx::NpDestroyRigidDynamic(NpRigidDynamic* np) { NpDestroy(np); } void physx::NpDestroyAggregate(NpAggregate* np) { NpDestroy(np); } void physx::NpDestroyShape(NpShape* np) { NpDestroy(np); } void physx::NpDestroyConstraint(NpConstraint* np) { NpDestroy(np); } void physx::NpDestroyArticulationLink(NpArticulationLink* np) { NpDestroy(np); } void physx::NpDestroyArticulationJoint(PxArticulationJointReducedCoordinate* np) { NpDestroy(np); } void physx::NpDestroyArticulation(PxArticulationReducedCoordinate* np) { NpDestroy(np); } #if PX_SUPPORT_GPU_PHYSX void physx::NpDestroySoftBody(NpSoftBody* np) { NpDestroy(np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void physx::NpDestroyFEMCloth(NpFEMCloth* np) { NpDestroy(np); } #endif void physx::NpDestroyParticleSystem(NpPBDParticleSystem* np) { NpDestroy(np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void physx::NpDestroyParticleSystem(NpFLIPParticleSystem* np) { NpDestroy(np); } void physx::NpDestroyParticleSystem(NpMPMParticleSystem* np) { NpDestroy(np); } void physx::NpDestroyHairSystem(NpHairSystem* np) { NpDestroy(np); } #endif #endif
41,394
C++
32.599838
248
0.751607
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidActorTemplate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_RIGID_ACTOR_TEMPLATE_H #define NP_RIGID_ACTOR_TEMPLATE_H #include "NpActorTemplate.h" #include "NpShapeManager.h" #include "NpConstraint.h" #include "NpFactory.h" #include "NpActor.h" // PX_SERIALIZATION #include "foundation/PxErrors.h" //~PX_SERIALIZATION #include "omnipvd/NpOmniPvdSetData.h" namespace physx { template<class APIClass> class NpRigidActorTemplate : public NpActorTemplate<APIClass> { private: typedef NpActorTemplate<APIClass> ActorTemplateClass; public: // PX_SERIALIZATION NpRigidActorTemplate(PxBaseFlags baseFlags) : ActorTemplateClass(baseFlags), mShapeManager(PxEmpty)//, mIndex(0xFFFFFFFF) { NpBase::mFreeSlot = 0xFFFFFFFF; } virtual void requiresObjects(PxProcessPxBaseCallback& c); void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); //~PX_SERIALIZATION virtual ~NpRigidActorTemplate(); // The rule is: If an API method is used somewhere in here, it has to be redeclared, else GCC whines // PxActor void removeShapes(PxSceneQuerySystem* sqManager); virtual PxActorType::Enum getType() const = 0; virtual PxBounds3 getWorldBounds(float inflation=1.01f) const PX_OVERRIDE; virtual void setActorFlag(PxActorFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setActorFlags(PxActorFlags inFlags) PX_OVERRIDE; //~PxActor // PxRigidActor virtual PxU32 getInternalActorIndex() const PX_OVERRIDE; virtual bool attachShape(PxShape& s) PX_OVERRIDE; virtual void detachShape(PxShape& s, bool wakeOnLostTouch) PX_OVERRIDE; virtual PxU32 getNbShapes() const PX_OVERRIDE; virtual PxU32 getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxU32 getNbConstraints() const PX_OVERRIDE; virtual PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; //~PxRigidActor NpRigidActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type); // not optimal but the template alternative is hardly more readable and perf is not that critical here virtual void switchToNoSim() { PX_ASSERT(false); } virtual void switchFromNoSim() { PX_ASSERT(false); } PX_FORCE_INLINE NpShapeManager& getShapeManager() { return mShapeManager; } PX_FORCE_INLINE const NpShapeManager& getShapeManager() const { return mShapeManager; } void updateShaderComs(); // index for the NpScene rigid dynamic or static array // PT: note that this index changes during the lifetime of the object, e.g. when another object // is removed and swaps happen in the scene's mRigidStatics/mRigidDynamics arrays. PX_FORCE_INLINE PxU32 getRigidActorArrayIndex() const { return NpBase::mFreeSlot; } PX_FORCE_INLINE void setRigidActorArrayIndex(PxU32 index) { NpBase::mFreeSlot = index; } // PX_FORCE_INLINE PxU32 getRigidActorArrayIndex() const { return mIndex; } // PX_FORCE_INLINE void setRigidActorArrayIndex(PxU32 index) { mIndex = index; } PX_FORCE_INLINE PxU32 getRigidActorSceneIndex() const { return NpBase::getBaseIndex(); } PX_FORCE_INLINE void setRigidActorSceneIndex(PxU32 index) { NpBase::setBaseIndex(index); } bool resetFiltering_(NpActor& ro, Sc::RigidCore& core, PxShape*const* shapes, PxU32 shapeCount); #if PX_ENABLE_DEBUG_VISUALIZATION public: void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif protected: PX_FORCE_INLINE void setActorSimFlag(bool value); NpShapeManager mShapeManager; // PT: note that this index changes during the lifetime of the object, e.g. when another object // is removed and swaps happen in the scene's mRigidStatics/mRigidDynamics arrays. // PxU32 mIndex; // index for the NpScene rigid dynamic or static array // PT: TODO: reduce padding }; // PX_SERIALIZATION template<class APIClass> void NpRigidActorTemplate<APIClass>::requiresObjects(PxProcessPxBaseCallback& c) { // export shapes PxU32 nbShapes = mShapeManager.getNbShapes(); for(PxU32 i=0;i<nbShapes;i++) { NpShape* np = mShapeManager.getShapes()[i]; c.process(*np); } } template<class APIClass> void NpRigidActorTemplate<APIClass>::preExportDataReset() { //Clearing the aggregate ID for serialization so we avoid having a stale //reference after deserialization. The aggregate ID get's reset on readding to the //scene anyway. Sc::ActorCore& actorCore = NpActor::getActorCore(); actorCore.setAggregateID(PX_INVALID_U32); mShapeManager.preExportDataReset(); //mIndex = 0xFFFFFFFF; NpBase::mFreeSlot = 0xFFFFFFFF; NpBase::setBaseIndex(NP_UNUSED_BASE_INDEX); } template<class APIClass> void NpRigidActorTemplate<APIClass>::exportExtraData(PxSerializationContext& context) { mShapeManager.exportExtraData(context); ActorTemplateClass::exportExtraData(context); } template<class APIClass> void NpRigidActorTemplate<APIClass>::importExtraData(PxDeserializationContext& context) { mShapeManager.importExtraData(context); ActorTemplateClass::importExtraData(context); } template<class APIClass> void NpRigidActorTemplate<APIClass>::resolveReferences(PxDeserializationContext& context) { const PxU32 nbShapes = mShapeManager.getNbShapes(); NpShape** shapes = const_cast<NpShape**>(mShapeManager.getShapes()); for(PxU32 j=0;j<nbShapes;j++) { context.translatePxBase(shapes[j]); shapes[j]->onActorAttach(*this); } ActorTemplateClass::resolveReferences(context); } //~PX_SERIALIZATION template<class APIClass> NpRigidActorTemplate<APIClass>::NpRigidActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type) : ActorTemplateClass (concreteType, baseFlags, type) //mIndex (0xffffffff) { NpBase::mFreeSlot = 0xFFFFFFFF; } template<class APIClass> NpRigidActorTemplate<APIClass>::~NpRigidActorTemplate() { // TODO: no mechanism for notifying shaders of actor destruction yet } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getInternalActorIndex() const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); const PxU32 index = NpBase::getBaseIndex(); return index!=NP_UNUSED_BASE_INDEX ? index : 0xffffffff; } template<class APIClass> void NpRigidActorTemplate<APIClass>::removeShapes(PxSceneQuerySystem* sqManager) { if(mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::release: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } mShapeManager.detachAll(sqManager, *this); } template<class APIClass> bool NpRigidActorTemplate<APIClass>::attachShape(PxShape& shape) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); NpShape& npShape = static_cast<NpShape&>(shape); PX_CHECK_AND_RETURN_VAL(!static_cast<NpShape&>(shape).isExclusive() || shape.getActor()==NULL, "PxRigidActor::attachShape: shape must be shared or unowned", false); PX_CHECK_AND_RETURN_VAL(!(npShape.getCore().getCore().mShapeCoreFlags & PxShapeCoreFlag::eSOFT_BODY_SHAPE), "PxRigidActor::attachShape() not allowed to attach a soft body shape to a rigid actor", false); PX_CHECK_AND_RETURN_VAL(!(npShape.getCore().getCore().mShapeCoreFlags & PxShapeCoreFlag::eCLOTH_SHAPE), "PxRigidActor::attachShape() not allowed to attach a cloth shape to a rigid actor", false); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxRigidActor::attachShape() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD // invalidate the pruning structure if the actor bounds changed if (mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::attachShape: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } mShapeManager.attachShape(npShape, *this); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, shapes, static_cast<PxRigidActor&>(*this), shape) return true; } template<class APIClass> void NpRigidActorTemplate<APIClass>::detachShape(PxShape& shape, bool wakeOnLostTouch) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidActor::detachShape() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, shapes, static_cast<PxRigidActor&>(*this), shape) //this needs to happen before the actual detach happens below, because that detach might actually delete the shape, which invalidates the shape handle. if (mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::detachShape: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } if(!mShapeManager.detachShape(static_cast<NpShape&>(shape), *this, wakeOnLostTouch)) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::detachShape: shape is not attached to this actor!"); } } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getNbShapes() const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return mShapeManager.getNbShapes(); } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return mShapeManager.getShapes(buffer, bufferSize, startIndex); } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getNbConstraints() const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return ActorTemplateClass::getNbConnectors(NpConnectorType::eConstraint); } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getConstraints(PxConstraint** buffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return ActorTemplateClass::template getConnectors<PxConstraint>(NpConnectorType::eConstraint, buffer, bufferSize, startIndex); // Some people will love me for this one... The syntax is to be standard compliant and // picky gcc won't compile without it. It is needed if you call a templated member function // of a templated class } template<class APIClass> PxBounds3 NpRigidActorTemplate<APIClass>::getWorldBounds(float inflation) const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(ActorTemplateClass::getNpScene(), "PxRigidActor::getWorldBounds() not allowed while simulation is running (except during PxScene::collide()).", PxBounds3::empty()); PX_SIMD_GUARD; const PxBounds3 bounds = mShapeManager.getWorldBounds_(*this); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } template<class APIClass> PX_FORCE_INLINE void NpRigidActorTemplate<APIClass>::setActorSimFlag(bool value) { NpScene* scene = ActorTemplateClass::getNpScene(); PxActorFlags oldFlags = ActorTemplateClass::getActorFlags(); bool hadNoSimFlag = oldFlags.isSet(PxActorFlag::eDISABLE_SIMULATION); PX_CHECK_AND_RETURN((getType() != PxActorType::eARTICULATION_LINK) || (!value && !hadNoSimFlag), "PxActor::setActorFlag: PxActorFlag::eDISABLE_SIMULATION is only supported by PxRigidDynamic and PxRigidStatic objects."); if (hadNoSimFlag && (!value)) { switchFromNoSim(); ActorTemplateClass::setActorFlagsInternal(oldFlags & (~PxActorFlag::eDISABLE_SIMULATION)); // needs to be done before the code below to make sure the latest flags get picked up if (scene) NpActor::addConstraintsToScene(); } else if ((!hadNoSimFlag) && value) { if (scene) NpActor::removeConstraintsFromScene(); ActorTemplateClass::setActorFlagsInternal(oldFlags | PxActorFlag::eDISABLE_SIMULATION); switchToNoSim(); } } template<class APIClass> void NpRigidActorTemplate<APIClass>::setActorFlag(PxActorFlag::Enum flag, bool value) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidActor::setActorFlag() not allowed while simulation is running. Call will be ignored.") if (flag == PxActorFlag::eDISABLE_SIMULATION) setActorSimFlag(value); ActorTemplateClass::setActorFlagInternal(flag, value); } template<class APIClass> void NpRigidActorTemplate<APIClass>::setActorFlags(PxActorFlags inFlags) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidActor::setActorFlags() not allowed while simulation is running. Call will be ignored.") bool noSim = inFlags.isSet(PxActorFlag::eDISABLE_SIMULATION); setActorSimFlag(noSim); ActorTemplateClass::setActorFlagsInternal(inFlags); } template<class APIClass> void NpRigidActorTemplate<APIClass>::updateShaderComs() { NpConnectorIterator iter = ActorTemplateClass::getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); c->comShift(this); } } template<class APIClass> bool NpRigidActorTemplate<APIClass>::resetFiltering_(NpActor& ro, Sc::RigidCore& core, PxShape*const* shapes, PxU32 shapeCount) { #if PX_CHECKED PX_CHECK_AND_RETURN_VAL(!(ro.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxScene::resetFiltering(): Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!", false); for(PxU32 i=0; i < shapeCount; i++) { PxRigidActor* ra = shapes[i]->getActor(); if (ra != this) { bool found = false; if (ra == NULL) { NpShape*const* sh = mShapeManager.getShapes(); for(PxU32 j=0; j < mShapeManager.getNbShapes(); j++) { if (sh[j] == shapes[i]) { found = true; break; } } } PX_CHECK_AND_RETURN_VAL(found, "PxScene::resetFiltering(): specified shape not in actor!", false); } PX_CHECK_AND_RETURN_VAL(static_cast<NpShape*>(shapes[i])->getCore().getFlags() & (PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE), "PxScene::resetFiltering(): specified shapes not of type eSIMULATION_SHAPE or eTRIGGER_SHAPE!", false); } #endif PxU32 sCount; if (shapes) sCount = shapeCount; else sCount = mShapeManager.getNbShapes(); PX_ALLOCA(scShapes, NpShape*, sCount); if (scShapes) { if (shapes) // the user specified the shapes { PxU32 sAccepted = 0; for(PxU32 i=0; i < sCount; i++) scShapes[sAccepted++] = static_cast<NpShape*>(shapes[i]); sCount = sAccepted; } else // the user just specified the actor and the shapes are taken from the actor { NpShape* const* sh = mShapeManager.getShapes(); PxU32 sAccepted = 0; for(PxU32 i=0; i < sCount; i++) { if(sh[i]->getCore().getFlags() & (PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) scShapes[sAccepted++] = sh[i]; } sCount = sAccepted; } if (sCount) { PX_ASSERT(!(core.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))); PX_ASSERT(!ro.isAPIWriteForbidden()); PX_UNUSED(ro); // PT: TODO: rewrite this thing, we end up in getSimForShape() each time for(PxU32 i=0; i < sCount; i++) core.onShapeChange(scShapes[i]->getCore(), Sc::ShapeChangeNotifyFlag::eRESET_FILTERING); } } return true; } #if PX_ENABLE_DEBUG_VISUALIZATION template<class APIClass> void NpRigidActorTemplate<APIClass>::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { mShapeManager.visualize(out, scene, *this, scale); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif } #endif
17,896
C
37.488172
257
0.750726
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPtrTableStorageManager.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_PTR_TABLE_STORAGE_MANAGER_H #define NP_PTR_TABLE_STORAGE_MANAGER_H #include "foundation/PxMutex.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxBitUtils.h" #include "CmPtrTable.h" namespace physx { class NpPtrTableStorageManager : public Cm::PtrTableStorageManager, public PxUserAllocated { PX_NOCOPY(NpPtrTableStorageManager) public: NpPtrTableStorageManager() {} ~NpPtrTableStorageManager() {} // PtrTableStorageManager virtual void** allocate(PxU32 capacity) { PX_ASSERT(PxIsPowerOfTwo(capacity)); PxMutex::ScopedLock lock(mMutex); return capacity<=4 ? reinterpret_cast<void**>(mPool4.construct()) : capacity<=16 ? reinterpret_cast<void**>(mPool16.construct()) : capacity<=64 ? reinterpret_cast<void**>(mPool64.construct()) : reinterpret_cast<void**>(PX_ALLOC(capacity*sizeof(void*), "CmPtrTable pointer array")); } virtual void deallocate(void** addr, PxU32 capacity) { PX_ASSERT(PxIsPowerOfTwo(capacity)); PxMutex::ScopedLock lock(mMutex); if(capacity<=4) mPool4.destroy(reinterpret_cast< PtrBlock<4>*>(addr)); else if(capacity<=16) mPool16.destroy(reinterpret_cast< PtrBlock<16>*>(addr)); else if(capacity<=64) mPool64.destroy(reinterpret_cast< PtrBlock<64>*>(addr)); else PX_FREE(addr); } // originalCapacity is the only way we know which pool the alloc request belongs to, // so if those are no longer going to match, we need to realloc. virtual bool canReuse(PxU32 originalCapacity, PxU32 newCapacity) { PX_ASSERT(PxIsPowerOfTwo(originalCapacity)); PX_ASSERT(PxIsPowerOfTwo(newCapacity)); return poolId(originalCapacity) == poolId(newCapacity) && newCapacity<=64; } //~PtrTableStorageManager private: PxMutex mMutex; int poolId(PxU32 size) { return size<=4 ? 0 : size<=16 ? 1 : size<=64 ? 2 : 3; } template<int N> class PtrBlock { void* ptr[N]; }; PxPool2<PtrBlock<4>, 4096 > mPool4; PxPool2<PtrBlock<16>, 4096 > mPool16; PxPool2<PtrBlock<64>, 4096 > mPool64; }; } #endif
3,713
C
34.371428
97
0.74118
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPhysicsInsertionCallback.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_PHYSICS_INSERTION_CALLBACK_H #define NP_PHYSICS_INSERTION_CALLBACK_H #include "common/PxInsertionCallback.h" #include "GuTriangleMesh.h" #include "GuHeightField.h" #include "GuConvexMesh.h" #include "NpFactory.h" #include "GuTetrahedronMesh.h" namespace physx { class NpPhysicsInsertionCallback : public PxInsertionCallback { public: NpPhysicsInsertionCallback() {} virtual PxBase* buildObjectFromData(PxConcreteType::Enum type, void* data) { if(type == PxConcreteType::eTRIANGLE_MESH_BVH33 || type == PxConcreteType::eTRIANGLE_MESH_BVH34) return NpFactory::getInstance().createTriangleMesh(data); if (type == PxConcreteType::eCONVEX_MESH) return NpFactory::getInstance().createConvexMesh(data); if (type == PxConcreteType::eHEIGHTFIELD) return NpFactory::getInstance().createHeightField(data); if (type == PxConcreteType::eBVH) return NpFactory::getInstance().createBVH(data); if (type == PxConcreteType::eTETRAHEDRON_MESH) return NpFactory::getInstance().createTetrahedronMesh(data); if (type == PxConcreteType::eSOFTBODY_MESH) return NpFactory::getInstance().createSoftBodyMesh(data); PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Inserting object failed: " "Object type not supported for buildObjectFromData."); return NULL; } }; } #endif
3,045
C
38.558441
99
0.757635
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpHairSystem.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef NP_HAIR_SYSTEM_H #define NP_HAIR_SYSTEM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxHairSystem.h" #include "ScHairSystemCore.h" #include "NpActorTemplate.h" namespace physx { class NpScene; class NpShape; class NpHairSystem : public NpActorTemplate<PxHairSystem> { public: template <class T> class MemoryWithAlloc { PX_NOCOPY(MemoryWithAlloc) public: MemoryWithAlloc() : mData(NULL), mSize(0), mAlloc(NULL) {} ~MemoryWithAlloc() { deallocate(); } void allocate(uint32_t size) { if (size == mSize) return; deallocate(); if (size > 0) { mData = reinterpret_cast<T*>(mAlloc->allocate(sizeof(T) * size, 0, PX_FL)); if (mData != NULL) mSize = size; } else { mData = NULL; mSize = 0; } } void setAllocatorCallback(physx::PxVirtualAllocatorCallback* cb) { if (mSize > 0) { deallocate(); } mAlloc = cb; } void reset() { if (mSize > 0) { deallocate(); } } void swap(MemoryWithAlloc<T>& other) { physx::PxSwap(mData, other.mData); physx::PxSwap(mSize, other.mSize); physx::PxSwap(mAlloc, other.mAlloc); } uint32_t size() const { return mSize; } const T& operator[](uint32_t i) const { PX_ASSERT(i < mSize); return mData[i]; } T& operator[](uint32_t i) { PX_ASSERT(i < mSize); return mData[i]; } const T* begin() const { return mData; } T* begin() { return mData; } private: void deallocate() { if (mSize > 0) { mAlloc->deallocate(mData); mSize = 0; } } private: T* mData; uint32_t mSize; physx::PxVirtualAllocatorCallback* mAlloc; }; public: NpHairSystem(PxCudaContextManager& cudaContextManager); NpHairSystem(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager); virtual ~NpHairSystem() PX_OVERRIDE; // external API virtual void release() PX_OVERRIDE; virtual PxActorType::Enum getType() const PX_OVERRIDE { return PxActorType::eHAIRSYSTEM; } virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const PX_OVERRIDE; virtual void setHairSystemFlag(PxHairSystemFlag::Enum flag, bool val) PX_OVERRIDE; virtual void setHairSystemFlags(PxHairSystemFlags flags) PX_OVERRIDE { mCore.setFlags(flags); } virtual PxHairSystemFlags getHairSystemFlags() const PX_OVERRIDE { return mCore.getFlags(); } virtual void setReadRequestFlag(PxHairSystemData::Enum flag, bool val) PX_OVERRIDE; virtual void setReadRequestFlags(PxHairSystemDataFlags flags) PX_OVERRIDE; virtual PxHairSystemDataFlags getReadRequestFlags() const PX_OVERRIDE; virtual void setBendingRestAngles(const PxReal* bendingRestAngles, PxReal bendingCompliance) PX_OVERRIDE; virtual void setTwistingCompliance(PxReal twistingCompliance) PX_OVERRIDE; virtual void getTwistingRestPositions(PxReal* buffer) PX_OVERRIDE; virtual PxCudaContextManager* getCudaContextManager() const PX_OVERRIDE { return mCudaContextManager; } virtual void setWakeCounter(PxReal wakeCounterValue) PX_OVERRIDE; virtual PxReal getWakeCounter() const PX_OVERRIDE; virtual bool isSleeping() const PX_OVERRIDE; virtual void setRestPositions(PxVec4* restPos, bool isGpuPtr) PX_OVERRIDE; virtual PxVec4* getRestPositionsGpu() PX_OVERRIDE; virtual void addRigidAttachment(const PxRigidBody& rigidBody) PX_OVERRIDE; virtual void removeRigidAttachment(const PxRigidBody& rigidBody) PX_OVERRIDE; virtual void setRigidAttachments(PxParticleRigidAttachment* attachments, PxU32 numAttachments, bool isGpuPtr) PX_OVERRIDE; virtual PxParticleRigidAttachment* getRigidAttachmentsGpu(PxU32* numAttachments = NULL) PX_OVERRIDE; virtual PxU32 addSoftbodyAttachment(const PxSoftBody& softbody, const PxU32* tetIds, const PxVec4* tetmeshBarycentrics, const PxU32* hairVertices, PxConeLimitedConstraint* constraints, PxReal* constraintOffsets, PxU32 numAttachments) PX_OVERRIDE; virtual void removeSoftbodyAttachment(const PxSoftBody& softbody, PxU32 handle) PX_OVERRIDE; virtual void initFromDesc(const PxHairSystemDesc& desc) PX_OVERRIDE; virtual void setTopology(PxVec4* vertexPositionsInvMass, PxVec4* vertexVelocities, const PxU32* strandPastEndIndices, PxReal segmentLength, PxReal segmentRadius, PxU32 numVertices, PxU32 numStrands, const PxBounds3& bounds) PX_OVERRIDE; virtual void setLevelOfDetailGradations(const PxReal* proportionOfStrands, const PxReal* proportionOfVertices, PxU32 numLevels) PX_OVERRIDE; virtual void setLevelOfDetail(PxU32 level) PX_OVERRIDE; virtual PxU32 getLevelOfDetail(PxU32* numLevels) const PX_OVERRIDE; virtual void setPositionsInvMass(PxVec4* vertexPositionsInvMass, const PxBounds3& bounds) PX_OVERRIDE; virtual PxVec4* getPositionInvMass() PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mPositionInvMass; } virtual const PxVec4* getPositionInvMass() const PX_OVERRIDE{ return mCore.getShapeCore().getLLCore().mPositionInvMass; } virtual const PxVec4* getPositionInvMassGpuSim() const PX_OVERRIDE{ return mCore.getShapeCore().getLLCore().mPositionInvMassGpuSim; } virtual void setVelocities(PxVec4* vertexVelocities) PX_OVERRIDE; virtual PxVec4* getVelocities() PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mVelocity; } virtual const PxVec4* getVelocities() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mVelocity; } virtual PxU32 getNumVertices() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mNumVertices; } virtual PxU32 getNumStrands() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mNumStrands; } virtual const PxU32* getStrandPastEndIndices() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mStrandPastEndIndices; } virtual const PxU32* getStrandPastEndIndicesGpuSim() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mStrandPastEndIndicesGpuSim; } virtual void setSolverIterationCounts(PxU32 iters) PX_OVERRIDE; virtual PxU32 getSolverIterationCounts() const PX_OVERRIDE; virtual void setWind(const PxVec3& wind) PX_OVERRIDE; virtual PxVec3 getWind() const PX_OVERRIDE; virtual void setAerodynamicDrag(PxReal dragCoefficient) PX_OVERRIDE; virtual PxReal getAerodynamicDrag() const PX_OVERRIDE; virtual void setAerodynamicLift(PxReal liftCoefficient) PX_OVERRIDE; virtual PxReal getAerodynamicLift() const PX_OVERRIDE; virtual void setSegmentRadius(PxReal radius) PX_OVERRIDE; virtual void getSegmentDimensions(PxReal& length, PxReal& radius) const PX_OVERRIDE; virtual void setFrictionParameters(PxReal interHairVelDamping, PxReal frictionCoeff) PX_OVERRIDE; virtual void getFrictionParameters(PxReal& interHairVelDamping, PxReal& frictionCoeff) const PX_OVERRIDE; virtual void setMaxDepenetrationVelocity(PxReal maxDepenetrationVelocity) PX_OVERRIDE; virtual PxReal getMaxDepenetrationVelocity() const PX_OVERRIDE; virtual void setShapeCompliance(PxReal startCompliance, PxReal strandRatio) PX_OVERRIDE; virtual void getShapeCompliance(PxReal& startCompliance, PxReal& strandRatio) const PX_OVERRIDE; virtual void setInterHairRepulsion(PxReal repulsion) PX_OVERRIDE; virtual PxReal getInterHairRepulsion() const PX_OVERRIDE; virtual void setSelfCollisionRelaxation(PxReal relaxation) PX_OVERRIDE; virtual PxReal getSelfCollisionRelaxation() const PX_OVERRIDE; virtual void setStretchingRelaxation(PxReal relaxation) PX_OVERRIDE; virtual PxReal getStretchingRelaxation() const PX_OVERRIDE; virtual void setContactOffset(PxReal contactOffset) PX_OVERRIDE; virtual PxReal getContactOffset() const PX_OVERRIDE; virtual void setHairContactOffset(PxReal hairContactOffset) PX_OVERRIDE; virtual PxReal getHairContactOffset() const PX_OVERRIDE; virtual void setShapeMatchingParameters(PxReal compliance, PxReal linearStretching, PxU16 numVerticesPerGroup, PxU16 numVerticesOverlap) PX_OVERRIDE; virtual PxReal getShapeMatchingCompliance() const PX_OVERRIDE; #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& npScene) const; #endif PX_FORCE_INLINE const Sc::HairSystemCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::HairSystemCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpHairSystem, mCore); } // Debug name void setName(const char*); const char* getName() const; private: void init(); void setLlGridSize(const PxBounds3& bounds); void createAllocator(); void releaseAllocator(); private: Sc::HairSystemCore mCore; PxHairSystemGeometry mGeometry; PxCudaContextManager* mCudaContextManager; PxsMemoryManager* mMemoryManager; PxVirtualAllocatorCallback* mHostMemoryAllocator; PxVirtualAllocatorCallback* mDeviceMemoryAllocator; // internal buffers populated when hair system initialized from desc instead of user-provided buffers MemoryWithAlloc<PxVec4> mPosInvMassInternal; MemoryWithAlloc<PxVec4> mVelInternal; MemoryWithAlloc<PxU32> mStrandPastEndIndicesInternal; // internal buffers in case user gives us CPU-buffers MemoryWithAlloc<PxParticleRigidAttachment> mParticleRigidAttachmentsInternal; MemoryWithAlloc<PxVec4> mRestPositionsInternal; PxArray<PxReal> mLodProportionOfStrands; PxArray<PxReal> mLodProportionOfVertices; PxHashMap<PxU32, PxPair<PxU32, PxU32>> mSoftbodyAttachmentsOffsets; // map from handle to {offset, size} PxPinnedArray<Dy::SoftbodyHairAttachment> mSoftbodyAttachments; }; } #endif #endif #endif
11,371
C
38.486111
154
0.755255
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidBodyTemplate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_RIGIDBODY_TEMPLATE_H #define NP_RIGIDBODY_TEMPLATE_H #include "NpRigidActorTemplate.h" #include "ScBodyCore.h" #include "NpPhysics.h" #include "NpShape.h" #include "NpScene.h" #include "CmVisualization.h" #include "NpDebugViz.h" #include "omnipvd/NpOmniPvdSetData.h" #if PX_SUPPORT_PVD // PT: updatePvdProperties() is overloaded and the compiler needs to know 'this' type to do the right thing. // Thus we can't just move this as an inlined Base function. #define UPDATE_PVD_PROPERTY_BODY \ { \ NpScene* sceneForPVD = RigidActorTemplateClass::getNpScene(); /* shared shapes also return zero here */ \ if(sceneForPVD) \ sceneForPVD->getScenePvdClientInternal().updateBodyPvdProperties(static_cast<NpActor*>(this)); \ } #else #define UPDATE_PVD_PROPERTY_BODY #endif namespace physx { PX_INLINE PxVec3 invertDiagInertia(const PxVec3& m) { return PxVec3( m.x == 0.0f ? 0.0f : 1.0f/m.x, m.y == 0.0f ? 0.0f : 1.0f/m.y, m.z == 0.0f ? 0.0f : 1.0f/m.z); } #if PX_ENABLE_DEBUG_VISUALIZATION /* given the diagonal of the body space inertia tensor, and the total mass this returns the body space AABB width, height and depth of an equivalent box */ PX_INLINE PxVec3 getDimsFromBodyInertia(const PxVec3& inertiaMoments, PxReal mass) { const PxVec3 inertia = inertiaMoments * (6.0f/mass); return PxVec3( PxSqrt(PxAbs(- inertia.x + inertia.y + inertia.z)), PxSqrt(PxAbs(+ inertia.x - inertia.y + inertia.z)), PxSqrt(PxAbs(+ inertia.x + inertia.y - inertia.z))); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif template<class APIClass> class NpRigidBodyTemplate : public NpRigidActorTemplate<APIClass> { protected: typedef NpRigidActorTemplate<APIClass> RigidActorTemplateClass; public: // PX_SERIALIZATION NpRigidBodyTemplate(PxBaseFlags baseFlags) : RigidActorTemplateClass(baseFlags), mCore(PxEmpty) {} //~PX_SERIALIZATION virtual ~NpRigidBodyTemplate(); // The rule is: If an API method is used somewhere in here, it has to be redeclared, else GCC whines // PxRigidActor virtual PxTransform getGlobalPose() const = 0; virtual bool attachShape(PxShape& shape) PX_OVERRIDE; //~PxRigidActor // PxRigidBody virtual PxTransform getCMassLocalPose() const PX_OVERRIDE; virtual void setMass(PxReal mass) PX_OVERRIDE; virtual PxReal getMass() const PX_OVERRIDE; virtual PxReal getInvMass() const PX_OVERRIDE; virtual void setMassSpaceInertiaTensor(const PxVec3& m) PX_OVERRIDE; virtual PxVec3 getMassSpaceInertiaTensor() const PX_OVERRIDE; virtual PxVec3 getMassSpaceInvInertiaTensor() const PX_OVERRIDE; virtual void setLinearDamping(PxReal linDamp) PX_OVERRIDE; virtual PxReal getLinearDamping() const PX_OVERRIDE; virtual void setAngularDamping(PxReal angDamp) PX_OVERRIDE; virtual PxReal getAngularDamping() const PX_OVERRIDE; virtual PxVec3 getLinearVelocity() const PX_OVERRIDE; virtual PxVec3 getAngularVelocity() const PX_OVERRIDE; virtual void setMaxLinearVelocity(PxReal maxLinVel) PX_OVERRIDE; virtual PxReal getMaxLinearVelocity() const PX_OVERRIDE; virtual void setMaxAngularVelocity(PxReal maxAngVel) PX_OVERRIDE; virtual PxReal getMaxAngularVelocity() const PX_OVERRIDE; //~PxRigidBody //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpRigidBodyTemplate(PxType concreteType, PxBaseFlags baseFlags, const PxActorType::Enum type, NpType::Enum npType, const PxTransform& bodyPose); PX_FORCE_INLINE const Sc::BodyCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::BodyCore& getCore() { return mCore; } // Flags virtual void setRigidBodyFlag(PxRigidBodyFlag::Enum, bool value) PX_OVERRIDE; virtual void setRigidBodyFlags(PxRigidBodyFlags inFlags) PX_OVERRIDE; PX_FORCE_INLINE PxRigidBodyFlags getRigidBodyFlagsFast() const { return mCore.getFlags(); } virtual PxRigidBodyFlags getRigidBodyFlags() const PX_OVERRIDE { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return getRigidBodyFlagsFast() & ~PxRigidBodyFlag::eRESERVED; } virtual void setMinCCDAdvanceCoefficient(PxReal advanceCoefficient) PX_OVERRIDE; virtual PxReal getMinCCDAdvanceCoefficient() const PX_OVERRIDE; virtual void setMaxDepenetrationVelocity(PxReal maxDepenVel) PX_OVERRIDE; virtual PxReal getMaxDepenetrationVelocity() const PX_OVERRIDE; virtual void setMaxContactImpulse(PxReal maxDepenVel) PX_OVERRIDE; virtual PxReal getMaxContactImpulse() const PX_OVERRIDE; virtual void setContactSlopCoefficient(PxReal slopCoefficient) PX_OVERRIDE; virtual PxReal getContactSlopCoefficient() const PX_OVERRIDE; virtual PxNodeIndex getInternalIslandNodeIndex() const PX_OVERRIDE; protected: void setCMassLocalPoseInternal(const PxTransform&); void addSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode); void clearSpatialForce(PxForceMode::Enum mode, bool force, bool torque); void setSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode); PX_FORCE_INLINE void setRigidBodyFlagsInternal(const PxRigidBodyFlags& currentFlags, const PxRigidBodyFlags& newFlags); public: #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif PX_FORCE_INLINE bool isKinematic() const { return (APIClass::getConcreteType() == PxConcreteType::eRIGID_DYNAMIC) && (mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC); } PX_INLINE void scSetSolverIterationCounts(PxU16 c) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setSolverIterationCounts(c); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetLockFlags(PxRigidDynamicLockFlags f) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setRigidDynamicLockFlags(f); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetBody2World(const PxTransform& p) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setBody2World(p); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetCMassLocalPose(const PxTransform& newBody2Actor) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setCMassLocalPose(newBody2Actor); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetLinearVelocity(const PxVec3& v) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setLinearVelocity(v); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetAngularVelocity(const PxVec3& v) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setAngularVelocity(v); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scWakeUpInternal(PxReal wakeCounter) { PX_ASSERT(RigidActorTemplateClass::getNpScene()); PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.wakeUp(wakeCounter); } PX_FORCE_INLINE void scWakeUp() { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); NpScene* scene = RigidActorTemplateClass::getNpScene(); PX_ASSERT(scene); // only allowed for an object in a scene scWakeUpInternal(scene->getWakeCounterResetValueInternal()); } PX_INLINE void scPutToSleepInternal() { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.putToSleep(); } PX_FORCE_INLINE void scPutToSleep() { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); scPutToSleepInternal(); } PX_INLINE void scSetWakeCounter(PxReal w) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setWakeCounter(w); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetFlags(PxRigidBodyFlags f) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setFlags(f); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scAddSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.addSpatialAcceleration(linAcc, angAcc); //Spatial acceleration isn't sent to PVD. } PX_INLINE void scSetSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setSpatialAcceleration(linAcc, angAcc); //Spatial acceleration isn't sent to PVD. } PX_INLINE void scClearSpatialAcceleration(bool force, bool torque) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.clearSpatialAcceleration(force, torque); //Spatial acceleration isn't sent to PVD. } PX_INLINE void scAddSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.addSpatialVelocity(linVelDelta, angVelDelta); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scClearSpatialVelocity(bool force, bool torque) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.clearSpatialVelocity(force, torque); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetKinematicTarget(const PxTransform& p) { NpScene* scene = RigidActorTemplateClass::getNpScene(); PX_ASSERT(scene); // only allowed for an object in a scene const PxReal wakeCounterResetValue = scene->getWakeCounterResetValueInternal(); PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setKinematicTarget(p, wakeCounterResetValue); UPDATE_PVD_PROPERTY_BODY #if PX_SUPPORT_PVD scene->getScenePvdClientInternal().updateKinematicTarget(this, p); #endif } PX_INLINE PxMat33 scGetGlobalInertiaTensorInverse() const { PxMat33 inverseInertiaWorldSpace; Cm::transformInertiaTensor(mCore.getInverseInertia(), PxMat33Padded(mCore.getBody2World().q), inverseInertiaWorldSpace); return inverseInertiaWorldSpace; } PX_FORCE_INLINE bool scCheckSleepReadinessBesidesWakeCounter() { return (getLinearVelocity().isZero() && getAngularVelocity().isZero()); // no need to test for pending force updates yet since currently this is not supported on scene insertion } protected: Sc::BodyCore mCore; }; template<class APIClass> NpRigidBodyTemplate<APIClass>::NpRigidBodyTemplate(PxType concreteType, PxBaseFlags baseFlags, PxActorType::Enum type, NpType::Enum npType, const PxTransform& bodyPose) : RigidActorTemplateClass (concreteType, baseFlags, npType), mCore (type, bodyPose) { } template<class APIClass> NpRigidBodyTemplate<APIClass>::~NpRigidBodyTemplate() { } namespace { PX_FORCE_INLINE static bool hasNegativeMass(const PxShape& shape) { const PxGeometry& geom = shape.getGeometry(); const PxGeometryType::Enum t = geom.getType(); if (t == PxGeometryType::eTRIANGLEMESH) { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const Gu::TriangleMesh* mesh = static_cast<const Gu::TriangleMesh*>(triGeom.triangleMesh); return mesh->getSdfDataFast().mSdf != NULL && mesh->getMass() < 0.f; } return false; } PX_FORCE_INLINE static bool isDynamicMesh(const PxGeometry& geom) { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const Gu::TriangleMesh* mesh = static_cast<const Gu::TriangleMesh*>(triGeom.triangleMesh); return mesh->getSdfDataFast().mSdf != NULL && mesh->getMass() > 0.f; } PX_FORCE_INLINE static bool isSimGeom(const PxShape& shape) { const PxGeometryType::Enum t = shape.getGeometry().getType(); return t != PxGeometryType::ePLANE && t != PxGeometryType::eHEIGHTFIELD && t != PxGeometryType::eTETRAHEDRONMESH && (t != PxGeometryType::eTRIANGLEMESH || isDynamicMesh(shape.getGeometry())); } } template<class APIClass> bool NpRigidBodyTemplate<APIClass>::attachShape(PxShape& shape) { NP_WRITE_CHECK(RigidActorTemplateClass::getNpScene()); PX_CHECK_AND_RETURN_VAL(!(shape.getFlags() & PxShapeFlag::eSIMULATION_SHAPE) || !hasNegativeMass(shape) || isKinematic(), "attachShape: The faces of the mesh are oriented the wrong way round leading to a negative mass. Please invert the orientation of all faces and try again.", false); PX_CHECK_AND_RETURN_VAL(!(shape.getFlags() & PxShapeFlag::eSIMULATION_SHAPE) || isSimGeom(shape) || isKinematic(), "attachShape: non-SDF triangle mesh, tetrahedron mesh, heightfield or plane geometry shapes configured as eSIMULATION_SHAPE are not supported for non-kinematic PxRigidDynamic instances.", false); return RigidActorTemplateClass::attachShape(shape); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setCMassLocalPoseInternal(const PxTransform& body2Actor) { //the point here is to change the mass distribution w/o changing the actors' pose in the world // AD note: I added an interface directly into the bodycore and pushed calculations there to avoid // NP and BP transform/bounds update notifications because this does not change the global pose. scSetCMassLocalPose(body2Actor); RigidActorTemplateClass::updateShaderComs(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, cMassLocalPose, static_cast<PxRigidBody&>(*this), body2Actor) } template<class APIClass> PxTransform NpRigidBodyTemplate<APIClass>::getCMassLocalPose() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getBody2Actor(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMass(PxReal mass) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(mass), "PxRigidBody::setMass(): invalid float"); PX_CHECK_AND_RETURN(mass>=0, "PxRigidBody::setMass(): mass must be non-negative!"); PX_CHECK_AND_RETURN(this->getType() != PxActorType::eARTICULATION_LINK || mass > 0.0f, "PxRigidBody::setMass(): components must be > 0 for articulations"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMass() not allowed while simulation is running. Call will be ignored.") mCore.setInverseMass(mass > 0.0f ? 1.0f/mass : 0.0f); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, mass, static_cast<PxRigidBody&>(*this), mass) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMass() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); const PxReal invMass = mCore.getInverseMass(); return invMass > 0.0f ? 1.0f/invMass : 0.0f; } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getInvMass() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getInverseMass(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMassSpaceInertiaTensor(const PxVec3& m) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(m.isFinite(), "PxRigidBody::setMassSpaceInertiaTensor(): invalid inertia"); PX_CHECK_AND_RETURN(m.x>=0.0f && m.y>=0.0f && m.z>=0.0f, "PxRigidBody::setMassSpaceInertiaTensor(): components must be non-negative"); PX_CHECK_AND_RETURN(this->getType() != PxActorType::eARTICULATION_LINK || (m.x > 0.0f && m.y > 0.0f && m.z > 0.0f), "PxRigidBody::setMassSpaceInertiaTensor(): components must be > 0 for articulations"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMassSpaceInertiaTensor() not allowed while simulation is running. Call will be ignored.") mCore.setInverseInertia(invertDiagInertia(m)); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, massSpaceInertiaTensor, static_cast<PxRigidBody&>(*this), m) } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getMassSpaceInertiaTensor() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return invertDiagInertia(mCore.getInverseInertia()); } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getMassSpaceInvInertiaTensor() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getInverseInertia(); } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getLinearVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(RigidActorTemplateClass::getNpScene(), "PxRigidBody::getLinearVelocity() not allowed while simulation is running (except during PxScene::collide()).", PxVec3(PxZero)); return mCore.getLinearVelocity(); } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getAngularVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(RigidActorTemplateClass::getNpScene(), "PxRigidBody::getAngularVelocity() not allowed while simulation is running (except during PxScene::collide()).", PxVec3(PxZero)); return mCore.getAngularVelocity(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::addSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); switch (mode) { case PxForceMode::eFORCE: { PxVec3 linAcc, angAcc; if (force) { linAcc = (*force) * mCore.getInverseMass(); force = &linAcc; } if (torque) { angAcc = scGetGlobalInertiaTensorInverse() * (*torque); torque = &angAcc; } scAddSpatialAcceleration(force, torque); } break; case PxForceMode::eACCELERATION: scAddSpatialAcceleration(force, torque); break; case PxForceMode::eIMPULSE: { PxVec3 linVelDelta, angVelDelta; if (force) { linVelDelta = ((*force) * mCore.getInverseMass()); force = &linVelDelta; } if (torque) { angVelDelta = (scGetGlobalInertiaTensorInverse() * (*torque)); torque = &angVelDelta; } scAddSpatialVelocity(force, torque); } break; case PxForceMode::eVELOCITY_CHANGE: scAddSpatialVelocity(force, torque); break; } } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); switch (mode) { case PxForceMode::eFORCE: { PxVec3 linAcc, angAcc; if (force) { linAcc = (*force) * mCore.getInverseMass(); force = &linAcc; } if (torque) { angAcc = scGetGlobalInertiaTensorInverse() * (*torque); torque = &angAcc; } scSetSpatialAcceleration(force, torque); } break; case PxForceMode::eACCELERATION: scSetSpatialAcceleration(force, torque); break; case PxForceMode::eIMPULSE: { PxVec3 linVelDelta, angVelDelta; if (force) { linVelDelta = ((*force) * mCore.getInverseMass()); force = &linVelDelta; } if (torque) { angVelDelta = (scGetGlobalInertiaTensorInverse() * (*torque)); torque = &angVelDelta; } scAddSpatialVelocity(force, torque); } break; case PxForceMode::eVELOCITY_CHANGE: scAddSpatialVelocity(force, torque); break; } } template<class APIClass> void NpRigidBodyTemplate<APIClass>::clearSpatialForce(PxForceMode::Enum mode, bool force, bool torque) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); switch (mode) { case PxForceMode::eFORCE: case PxForceMode::eACCELERATION: scClearSpatialAcceleration(force, torque); break; case PxForceMode::eIMPULSE: case PxForceMode::eVELOCITY_CHANGE: scClearSpatialVelocity(force, torque); break; } } #if PX_ENABLE_DEBUG_VISUALIZATION template<class APIClass> void NpRigidBodyTemplate<APIClass>::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { RigidActorTemplateClass::visualize(out, scene, scale); visualizeRigidBody(out, scene, *this, mCore, scale); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif template<class APIClass> PX_FORCE_INLINE void NpRigidBodyTemplate<APIClass>::setRigidBodyFlagsInternal(const PxRigidBodyFlags& currentFlags, const PxRigidBodyFlags& newFlags) { PxRigidBodyFlags filteredNewFlags = newFlags; //Test to ensure we are not enabling both CCD and kinematic state on a body. This is unsupported if((filteredNewFlags & PxRigidBodyFlag::eENABLE_CCD) && (filteredNewFlags & PxRigidBodyFlag::eKINEMATIC)) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBody::setRigidBodyFlag(): kinematic bodies with CCD enabled are not supported! CCD will be ignored."); filteredNewFlags &= PxRigidBodyFlags(~PxRigidBodyFlag::eENABLE_CCD); } NpScene* scene = RigidActorTemplateClass::getNpScene(); Sc::Scene* scScene = scene ? &scene->getScScene() : NULL; const bool isKinematic = currentFlags & PxRigidBodyFlag::eKINEMATIC; const bool willBeKinematic = filteredNewFlags & PxRigidBodyFlag::eKINEMATIC; const bool kinematicSwitchingToDynamic = isKinematic && (!willBeKinematic); const bool dynamicSwitchingToKinematic = (!isKinematic) && willBeKinematic; bool mustUpdateSQ = false; if(kinematicSwitchingToDynamic) { NpShapeManager& shapeManager = this->getShapeManager(); PxU32 nbShapes = shapeManager.getNbShapes(); NpShape*const* shapes = shapeManager.getShapes(); bool hasTriangleMesh = false; for(PxU32 i=0;i<nbShapes;i++) { if((shapes[i]->getFlags() & PxShapeFlag::eSIMULATION_SHAPE) && (shapes[i]->getGeometryTypeFast()==PxGeometryType::eTRIANGLEMESH || shapes[i]->getGeometryTypeFast()==PxGeometryType::ePLANE || shapes[i]->getGeometryTypeFast()==PxGeometryType::eHEIGHTFIELD)) { hasTriangleMesh = true; break; } } if(hasTriangleMesh) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBody::setRigidBodyFlag(): dynamic meshes/planes/heightfields are not supported!"); return; } PxTransform bodyTarget; if ((currentFlags & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) && mCore.getKinematicTarget(bodyTarget) && scene) mustUpdateSQ = true; if(scScene) { scScene->decreaseNumKinematicsCounter(); scScene->increaseNumDynamicsCounter(); } } else if (dynamicSwitchingToKinematic) { if (this->getType() == PxActorType::eARTICULATION_LINK) { //We're an articulation, raise an issue PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBody::setRigidBodyFlag(): kinematic articulation links are not supported!"); return; } if(scScene) { scScene->decreaseNumDynamicsCounter(); scScene->increaseNumKinematicsCounter(); } } const bool kinematicSwitchingUseTargetForSceneQuery = isKinematic && willBeKinematic && ((currentFlags & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) != (filteredNewFlags & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES)); if (kinematicSwitchingUseTargetForSceneQuery) { PxTransform bodyTarget; if (mCore.getKinematicTarget(bodyTarget) && scene) mustUpdateSQ = true; } scSetFlags(filteredNewFlags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, static_cast<PxRigidBody&>(*this), filteredNewFlags) // PT: the SQ update should be done after the scSetFlags() call if(mustUpdateSQ) this->getShapeManager().markActorForSQUpdate(scene->getSQAPI(), *this); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setRigidBodyFlag(PxRigidBodyFlag::Enum flag, bool value) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setRigidBodyFlag() not allowed while simulation is running. Call will be ignored.") const PxRigidBodyFlags currentFlags = mCore.getFlags(); const PxRigidBodyFlags newFlags = value ? currentFlags | flag : currentFlags & (~PxRigidBodyFlags(flag)); setRigidBodyFlagsInternal(currentFlags, newFlags); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setRigidBodyFlags(PxRigidBodyFlags inFlags) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setRigidBodyFlags() not allowed while simulation is running. Call will be ignored.") const PxRigidBodyFlags currentFlags = mCore.getFlags(); setRigidBodyFlagsInternal(currentFlags, inFlags); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMinCCDAdvanceCoefficient(PxReal minCCDAdvanceCoefficient) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMinCCDAdvanceCoefficient() not allowed while simulation is running. Call will be ignored.") mCore.setCCDAdvanceCoefficient(minCCDAdvanceCoefficient); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, minAdvancedCCDCoefficient, static_cast<PxRigidBody&>(*this), minCCDAdvanceCoefficient) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMinCCDAdvanceCoefficient() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getCCDAdvanceCoefficient(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxDepenetrationVelocity(PxReal maxDepenVel) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(maxDepenVel > 0.0f, "PxRigidBody::setMaxDepenetrationVelocity(): maxDepenVel must be greater than zero."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxDepenetrationVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxPenetrationBias(-maxDepenVel); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxDepenetrationVelocity, static_cast<PxRigidBody&>(*this), maxDepenVel) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxDepenetrationVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return -mCore.getMaxPenetrationBias(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxContactImpulse(const PxReal maxImpulse) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(maxImpulse >= 0.f, "PxRigidBody::setMaxContactImpulse(): impulse limit must be greater than or equal to zero."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxContactImpulse() not allowed while simulation is running. Call will be ignored.") mCore.setMaxContactImpulse(maxImpulse); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxContactImpulse, static_cast<PxRigidBody&>(*this), maxImpulse) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxContactImpulse() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getMaxContactImpulse(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setContactSlopCoefficient(const PxReal contactSlopCoefficient) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(contactSlopCoefficient >= 0.f, "PxRigidBody::setContactSlopCoefficient(): contact slop coefficientmust be greater than or equal to zero."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setContactSlopCoefficient() not allowed while simulation is running. Call will be ignored.") mCore.setOffsetSlop(contactSlopCoefficient); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, contactSlopCoefficient, static_cast<PxRigidBody&>(*this), contactSlopCoefficient) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getContactSlopCoefficient() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getOffsetSlop(); } template<class APIClass> PxNodeIndex NpRigidBodyTemplate<APIClass>::getInternalIslandNodeIndex() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getInternalIslandNodeIndex(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setLinearDamping(PxReal linearDamping) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(linearDamping), "PxRigidBody::setLinearDamping(): invalid float"); PX_CHECK_AND_RETURN(linearDamping >= 0, "PxRigidBody::setLinearDamping(): The linear damping must be nonnegative!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setLinearDamping() not allowed while simulation is running. Call will be ignored.") mCore.setLinearDamping(linearDamping); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearDamping, static_cast<PxRigidBody&>(*this), linearDamping) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getLinearDamping() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getLinearDamping(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setAngularDamping(PxReal angularDamping) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(angularDamping), "PxRigidBody::setAngularDamping(): invalid float"); PX_CHECK_AND_RETURN(angularDamping>=0, "PxRigidBody::setAngularDamping(): The angular damping must be nonnegative!") PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setAngularDamping() not allowed while simulation is running. Call will be ignored.") mCore.setAngularDamping(angularDamping); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularDamping, static_cast<PxRigidBody&>(*this), angularDamping) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getAngularDamping() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getAngularDamping(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxAngularVelocity(PxReal maxAngularVelocity) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(maxAngularVelocity), "PxRigidBody::setMaxAngularVelocity(): invalid float"); PX_CHECK_AND_RETURN(maxAngularVelocity>=0.0f, "PxRigidBody::setMaxAngularVelocity(): threshold must be non-negative!"); PX_CHECK_AND_RETURN(maxAngularVelocity <= PxReal(1.00000003e+16f), "PxRigidBody::setMaxAngularVelocity(): maxAngularVelocity*maxAngularVelocity must be less than 1e16"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxAngularVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxAngVelSq(maxAngularVelocity * maxAngularVelocity); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxAngularVelocity, static_cast<PxRigidBody&>(*this), maxAngularVelocity) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxAngularVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return PxSqrt(mCore.getMaxAngVelSq()); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxLinearVelocity(PxReal maxLinearVelocity) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(maxLinearVelocity), "PxRigidBody::setMaxLinearVelocity(): invalid float"); PX_CHECK_AND_RETURN(maxLinearVelocity >= 0.0f, "PxRigidBody::setMaxLinearVelocity(): threshold must be non-negative!"); PX_CHECK_AND_RETURN(maxLinearVelocity <= PxReal(1.00000003e+16), "PxRigidBody::setMaxLinearVelocity(): maxLinearVelocity*maxLinearVelocity must be less than 1e16"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxLinearVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxLinVelSq(maxLinearVelocity * maxLinearVelocity); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxLinearVelocity, static_cast<PxRigidBody&>(*this), maxLinearVelocity) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxLinearVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return PxSqrt(mCore.getMaxLinVelSq()); } } #endif
34,983
C
36.536481
258
0.739816
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMetaData.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxIO.h" #include "PxPhysicsSerialization.h" #include "NpShape.h" #include "NpShapeManager.h" #include "NpConstraint.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationLink.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationSensor.h" #include "NpArticulationTendon.h" #include "NpAggregate.h" #include "NpPruningStructure.h" #include "NpMaterial.h" #include "NpFEMSoftBodyMaterial.h" #include "NpFEMClothMaterial.h" #include "NpMPMMaterial.h" #include "NpFLIPMaterial.h" #include "NpPBDMaterial.h" #include "GuConvexMesh.h" #include "GuTriangleMesh.h" #include "GuTriangleMeshBV4.h" #include "GuTriangleMeshRTree.h" #include "GuHeightField.h" #include "GuPrunerMergeData.h" using namespace physx; using namespace Cm; using namespace Gu; /////////////////////////////////////////////////////////////////////////////// // PT: the offsets can be different for different templated classes so I need macros here. #define DefineMetaData_PxActor(x) \ PX_DEF_BIN_METADATA_ITEM(stream, x, void, userData, PxMetaDataFlag::ePTR) #define DefineMetaData_NpRigidActorTemplate(x) \ PX_DEF_BIN_METADATA_ITEM(stream, x, NpShapeManager, mShapeManager, 0) // PX_DEF_BIN_METADATA_ITEM(stream, x, PxU32, mIndex, 0) #define DefineMetaData_NpRigidBodyTemplate(x) \ PX_DEF_BIN_METADATA_ITEM(stream, x, Sc::BodyCore, mCore, 0) /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PxVec3(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxVec3) PX_DEF_BIN_METADATA_ITEM(stream, PxVec3, PxReal, x, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec3, PxReal, y, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec3, PxReal, z, 0) } static void getBinaryMetaData_PxVec4(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxVec4) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, x, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, y, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, z, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, w, 0) } static void getBinaryMetaData_PxQuat(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxQuat) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, x, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, y, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, z, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, w, 0) } static void getBinaryMetaData_PxBounds3(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxBounds3) PX_DEF_BIN_METADATA_ITEM(stream, PxBounds3, PxVec3, minimum, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxBounds3, PxVec3, maximum, 0) } static void getBinaryMetaData_PxTransform(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxTransform) PX_DEF_BIN_METADATA_ITEM(stream, PxTransform, PxQuat, q, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxTransform, PxVec3, p, 0) } static void getBinaryMetaData_PxTransform32(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxTransform32) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxTransform32, PxTransform) PX_DEF_BIN_METADATA_ITEM(stream, PxTransform32, PxU32, padding, 0) } static void getBinaryMetaData_PxMat33(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxMat33) PX_DEF_BIN_METADATA_ITEM(stream, PxMat33, PxVec3, column0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxMat33, PxVec3, column1, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxMat33, PxVec3, column2, 0) } static void getBinaryMetaData_SpatialVectorF(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, Cm::SpatialVectorF) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxVec3, top, 0) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxReal, pad0, 0) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxVec3, bottom, 0) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxReal, pad1, 0) } namespace { class ShadowBitMap : public PxBitMap { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowBitMap) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBitMap, PxU32, mMap, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBitMap, PxU32, mWordCount, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBitMap, PxAllocator, mAllocator, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream_, ShadowBitMap, PxU8, mPadding, PxMetaDataFlag::ePADDING) //------ Extra-data ------ // mMap PX_DEF_BIN_METADATA_EXTRA_ARRAY(stream_, ShadowBitMap, PxU32, mWordCount, PX_SERIAL_ALIGN, PxMetaDataFlag::eCOUNT_MASK_MSB) } }; } static void getBinaryMetaData_BitMap(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxAllocator, PxU8) ShadowBitMap::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, BitMap, ShadowBitMap) } static void getBinaryMetaData_PxPlane(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxPlane) PX_DEF_BIN_METADATA_ITEM(stream, PxPlane, PxVec3, n, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxPlane, PxReal, d, 0) } static void getBinaryMetaData_PxConstraintInvMassScale(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxConstraintInvMassScale) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, linear0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, angular0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, linear1, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, angular1, 0) } /////////////////////////////////////////////////////////////////////////////// void NpBase::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, NpType::Enum, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpBase, NpScene, mScene, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpBase, PxU32, mBaseIndexAndType, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpBase, PxU32, mFreeSlot, 0) } /////////////////////////////////////////////////////////////////////////////// void NpActor::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpActor) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpActor, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpActor, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpActor, NpConnectorArray, mConnectorArray, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpMaterial, PxsMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpFEMSoftBodyMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpFEMSoftBodyMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMSoftBodyMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMSoftBodyMaterial, PxsFEMSoftBodyMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpFEMClothMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpFEMClothMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpFEMClothMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMClothMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMClothMaterial, PxsFEMClothMaterialCore, mMaterial, 0) } #endif /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpPBDMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpPBDMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpPBDMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpPBDMaterial, PxsPBDMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpFLIPMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpFLIPMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpFLIPMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpFLIPMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpFLIPMaterial, PxsFLIPMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpMPMMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpMPMMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpMPMMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpMPMMaterial, PxsMPMMaterialCore, mMaterial, 0) } #endif /////////////////////////////////////////////////////////////////////////////// void NpConstraint::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpConstraint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpConstraint, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpConstraint, NpBase) // PxConstraint PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, void, userData, PxMetaDataFlag::ePTR) // NpConstraint PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, PxRigidActor, mActor0, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, PxRigidActor, mActor1, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, ConstraintCore, mCore, 0) } /////////////////////////////////////////////////////////////////////////////// void NpShapeManager::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpShapeManager) PX_DEF_BIN_METADATA_ITEM(stream, NpShapeManager, PtrTable, mShapes, 0) // PX_DEF_BIN_METADATA_ITEM(stream, NpShapeManager, PxU32, mSqCompoundId, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpShapeManager, Sq::PruningStructure, mPruningStructure, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void NpShape::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpShape) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpShape, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpShape, NpBase) // PxShape PX_DEF_BIN_METADATA_ITEM(stream, NpShape, void, userData, PxMetaDataFlag::ePTR) // NpShape PX_DEF_BIN_METADATA_ITEM(stream, NpShape, PxRigidActor, mExclusiveShapeActor, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpShape, ShapeCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpShape, PxFilterData, mQueryFilterData, 0) } /////////////////////////////////////////////////////////////////////////////// void NpRigidStatic::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpRigidStatic) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidStatic, PxBase) // PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidStatic, NpRigidStaticT) // ### ??? PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidStatic, NpActor) DefineMetaData_PxActor(NpRigidStatic) DefineMetaData_NpRigidActorTemplate(NpRigidStatic) // NpRigidStatic PX_DEF_BIN_METADATA_ITEM(stream, NpRigidStatic, Sc::StaticCore, mCore, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, NpRigidStatic, NpConnectorArray, mConnectorArray, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpRigidStatic, mName, 0) } /////////////////////////////////////////////////////////////////////////////// void NpConnector::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpConnector) PX_DEF_BIN_METADATA_ITEM(stream, NpConnector, PxU8, mType, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, NpConnector, PxU8, mPadding, PxMetaDataFlag::ePADDING) PX_DEF_BIN_METADATA_ITEM(stream, NpConnector, PxBase, mObject, PxMetaDataFlag::ePTR) } void NpConnectorArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpConnectorArray) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, NpConnectorArray, NpConnector, mBuffer, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitly in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpConnectorArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, NpConnector, mData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpConnectorArray, NpConnector, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB, 0) } /////////////////////////////////////////////////////////////////////////////// void NpRigidDynamic::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpRigidDynamic) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidDynamic, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidDynamic, NpActor) DefineMetaData_PxActor(NpRigidDynamic) DefineMetaData_NpRigidActorTemplate(NpRigidDynamic) DefineMetaData_NpRigidBodyTemplate(NpRigidDynamic) // NpRigidDynamic //------ Extra-data ------ // Extra data: // - inline array from shape manager // - optional constraint array // PX_DEF_BIN_METADATA_ITEM(stream,NpRigidDynamic, NpShapeManager, mShapeManager.mShapes, 0) /* virtual void exportExtraData(PxOutputStream& stream) { mShapeManager.exportExtraData(stream); ActorTemplateClass::exportExtraData(stream); } void NpActorTemplate<APIClass, LeafClass>::exportExtraData(PxOutputStream& stream) { if(mConnectorArray) { stream.storeBuffer(mConnectorArray, sizeof(NpConnectorArray) mConnectorArray->exportExtraData(stream); } } */ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, NpRigidDynamic, NpConnectorArray, mConnectorArray, PX_SERIAL_ALIGN) //### missing inline array data here... only works for "buffered" arrays so far /* Big issue: we can't output the "offset of" the inline array within the class, since the inline array itself is extra-data. But we need to read the array itself to know if it's inline or not (the "is buffered" bool). So we need to read from the extra data! */ /* [17:41:39] Gordon Yeoman nvidia: PxsBodyCore need to be 16-byte aligned for spu. If it is 128-byte aligned then that is a mistake. Feel free to change it to 16. */ PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpRigidDynamic, mName, 0) } /////////////////////////////////////////////////////////////////////////////// void NpArticulationLinkArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpArticulationLinkArray) PX_DEF_BIN_METADATA_ITEMS(stream, NpArticulationLinkArray, NpArticulationLink, mBuffer, PxMetaDataFlag::ePTR, 4) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitely in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpArticulationLinkArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, NpArticulationLink, mData, PxMetaDataFlag::ePTR) // ### PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpArticulationLinkArray, NpArticulationLink, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) } void NpArticulationAttachmentArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpArticulationAttachmentArray) PX_DEF_BIN_METADATA_ITEMS(stream, NpArticulationAttachmentArray, NpArticulationAttachment, mBuffer, PxMetaDataFlag::ePTR, 4) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitely in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpArticulationAttachmentArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, NpArticulationAttachment, mData, PxMetaDataFlag::ePTR) // ### PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpArticulationAttachmentArray, NpArticulationAttachment, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) } namespace { struct ShadowLoopJointArray : public PxArray<PxConstraint*> { static void getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ShadowLoopJointArray) PX_DEF_BIN_METADATA_ITEM(stream, ShadowLoopJointArray, NpConstraint, mData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ShadowLoopJointArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowLoopJointArray, PxU32, mCapacity, 0) } }; #define DECL_SHADOW_PTR_ARRAY(T) \ struct ShadowArray##T : public PxArray<T*> \ { \ static void getBinaryMetaData(PxOutputStream& stream) \ { \ PX_DEF_BIN_METADATA_CLASS(stream, ShadowArray##T) \ PX_DEF_BIN_METADATA_ITEM(stream, ShadowArray##T, T, mData, PxMetaDataFlag::ePTR)\ PX_DEF_BIN_METADATA_ITEM(stream, ShadowArray##T, PxU32, mSize, 0) \ PX_DEF_BIN_METADATA_ITEM(stream, ShadowArray##T, PxU32, mCapacity, 0) \ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, ShadowArray##T, T, mData, mCapacity, PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) \ } \ }; DECL_SHADOW_PTR_ARRAY(NpArticulationSpatialTendon) DECL_SHADOW_PTR_ARRAY(NpArticulationFixedTendon) DECL_SHADOW_PTR_ARRAY(NpArticulationSensor) } void NpArticulationReducedCoordinate::getBinaryMetaData(PxOutputStream& stream) { ShadowLoopJointArray::getBinaryMetaData(stream); ShadowArrayNpArticulationSpatialTendon::getBinaryMetaData(stream); ShadowArrayNpArticulationFixedTendon::getBinaryMetaData(stream); ShadowArrayNpArticulationSensor::getBinaryMetaData(stream); //sticking this here, since typedefs are only allowed to declared once. PX_DEF_BIN_METADATA_TYPEDEF(stream, ArticulationTendonHandle, PxU32) PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationReducedCoordinate) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationReducedCoordinate, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationReducedCoordinate, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ArticulationCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, NpArticulationLinkArray, mArticulationLinks, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, PxU32, mNumShapes, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, NpAggregate, mAggregate, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpArticulationReducedCoordinate, mName, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, PxU32, mCacheVersion, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, bool, mTopologyChanged, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowLoopJointArray, mLoopJoints, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowArrayNpArticulationSpatialTendon, mSpatialTendons, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowArrayNpArticulationFixedTendon, mFixedTendons, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowArrayNpArticulationSensor, mSensors, 0) } void NpArticulationSensor::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationSensor) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSensor, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSensor, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, PxArticulationLink, mLink, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, ArticulationSensorCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, PxU32, mHandle, 0) } void NpArticulationAttachment::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationAttachment) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationAttachment, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationAttachment, NpBase) PX_DEF_BIN_METADATA_TYPEDEF(stream, ArticulationAttachmentHandle, PxU32); PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, PxArticulationLink, mLink, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, PxArticulationAttachment, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, ArticulationAttachmentHandle, mHandle, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, NpArticulationAttachmentArray, mChildren, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, NpArticulationSpatialTendon, mTendon, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, ArticulationAttachmentCore, mCore, 0) } void NpArticulationTendonJoint::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationTendonJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationTendonJoint, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationTendonJoint, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, PxArticulationLink, mLink, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, PxArticulationTendonJoint, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, NpArticulationTendonJointArray, mChildren, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, NpArticulationFixedTendon, mTendon, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, ArticulationTendonJointCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, PxU32, mHandle, 0) } void NpArticulationTendonJointArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpArticulationTendonJointArray) PX_DEF_BIN_METADATA_ITEMS(stream, NpArticulationTendonJointArray, NpArticulationTendonJoint, mBuffer, PxMetaDataFlag::ePTR, 4) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitely in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpArticulationTendonJointArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, NpArticulationTendonJoint, mData, PxMetaDataFlag::ePTR) // ### PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpArticulationTendonJointArray, NpArticulationTendonJoint, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) } void NpArticulationSpatialTendon::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationSpatialTendon) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSpatialTendon, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSpatialTendon, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, NpArticulationAttachmentArray, mAttachments, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, NpArticulationReducedCoordinate, mArticulation, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, PxU32, mLLIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, ArticulationSpatialTendonCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, ArticulationTendonHandle, mHandle, 0) } void NpArticulationFixedTendon::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationFixedTendon) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationFixedTendon, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationFixedTendon, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, NpArticulationTendonJointArray, mTendonJoints, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, NpArticulationReducedCoordinate, mArticulation, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, PxU32, mLLIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, ArticulationFixedTendonCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, ArticulationTendonHandle, mHandle, 0) } void NpArticulationLink::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationLink) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationLink, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationLink, NpActor) DefineMetaData_PxActor(NpArticulationLink) DefineMetaData_NpRigidActorTemplate(NpArticulationLink) DefineMetaData_NpRigidBodyTemplate(NpArticulationLink) // NpArticulationLink PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulation, mRoot, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulationJoint, mInboundJoint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulationLink, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulationLinkArray, mChildLinks, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, PxU32, mLLIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, PxU32, mInboundJointDof, 0); //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, NpArticulationLink, NpConnectorArray, mConnectorArray, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpArticulationLink, mName, 0) } void NpArticulationJointReducedCoordinate::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationJointReducedCoordinate) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationJointReducedCoordinate, NpBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationJointReducedCoordinate, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, ArticulationJointCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, NpArticulationLink, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, NpArticulationLink, mChild, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void NpAggregate::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpAggregate) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpAggregate, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpAggregate, NpBase) // PxAggregate PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, void, userData, PxMetaDataFlag::ePTR) // NpAggregate PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mAggregateID, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mMaxNbActors, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mMaxNbShapes, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mFilterHint, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mNbActors, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mNbShapes, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxActor, mActors, PxMetaDataFlag::ePTR) //------ Extra-data ------ // mActors PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpAggregate, PxActor, mActors, mNbActors, PxMetaDataFlag::ePTR, PX_SERIAL_ALIGN) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PxMeshScale(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxMeshScale) PX_DEF_BIN_METADATA_ITEM(stream, PxMeshScale, PxVec3, scale, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxMeshScale, PxQuat, rotation, 0) } static void getBinaryMetaData_AABBPrunerMergeData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, AABBPrunerMergeData) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, PxU32, mNbNodes, 0) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, Gu::BVHNode, mAABBTreeNodes, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, PxU32, mNbObjects, 0) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, PxU32, mAABBTreeIndices, PxMetaDataFlag::ePTR) } void Sq::PruningStructure::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_AABBPrunerMergeData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, PruningStructure) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PruningStructure, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, AABBPrunerMergeData, mData[0], 0) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, AABBPrunerMergeData, mData[1], 0) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, PxU32, mNbActors, 0) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, PxActor*, mActors, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, bool, mValid, 0) } /////////////////////////////////////////////////////////////////////////////// namespace physx { void getBinaryMetaData_PxBase(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxBaseFlags, PxU16) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxType, PxU16) PX_DEF_BIN_METADATA_VCLASS(stream, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, PxBase, PxType, mConcreteType, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxBase, PxBaseFlags, mBaseFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxBase, PxI32, mBuiltInRefCount, 0) } } void RefCountable::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, RefCountable) PX_DEF_BIN_METADATA_ITEM(stream, RefCountable, PxI32, mRefCount, 0) } static void getFoundationMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxU8, char) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxI8, char) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxU16, short) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxI16, short) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxU32, int) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxI32, int) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxReal, float) getBinaryMetaData_PxVec3(stream); getBinaryMetaData_PxVec4(stream); getBinaryMetaData_PxQuat(stream); getBinaryMetaData_PxBounds3(stream); getBinaryMetaData_PxTransform(stream); getBinaryMetaData_PxTransform32(stream); getBinaryMetaData_PxMat33(stream); getBinaryMetaData_SpatialVectorF(stream); getBinaryMetaData_BitMap(stream); Cm::PtrTable::getBinaryMetaData(stream); getBinaryMetaData_PxPlane(stream); getBinaryMetaData_PxConstraintInvMassScale(stream); getBinaryMetaData_PxBase(stream); RefCountable::getBinaryMetaData(stream); } /////////////////////////////////////////////////////////////////////////////// namespace physx { template<> void PxsMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsFEMSoftBodyMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsFEMClothMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsPBDMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsFLIPMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsMPMMaterialCore::getBinaryMetaData(PxOutputStream& stream); } void PxGetPhysicsBinaryMetaData(PxOutputStream& stream) { getFoundationMetaData(stream); getBinaryMetaData_PxMeshScale(stream); Gu::ConvexMesh::getBinaryMetaData(stream); Gu::TriangleMesh::getBinaryMetaData(stream); Gu::RTreeTriangleMesh::getBinaryMetaData(stream); Gu::BV4TriangleMesh::getBinaryMetaData(stream); Gu::HeightField::getBinaryMetaData(stream); PxsMaterialCore::getBinaryMetaData(stream); PxsFEMSoftBodyMaterialCore::getBinaryMetaData(stream); PxsFEMClothMaterialCore::getBinaryMetaData(stream); PxsPBDMaterialCore::getBinaryMetaData(stream); PxsFLIPMaterialCore::getBinaryMetaData(stream); PxsMPMMaterialCore::getBinaryMetaData(stream); MaterialIndicesStruct::getBinaryMetaData(stream); GeometryUnion::getBinaryMetaData(stream); Sc::ActorCore::getBinaryMetaData(stream); Sc::RigidCore::getBinaryMetaData(stream); Sc::StaticCore::getBinaryMetaData(stream); Sc::BodyCore::getBinaryMetaData(stream); Sc::ShapeCore::getBinaryMetaData(stream); Sc::ConstraintCore::getBinaryMetaData(stream); Sc::ArticulationCore::getBinaryMetaData(stream); Sc::ArticulationJointCore::getBinaryMetaData(stream); Sc::ArticulationSensorCore::getBinaryMetaData(stream); Sc::ArticulationTendonCore::getBinaryMetaData(stream); Sc::ArticulationSpatialTendonCore::getBinaryMetaData(stream); Sc::ArticulationAttachmentCore::getBinaryMetaData(stream); Sc::ArticulationFixedTendonCore::getBinaryMetaData(stream); Sc::ArticulationTendonJointCore::getBinaryMetaData(stream); NpConnector::getBinaryMetaData(stream); NpConnectorArray::getBinaryMetaData(stream); NpBase::getBinaryMetaData(stream); NpActor::getBinaryMetaData(stream); NpMaterial::getBinaryMetaData(stream); NpFEMSoftBodyMaterial::getBinaryMetaData(stream); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFEMClothMaterial::getBinaryMetaData(stream); #endif NpPBDMaterial::getBinaryMetaData(stream); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFLIPMaterial::getBinaryMetaData(stream); NpMPMMaterial::getBinaryMetaData(stream); #endif NpRigidDynamic::getBinaryMetaData(stream); NpRigidStatic::getBinaryMetaData(stream); NpShape::getBinaryMetaData(stream); NpConstraint::getBinaryMetaData(stream); NpArticulationReducedCoordinate::getBinaryMetaData(stream); NpArticulationLink::getBinaryMetaData(stream); NpArticulationJointReducedCoordinate::getBinaryMetaData(stream); NpArticulationLinkArray::getBinaryMetaData(stream); NpArticulationSensor::getBinaryMetaData(stream); NpArticulationSpatialTendon::getBinaryMetaData(stream); NpArticulationFixedTendon::getBinaryMetaData(stream); NpArticulationAttachment::getBinaryMetaData(stream); NpArticulationAttachmentArray::getBinaryMetaData(stream); NpArticulationTendonJoint::getBinaryMetaData(stream); NpArticulationTendonJointArray::getBinaryMetaData(stream); NpShapeManager::getBinaryMetaData(stream); NpAggregate::getBinaryMetaData(stream); }
38,206
C++
44.811751
210
0.75407
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdTypeNames.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 PVD_TYPE_NAMES_H #define PVD_TYPE_NAMES_H #if PX_SUPPORT_PVD #include "geometry/PxHeightFieldSample.h" #include "PxPvdObjectModelBaseTypes.h" #include "PxMetaDataObjects.h" namespace physx { namespace Vd { struct PvdSqHit; struct PvdRaycast; struct PvdOverlap; struct PvdSweep; struct PvdHullPolygonData { PxU16 mNumVertices; PxU16 mIndexBase; PvdHullPolygonData(PxU16 numVert, PxU16 idxBase) : mNumVertices(numVert), mIndexBase(idxBase) { } }; struct PxArticulationLinkUpdateBlock { PxTransform GlobalPose; PxVec3 LinearVelocity; PxVec3 AngularVelocity; }; struct PxArticulationJointUpdateBlock { PxReal JointPosition_eX; PxReal JointPosition_eY; PxReal JointPosition_eZ; PxReal JointPosition_eTwist; PxReal JointPosition_eSwing1; PxReal JointPosition_eSwing2; PxReal JointVelocity_eX; PxReal JointVelocity_eY; PxReal JointVelocity_eZ; PxReal JointVelocity_eTwist; PxReal JointVelocity_eSwing1; PxReal JointVelocity_eSwing2; }; struct PxRigidDynamicUpdateBlock : public PxArticulationLinkUpdateBlock { bool IsSleeping; }; struct PvdContact { PxVec3 point; PxVec3 axis; const void* shape0; const void* shape1; PxF32 separation; PxF32 normalForce; PxU32 internalFaceIndex0; PxU32 internalFaceIndex1; bool normalForceAvailable; }; struct PvdPositionAndRadius { PxVec3 position; PxF32 radius; }; } //Vd } //physx namespace physx { namespace pvdsdk { #define DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(type) DEFINE_PVD_TYPE_NAME_MAP(physx::type, "physx3", #type) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPhysics) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxScene) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTolerancesScale) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTolerancesScaleGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSceneDescGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSceneDesc) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSimulationStatistics) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSimulationStatisticsGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxMaterial) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxMaterialGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMSoftBodyMaterial) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMSoftBodyMaterialGeneratedValues) // DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMClothMaterial) // jcarius: Commented-out until FEMCloth is not under construction anymore // DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMClothMaterialGeneratedValues) // jcarius: Commented-out until FEMCloth is not under construction anymore DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPBDMaterial) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPBDMaterialGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightField) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldDesc) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldDescGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTriangleMesh) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTetrahedronMesh) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConvexMesh) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxActor) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidActor) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidBody) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidDynamic) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidDynamicGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidStatic) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidStaticGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxShape) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxShapeGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxBoxGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPlaneGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCapsuleGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSphereGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTriangleMeshGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTetrahedronMeshGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConvexMeshGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCustomGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxBoxGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPlaneGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCapsuleGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSphereGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTetrahedronMeshGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTriangleMeshGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConvexMeshGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCustomGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldSample) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConstraint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConstraintGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationReducedCoordinate) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationReducedCoordinateGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationLink) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationLinkGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationJointReducedCoordinate) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationJointReducedCoordinateGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxAggregate) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxAggregateGeneratedValues) #undef DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP #define DEFINE_NATIVE_PVD_TYPE_MAP(type) DEFINE_PVD_TYPE_NAME_MAP(physx::Vd::type, "physx3", #type) DEFINE_NATIVE_PVD_TYPE_MAP(PvdHullPolygonData) DEFINE_NATIVE_PVD_TYPE_MAP(PxRigidDynamicUpdateBlock) DEFINE_NATIVE_PVD_TYPE_MAP(PxArticulationLinkUpdateBlock) DEFINE_NATIVE_PVD_TYPE_MAP(PxArticulationJointUpdateBlock) DEFINE_NATIVE_PVD_TYPE_MAP(PvdContact) DEFINE_NATIVE_PVD_TYPE_MAP(PvdRaycast) DEFINE_NATIVE_PVD_TYPE_MAP(PvdSweep) DEFINE_NATIVE_PVD_TYPE_MAP(PvdOverlap) DEFINE_NATIVE_PVD_TYPE_MAP(PvdSqHit) DEFINE_NATIVE_PVD_TYPE_MAP(PvdPositionAndRadius) #undef DEFINE_NATIVE_PVD_TYPE_MAP DEFINE_PVD_TYPE_ALIAS(physx::PxFilterData, U32Array4) } } #endif #endif
7,640
C
37.590909
146
0.821073
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterial.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_MATERIAL_H #define NP_MATERIAL_H #include "common/PxSerialFramework.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" #include "CmRefCountable.h" #include "PxsMaterialCore.h" namespace physx { // Compared to other objects, materials are special since they belong to the SDK and not to scenes // (similar to meshes). That's why the NpMaterial does have direct access to the core material instead // of having a buffered interface for it. Scenes will have copies of the SDK material table and there // the materials will be buffered. class NpMaterial : public PxMaterial, public PxUserAllocated { public: // PX_SERIALIZATION NpMaterial(PxBaseFlags baseFlags) : PxMaterial(baseFlags), mMaterial(PxEmpty) {} virtual void resolveReferences(PxDeserializationContext& context); static NpMaterial* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&){} //~PX_SERIALIZATION NpMaterial(const PxsMaterialCore& desc); virtual ~NpMaterial(); // PxBase virtual void release() PX_OVERRIDE; //~PxBase // PxRefCounted virtual void acquireReference() PX_OVERRIDE; virtual PxU32 getReferenceCount() const PX_OVERRIDE; virtual void onRefCountZero() PX_OVERRIDE; //~PxRefCounted // PxMaterial virtual void setDynamicFriction(PxReal) PX_OVERRIDE; virtual PxReal getDynamicFriction() const PX_OVERRIDE; virtual void setStaticFriction(PxReal) PX_OVERRIDE; virtual PxReal getStaticFriction() const PX_OVERRIDE; virtual void setRestitution(PxReal) PX_OVERRIDE; virtual PxReal getRestitution() const PX_OVERRIDE; virtual void setDamping(PxReal) PX_OVERRIDE; virtual PxReal getDamping() const PX_OVERRIDE; virtual void setFlag(PxMaterialFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setFlags(PxMaterialFlags inFlags) PX_OVERRIDE; virtual PxMaterialFlags getFlags() const PX_OVERRIDE; virtual void setFrictionCombineMode(PxCombineMode::Enum) PX_OVERRIDE; virtual PxCombineMode::Enum getFrictionCombineMode() const PX_OVERRIDE; virtual void setRestitutionCombineMode(PxCombineMode::Enum) PX_OVERRIDE; virtual PxCombineMode::Enum getRestitutionCombineMode() const PX_OVERRIDE; //~PxMaterial PX_FORCE_INLINE static void getMaterialIndices(PxMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount); private: PX_INLINE void updateMaterial(); // PX_SERIALIZATION public: //~PX_SERIALIZATION PxsMaterialCore mMaterial; }; PX_FORCE_INLINE void NpMaterial::getMaterialIndices(PxMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount) { for(PxU32 i=0; i < materialCount; i++) materialIndices[i] = static_cast<NpMaterial*>(materials[i])->mMaterial.mMaterialIndex; } } #endif
4,816
C
43.19266
125
0.761005
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpActorTemplate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_ACTOR_TEMPLATE_H #define NP_ACTOR_TEMPLATE_H #include "NpCheck.h" #include "NpActor.h" #include "NpScene.h" #include "omnipvd/NpOmniPvdSetData.h" namespace physx { // PT: only API (virtual) functions should be implemented here. Other shared non-virtual functions should go to NpActor. /** This is an API class. API classes run in a different thread than the simulation. For the sake of simplicity they have their own methods, and they do not call simulation methods directly. To set simulation state, they also have their own custom set methods in the implementation classes. Changing the data layout of this class breaks the binary serialization format. See comments for PX_BINARY_SERIAL_VERSION. */ template<class APIClass> class NpActorTemplate : public APIClass, public NpActor { PX_NOCOPY(NpActorTemplate) public: // PX_SERIALIZATION NpActorTemplate(PxBaseFlags baseFlags) : APIClass(baseFlags), NpActor(PxEmpty) {} virtual void exportExtraData(PxSerializationContext& context) { NpActor::exportExtraData(context); } virtual void importExtraData(PxDeserializationContext& context) { NpActor::importExtraData(context); } virtual void resolveReferences(PxDeserializationContext& context) { NpActor::resolveReferences(context); } //~PX_SERIALIZATION NpActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type); virtual ~NpActorTemplate(); // The rule is: If an API method is used somewhere in here, it has to be redeclared, else GCC whines // PxActor virtual void release() = 0; virtual PxActorType::Enum getType() const = 0; virtual PxScene* getScene() const PX_OVERRIDE; virtual void setName(const char*) PX_OVERRIDE; virtual const char* getName() const PX_OVERRIDE; virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0; virtual void setActorFlag(PxActorFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setActorFlags(PxActorFlags inFlags) PX_OVERRIDE; virtual PxActorFlags getActorFlags() const PX_OVERRIDE; virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) PX_OVERRIDE; virtual PxDominanceGroup getDominanceGroup() const PX_OVERRIDE; virtual void setOwnerClient( PxClientID inClient ) PX_OVERRIDE; virtual PxClientID getOwnerClient() const PX_OVERRIDE; virtual PxAggregate* getAggregate() const PX_OVERRIDE { return NpActor::getAggregate(); } //~PxActor protected: PX_FORCE_INLINE void setActorFlagInternal(PxActorFlag::Enum flag, bool value); PX_FORCE_INLINE void setActorFlagsInternal(PxActorFlags inFlags); }; /////////////////////////////////////////////////////////////////////////////// template<class APIClass> NpActorTemplate<APIClass>::NpActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type) : APIClass(concreteType, baseFlags), NpActor (type) { PX_ASSERT(!APIClass::userData); } template<class APIClass> NpActorTemplate<APIClass>::~NpActorTemplate() { NpActor::onActorRelease(this); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> PxScene* NpActorTemplate<APIClass>::getScene() const { return getNpScene(); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> void NpActorTemplate<APIClass>::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(getNpScene(), "PxActor::setName() not allowed while simulation is running. Call will be ignored.") mName = debugName; #if PX_SUPPORT_OMNI_PVD PxActor & a = *this; streamActorName(a, mName); #endif #if PX_SUPPORT_PVD NpScene* npScene = getNpScene(); //Name changing is not bufferred if(npScene) npScene->getScenePvdClientInternal().updatePvdProperties(static_cast<NpActor*>(this)); #endif } template<class APIClass> const char* NpActorTemplate<APIClass>::getName() const { NP_READ_CHECK(getNpScene()); return mName; } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> void NpActorTemplate<APIClass>::setDominanceGroup(PxDominanceGroup dominanceGroup) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxActor::setDominanceGroup() not allowed while simulation is running. Call will be ignored.") NpActor::scSetDominanceGroup(dominanceGroup); } template<class APIClass> PxDominanceGroup NpActorTemplate<APIClass>::getDominanceGroup() const { NP_READ_CHECK(getNpScene()); return NpActor::getDominanceGroup(); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> void NpActorTemplate<APIClass>::setOwnerClient( PxClientID inId ) { if ( getNpScene() != NULL ) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Attempt to set the client id when an actor is already in a scene."); } else NpActor::scSetOwnerClient( inId ); } template<class APIClass> PxClientID NpActorTemplate<APIClass>::getOwnerClient() const { return NpActor::getOwnerClient(); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> PX_FORCE_INLINE void NpActorTemplate<APIClass>::setActorFlagInternal(PxActorFlag::Enum flag, bool value) { NpActor& a = *this; if (value) a.scSetActorFlags( a.getActorFlags() | flag ); else a.scSetActorFlags( a.getActorFlags() & (~PxActorFlags(flag)) ); } template<class APIClass> PX_FORCE_INLINE void NpActorTemplate<APIClass>::setActorFlagsInternal(PxActorFlags inFlags) { NpActor::scSetActorFlags(inFlags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, flags, static_cast<PxActor&>(*this), inFlags) } template<class APIClass> void NpActorTemplate<APIClass>::setActorFlag(PxActorFlag::Enum flag, bool value) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxActor::setActorFlag() not allowed while simulation is running. Call will be ignored.") setActorFlagInternal(flag, value); } template<class APIClass> void NpActorTemplate<APIClass>::setActorFlags(PxActorFlags inFlags) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxActor::setActorFlags() not allowed while simulation is running. Call will be ignored.") setActorFlagsInternal(inFlags); } template<class APIClass> PxActorFlags NpActorTemplate<APIClass>::getActorFlags() const { NP_READ_CHECK(getNpScene()); return NpActor::getActorFlags(); } /////////////////////////////////////////////////////////////////////////////// } #endif
8,361
C
33.697095
151
0.714867
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpConstraint.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_CONSTRAINT_H #define NP_CONSTRAINT_H #include "foundation/PxUserAllocated.h" #include "PxConstraint.h" #include "NpBase.h" #include "../../../simulationcontroller/include/ScConstraintCore.h" #include "NpActor.h" namespace physx { class NpScene; class NpConstraint : public PxConstraint, public NpBase { public: // PX_SERIALIZATION NpConstraint(PxBaseFlags baseFlags) : PxConstraint(baseFlags), NpBase(PxEmpty), mCore(PxEmpty) {} static NpConstraint* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() {} void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback&) {} virtual bool isSubordinate() const { return true; } //~PX_SERIALIZATION NpConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize); virtual ~NpConstraint(); // PxConstraint virtual void release() PX_OVERRIDE; virtual PxScene* getScene() const PX_OVERRIDE; virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const PX_OVERRIDE; virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) PX_OVERRIDE; virtual void markDirty() PX_OVERRIDE; virtual PxConstraintFlags getFlags() const PX_OVERRIDE; virtual void setFlags(PxConstraintFlags flags) PX_OVERRIDE; virtual void setFlag(PxConstraintFlag::Enum flag, bool value) PX_OVERRIDE; virtual void getForce(PxVec3& linear, PxVec3& angular) const PX_OVERRIDE; virtual bool isValid() const PX_OVERRIDE; virtual void setBreakForce(PxReal linear, PxReal angular) PX_OVERRIDE; virtual void getBreakForce(PxReal& linear, PxReal& angular) const PX_OVERRIDE; virtual void setMinResponseThreshold(PxReal threshold) PX_OVERRIDE; virtual PxReal getMinResponseThreshold() const PX_OVERRIDE; virtual void* getExternalReference(PxU32& typeID) PX_OVERRIDE; virtual void setConstraintFunctions(PxConstraintConnector& n, const PxConstraintShaderTable& t) PX_OVERRIDE; //~PxConstraint void updateConstants(PxsSimulationController& simController); void comShift(PxRigidActor*); void actorDeleted(PxRigidActor*); NpScene* getSceneFromActors() const; PX_FORCE_INLINE Sc::ConstraintCore& getCore() { return mCore; } PX_FORCE_INLINE const Sc::ConstraintCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpConstraint, mCore); } PX_FORCE_INLINE bool isDirty() const { return mCore.isDirty(); } PX_FORCE_INLINE void markClean() { mCore.clearDirty(); } private: PxRigidActor* mActor0; PxRigidActor* mActor1; Sc::ConstraintCore mCore; void addConnectors(PxRigidActor* actor0, PxRigidActor* actor1); void removeConnectors(const char* errorMsg0, const char* errorMsg1); PX_INLINE void scSetFlags(PxConstraintFlags f) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setFlags(f); markDirty(); UPDATE_PVD_PROPERTY } }; } #endif
5,170
C
46.440367
159
0.723985
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMClothMaterial.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 "NpFEMClothMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX using namespace physx; using namespace Cm; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFEMClothMaterial::NpFEMClothMaterial(const PxsFEMClothMaterialCore& desc) : PxFEMClothMaterial(PxConcreteType::eCLOTH_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpFEMClothMaterial::~NpFEMClothMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpFEMClothMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: why commented out? //NpPhysics::getInstance().addFEMMaterial(this); } void NpFEMClothMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseFEMClothMaterialToPool(*this); } else this->~NpFEMClothMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpFEMClothMaterial* NpFEMClothMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpFEMClothMaterial* obj = PX_PLACEMENT_NEW(address, NpFEMClothMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpFEMClothMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpFEMClothMaterial::release() { RefCountable_decRefCount(*this); } void NpFEMClothMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpFEMClothMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpFEMClothMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setYoungsModulus(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMClothMaterial::setYoungsModulus: invalid float"); mMaterial.youngs = x; updateMaterial(); } PxReal NpFEMClothMaterial::getYoungsModulus() const { return mMaterial.youngs; } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setPoissons(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x < 0.5f, "PxFEMClothMaterial::setPoissons: invalid float"); mMaterial.poissons = x; updateMaterial(); } PxReal NpFEMClothMaterial::getPoissons() const { return mMaterial.poissons; } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setDynamicFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFEMClothMaterial::setDynamicFriction: invalid float"); mMaterial.dynamicFriction = x; updateMaterial(); } PxReal NpFEMClothMaterial::getDynamicFriction() const { return mMaterial.dynamicFriction; } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setThickness(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFEMClothMaterial::setThickness: invalid float"); mMaterial.thickness = x; updateMaterial(); } PxReal NpFEMClothMaterial::getThickness() const { return mMaterial.thickness; } ////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #endif #endif
5,489
C++
30.371428
108
0.703771
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpAggregate.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 "NpAggregate.h" #include "PxActor.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpActor.h" #include "GuBVH.h" #include "CmUtils.h" #include "NpArticulationReducedCoordinate.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; using namespace Gu; namespace { #if PX_SUPPORT_PVD PX_FORCE_INLINE void PvdAttachActorToAggregate(NpAggregate* pAggregate, NpActor* pscActor) { NpScene* npScene = pAggregate->getNpScene(); if(npScene/* && scScene->getScenePvdClient().isInstanceValid(pAggregate)*/) npScene->getScenePvdClientInternal().attachAggregateActor( pAggregate, pscActor ); } PX_FORCE_INLINE void PvdDetachActorFromAggregate(NpAggregate* pAggregate, NpActor* pscActor) { NpScene* npScene = pAggregate->getNpScene(); if(npScene/*&& scScene->getScenePvdClient().isInstanceValid(pAggregate)*/) npScene->getScenePvdClientInternal().detachAggregateActor( pAggregate, pscActor ); } PX_FORCE_INLINE void PvdUpdateProperties(NpAggregate* pAggregate) { NpScene* npScene = pAggregate->getNpScene(); if(npScene /*&& scScene->getScenePvdClient().isInstanceValid(pAggregate)*/) npScene->getScenePvdClientInternal().updatePvdProperties( pAggregate ); } #else #define PvdAttachActorToAggregate(aggregate, scActor) {} #define PvdDetachActorFromAggregate(aggregate, scActor) {} #define PvdUpdateProperties(aggregate) {} #endif } /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void setAggregate(NpAggregate* aggregate, PxActor& actor) { NpActor& np = NpActor::getFromPxActor(actor); np.setAggregate(aggregate, actor); } /////////////////////////////////////////////////////////////////////////////// NpAggregate::NpAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint) : PxAggregate (PxConcreteType::eAGGREGATE, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), NpBase (NpType::eAGGREGATE), mAggregateID (PX_INVALID_U32), mMaxNbActors (maxActors), mMaxNbShapes (maxShapes), mFilterHint (filterHint), mNbActors (0), mNbShapes (0) { mActors = PX_ALLOCATE(PxActor*, maxActors, "PxActor*"); } NpAggregate::~NpAggregate() { NpFactory::getInstance().onAggregateRelease(this); if(getBaseFlags()&PxBaseFlag::eOWNS_MEMORY) PX_FREE(mActors); } void NpAggregate::scAddActor(NpActor& actor) { PX_ASSERT(!isAPIWriteForbidden()); actor.getActorCore().setAggregateID(mAggregateID); PvdAttachActorToAggregate( this, &actor ); PvdUpdateProperties( this ); } void NpAggregate::scRemoveActor(NpActor& actor, bool reinsert) { PX_ASSERT(!isAPIWriteForbidden()); Sc::ActorCore& ac = actor.getActorCore(); ac.setAggregateID(PX_INVALID_U32); if(getNpScene() && reinsert) ac.reinsertShapes(); //Update pvd status PvdDetachActorFromAggregate( this, &actor ); PvdUpdateProperties( this ); } void NpAggregate::removeAndReinsert(PxActor& actor, bool reinsert) { NpActor& np = NpActor::getFromPxActor(actor); np.setAggregate(NULL, actor); scRemoveActor(np, reinsert); } void NpAggregate::release() { NpScene* s = getNpScene(); NP_WRITE_CHECK(s); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(s, "PxAggregate::release() not allowed while simulation is running. Call will be ignored.") PX_SIMD_GUARD; NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, NULL); // "An aggregate should be empty when it gets released. If it isn't, the behavior should be: remove the actors from // the aggregate, then remove the aggregate from the scene (if any) then delete it. I guess that implies the actors // get individually reinserted into the broad phase if the aggregate is in a scene." for(PxU32 i=0;i<mNbActors;i++) { if (mActors[i]->getType() == PxActorType::eARTICULATION_LINK) { NpArticulationLink* link = static_cast<NpArticulationLink*>(mActors[i]); NpArticulationReducedCoordinate& articulation = static_cast<NpArticulationReducedCoordinate&>(link->getRoot()); articulation.setAggregate(NULL); } removeAndReinsert(*mActors[i], true); } if(s) { s->scRemoveAggregate(*this); s->removeFromAggregateList(*this); } NpDestroyAggregate(this); } void NpAggregate::addActorInternal(PxActor& actor, NpScene& s, const PxBVH* bvh) { if (actor.getType() != PxActorType::eARTICULATION_LINK) { NpActor& np = NpActor::getFromPxActor(actor); scAddActor(np); s.addActorInternal(actor, bvh); } else if (!actor.getScene()) // This check makes sure that a link of an articulation gets only added once. { NpArticulationLink& al = static_cast<NpArticulationLink&>(actor); PxArticulationReducedCoordinate& npArt = al.getRoot(); for(PxU32 i=0; i < npArt.getNbLinks(); i++) { PxArticulationLink* link; npArt.getLinks(&link, 1, i); scAddActor(*static_cast<NpArticulationLink*>(link)); } s.addArticulationInternal(npArt); } } void NpAggregate::addToScene(NpScene& scene) { const PxU32 nb = mNbActors; for(PxU32 i=0;i<nb;i++) { PX_ASSERT(mActors[i]); PxActor& actor = *mActors[i]; //A.B. check if a bvh was connected to that actor, we will use it for the insert and remove it NpActor& npActor = NpActor::getFromPxActor(actor); BVH* bvh = NULL; if(npActor.getConnectors<BVH>(NpConnectorType::eBvh, &bvh, 1)) npActor.removeConnector(actor, NpConnectorType::eBvh, bvh, "PxBVH connector could not have been removed!"); addActorInternal(actor, scene, bvh); // if a bvh was used dec ref count, we increased the ref count when adding the actor connection if(bvh) bvh->decRefCount(); } } bool NpAggregate::addActor(PxActor& actor, const PxBVH* bvh) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::addActor() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if(mNbActors==mMaxNbActors) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, max number of actors reached"); PxRigidActor* rigidActor = actor.is<PxRigidActor>(); PxU32 numShapes = 0; if(rigidActor) { numShapes = rigidActor->getNbShapes(); if ((mNbShapes + numShapes) > mMaxNbShapes) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, max number of shapes reached"); } if(actor.getAggregate()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, actor already belongs to an aggregate"); if(actor.getScene()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, actor already belongs to a scene"); const PxType ctype = actor.getConcreteType(); if(ctype == PxConcreteType::eARTICULATION_LINK) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation link to aggregate, only whole articulations can be added"); if(PxGetAggregateType(mFilterHint)==PxAggregateType::eSTATIC && ctype != PxConcreteType::eRIGID_STATIC) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add non-static actor to static aggregate"); if(PxGetAggregateType(mFilterHint)==PxAggregateType::eKINEMATIC) { bool isKine = false; if(ctype == PxConcreteType::eRIGID_DYNAMIC) { PxRigidDynamic& dyna = static_cast<PxRigidDynamic&>(actor); isKine = dyna.getRigidBodyFlags().isSet(PxRigidBodyFlag::eKINEMATIC); } if(!isKine) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add non-kinematic actor to kinematic aggregate"); } setAggregate(this, actor); mActors[mNbActors++] = &actor; mNbShapes += numShapes; OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxAggregate, actors, static_cast<PxAggregate&>(*this), actor); // PT: when an object is added to a aggregate at runtime, i.e. when the aggregate has already been added to the scene, // we need to immediately add the newcomer to the scene as well. if(npScene) { addActorInternal(actor, *npScene, bvh); } else { // A.B. if BVH is provided we need to keep it stored till the aggregate is inserted into a scene if(bvh) { PxBVH* bvhMutable = const_cast<PxBVH*>(bvh); static_cast<BVH*>(bvhMutable)->incRefCount(); NpActor::getFromPxActor(actor).addConnector(NpConnectorType::eBvh, bvhMutable, "PxBVH already added to the PxActor!"); } } return true; } bool NpAggregate::removeActorAndReinsert(PxActor& actor, bool reinsert) { for(PxU32 i=0;i<mNbActors;i++) { if(mActors[i]==&actor) { PxRigidActor* rigidActor = actor.is<PxRigidActor>(); if(rigidActor) mNbShapes -= rigidActor->getNbShapes(); mActors[i] = mActors[--mNbActors]; removeAndReinsert(actor, reinsert); return true; } } return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't remove actor, actor doesn't belong to aggregate"); } bool NpAggregate::removeActor(PxActor& actor) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::removeActor() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if(actor.getType() == PxActorType::eARTICULATION_LINK) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't remove articulation link, only whole articulations can be removed"); // A.B. remove the BVH reference if there is and the aggregate was not added to a scene if(!npScene) { NpActor& np = NpActor::getFromPxActor(actor); BVH* bvh = NULL; if(np.getConnectors<BVH>(NpConnectorType::eBvh, &bvh, 1)) { np.removeConnector(actor, NpConnectorType::eBvh, bvh, "PxBVH connector could not have been removed!"); bvh->decRefCount(); } } OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxAggregate, actors, static_cast<PxAggregate&>(*this), actor); // PT: there are really 2 cases here: // a) the user just wants to remove the actor from the aggregate, but the actor is still alive so if the aggregate has been added to a scene, // we must reinsert the removed actor to that same scene // b) this is called by the framework when releasing an actor, in which case we don't want to reinsert it anywhere. // // We assume that when called by the user, we always want to reinsert. The framework however will call the internal function // without reinsertion. return removeActorAndReinsert(actor, true); } bool NpAggregate::addArticulation(PxArticulationReducedCoordinate& art) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::addArticulation() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if((mNbActors+art.getNbLinks()) > mMaxNbActors) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation links, max number of actors reached"); const PxU32 numShapes = art.getNbShapes(); if((mNbShapes + numShapes) > mMaxNbShapes) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation, max number of shapes reached"); if(art.getAggregate()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation to aggregate, articulation already belongs to an aggregate"); if(art.getScene()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation to aggregate, articulation already belongs to a scene"); NpArticulationReducedCoordinate* impl = static_cast<NpArticulationReducedCoordinate*>(&art); impl->setAggregate(this); NpArticulationLink* const* links = impl->getLinks(); for(PxU32 i=0; i < impl->getNbLinks(); i++) { NpArticulationLink& l = *links[i]; setAggregate(this, l); mActors[mNbActors++] = &l; scAddActor(l); } mNbShapes += numShapes; // PT: when an object is added to a aggregate at runtime, i.e. when the aggregate has already been added to the scene, // we need to immediately add the newcomer to the scene as well. if(npScene) npScene->addArticulationInternal(art); return true; } bool NpAggregate::removeArticulationAndReinsert(PxArticulationReducedCoordinate& art, bool reinsert) { bool found = false; PxU32 idx = 0; while(idx < mNbActors) { if ((mActors[idx]->getType() == PxActorType::eARTICULATION_LINK) && (&static_cast<NpArticulationLink*>(mActors[idx])->getRoot() == &art)) { PxActor* a = mActors[idx]; mNbShapes -= static_cast<NpArticulationLink*>(mActors[idx])->getNbShapes(); mActors[idx] = mActors[--mNbActors]; removeAndReinsert(*a, reinsert); found = true; } else idx++; } static_cast<NpArticulationReducedCoordinate&>(art).setAggregate(NULL); if(!found) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't remove articulation, articulation doesn't belong to aggregate"); return found; } bool NpAggregate::removeArticulation(PxArticulationReducedCoordinate& art) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::removeArticulation() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; // see comments in removeActor() return removeArticulationAndReinsert(art, true); } PxU32 NpAggregate::getNbActors() const { NP_READ_CHECK(getNpScene()); return mNbActors; } PxU32 NpAggregate::getMaxNbActors() const { NP_READ_CHECK(getNpScene()); return mMaxNbActors; } PxU32 NpAggregate::getMaxNbShapes() const { NP_READ_CHECK(getNpScene()); return mMaxNbShapes; } PxU32 NpAggregate::getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mActors, getCurrentSizeFast()); } PxScene* NpAggregate::getScene() { return getNpScene(); } bool NpAggregate::getSelfCollision() const { NP_READ_CHECK(getNpScene()); return getSelfCollideFast(); } // PX_SERIALIZATION void NpAggregate::preExportDataReset() { mAggregateID = PX_INVALID_U32; } void NpAggregate::exportExtraData(PxSerializationContext& stream) { if(mActors) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mActors, mNbActors * sizeof(PxActor*)); } } void NpAggregate::importExtraData(PxDeserializationContext& context) { if(mActors) mActors = context.readExtraData<PxActor*, PX_SERIAL_ALIGN>(mNbActors); } void NpAggregate::resolveReferences(PxDeserializationContext& context) { // Resolve actor pointers if needed for(PxU32 i=0; i < mNbActors; i++) { context.translatePxBase(mActors[i]); { //update aggregate if mActors is in external reference NpActor& np = NpActor::getFromPxActor(*mActors[i]); if(np.getAggregate() == NULL) { np.setAggregate(this, *mActors[i]); } if(mActors[i]->getType() == PxActorType::eARTICULATION_LINK) { PxArticulationReducedCoordinate& articulation = static_cast<NpArticulationLink*>(mActors[i])->getRoot(); if(!articulation.getAggregate()) static_cast<NpArticulationReducedCoordinate&>(articulation).setAggregate(this); } } } } NpAggregate* NpAggregate::createObject(PxU8*& address, PxDeserializationContext& context) { NpAggregate* obj = PX_PLACEMENT_NEW(address, NpAggregate(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpAggregate); obj->importExtraData(context); obj->resolveReferences(context); return obj; } void NpAggregate::requiresObjects(PxProcessPxBaseCallback& c) { for(PxU32 i=0; i < mNbActors; i++) { PxArticulationLink* link = mActors[i]->is<PxArticulationLink>(); if(link) c.process(link->getArticulation()); else c.process(*mActors[i]); } } // ~PX_SERIALIZATION void NpAggregate::incShapeCount() { if(mNbShapes == mMaxNbShapes) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxRigidActor::attachShape: Actor is part of an aggregate and max number of shapes reached!"); mNbShapes++; } void NpAggregate::decShapeCount() { PX_ASSERT(mNbShapes > 0); mNbShapes--; }
17,839
C++
31.377495
167
0.730478
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpAggregate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_AGGREGATE_H #define NP_AGGREGATE_H #include "PxAggregate.h" #include "NpBase.h" namespace physx { class NpScene; class NpAggregate : public PxAggregate, public NpBase { public: // PX_SERIALIZATION NpAggregate(PxBaseFlags baseFlags) : PxAggregate(baseFlags), NpBase(PxEmpty) {} void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpAggregate* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint); virtual ~NpAggregate(); // PxAggregate virtual void release() PX_OVERRIDE; virtual bool addActor(PxActor&, const PxBVH*) PX_OVERRIDE; virtual bool removeActor(PxActor&) PX_OVERRIDE; virtual bool addArticulation(PxArticulationReducedCoordinate&) PX_OVERRIDE; virtual bool removeArticulation(PxArticulationReducedCoordinate&) PX_OVERRIDE; virtual PxU32 getNbActors() const PX_OVERRIDE; virtual PxU32 getMaxNbActors() const PX_OVERRIDE; virtual PxU32 getMaxNbShapes() const PX_OVERRIDE; virtual PxU32 getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE; virtual PxScene* getScene() PX_OVERRIDE; virtual bool getSelfCollision() const PX_OVERRIDE; //~PxAggregate PX_FORCE_INLINE PxU32 getMaxNbShapesFast() const { return mMaxNbShapes; } PX_FORCE_INLINE PxU32 getCurrentSizeFast() const { return mNbActors; } PX_FORCE_INLINE PxActor* getActorFast(PxU32 i) const { return mActors[i]; } PX_FORCE_INLINE PxU32 getAggregateID() const { return mAggregateID; } PX_FORCE_INLINE void setAggregateID(PxU32 cid) { mAggregateID = cid; } PX_FORCE_INLINE bool getSelfCollideFast() const { return PxGetAggregateSelfCollisionBit(mFilterHint)!=0; } PX_FORCE_INLINE PxAggregateFilterHint getFilterHint() const { return mFilterHint; } void scRemoveActor(NpActor& actor, bool reinsert); bool removeActorAndReinsert(PxActor& actor, bool reinsert); bool removeArticulationAndReinsert(PxArticulationReducedCoordinate& art, bool reinsert); void addToScene(NpScene& scene); void incShapeCount(); void decShapeCount(); private: PxU32 mAggregateID; PxU32 mMaxNbActors; PxU32 mMaxNbShapes; PxAggregateFilterHint mFilterHint; PxU32 mNbActors; PxU32 mNbShapes; PxActor** mActors; void scAddActor(NpActor&); void removeAndReinsert(PxActor& actor, bool reinsert); void addActorInternal(PxActor& actor, NpScene& s, const PxBVH* bvh); }; } #endif
4,748
C
45.558823
112
0.726411
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpShapeManager.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_SHAPE_MANAGER_H #define NP_SHAPE_MANAGER_H #include "NpShape.h" #include "CmPtrTable.h" #include "GuBVH.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif #include "SqTypedef.h" namespace physx { namespace Sq { class PruningStructure; class PrunerManager; } class NpScene; // PT: if we go through an SQ virtual interface then the implementation can be different from our internal version, // and nothing says it uses the same types as what we have internally in SQ. So we need a separate set of types. typedef PxSQCompoundHandle NpCompoundId; static const NpCompoundId NP_INVALID_COMPOUND_ID = NpCompoundId(Sq::INVALID_COMPOUND_ID); class NpShapeManager : public PxUserAllocated { public: // PX_SERIALIZATION static void getBinaryMetaData(PxOutputStream& stream); NpShapeManager(const PxEMPTY); void preExportDataReset(); void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); //~PX_SERIALIZATION NpShapeManager(); ~NpShapeManager(); PX_FORCE_INLINE PxU32 getNbShapes() const { return mShapes.getCount(); } PX_FORCE_INLINE NpShape* const* getShapes() const { return reinterpret_cast<NpShape*const*>(mShapes.getPtrs()); } PxU32 getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex=0) const; void attachShape(NpShape& shape, PxRigidActor& actor); bool detachShape(NpShape& s, PxRigidActor& actor, bool wakeOnLostTouch); void detachAll(PxSceneQuerySystem* pxsq, const PxRigidActor& actor); void setupSQShape(PxSceneQuerySystem& pxsq, const NpShape& shape, const NpActor& npActor, const PxRigidActor& actor, bool dynamic, const PxBounds3* bounds, const Sq::PruningStructure* ps); void setupSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape); void setupAllSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const Sq::PruningStructure* ps, const PxBounds3* bounds, bool isDynamic); void setupAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const Sq::PruningStructure* ps, const PxBounds3* bounds=NULL, const Gu::BVH* bvh = NULL); void teardownAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor); void teardownSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const NpShape& shape); void markShapeForSQUpdate(PxSceneQuerySystem& pxsq, const PxShape& shape, const PxRigidActor& actor); void markActorForSQUpdate(PxSceneQuerySystem& pxsq, const PxRigidActor& actor); PxBounds3 getWorldBounds_(const PxRigidActor&) const; PX_FORCE_INLINE void setPruningStructure(Sq::PruningStructure* ps) { mPruningStructure = ps; } PX_FORCE_INLINE Sq::PruningStructure* getPruningStructure() const { return mPruningStructure; } // PX_FORCE_INLINE bool isSqCompound() const { return mSqCompoundId != NP_INVALID_COMPOUND_ID; } // PX_FORCE_INLINE NpCompoundId getCompoundID() const { return mSqCompoundId; } // PX_FORCE_INLINE void setCompoundID(NpCompoundId id) { mSqCompoundId = id; } // PT: TODO: we don't really need to store the compound id anymore PX_FORCE_INLINE bool isSqCompound() const { return mShapes.mFreeSlot != NP_INVALID_COMPOUND_ID; } PX_FORCE_INLINE NpCompoundId getCompoundID() const { return mShapes.mFreeSlot; } PX_FORCE_INLINE void setCompoundID(NpCompoundId id) { mShapes.mFreeSlot = id; } void clearShapesOnRelease(NpScene& s, PxRigidActor&); #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, const PxRigidActor& actor, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif // for batching PX_FORCE_INLINE const Cm::PtrTable& getShapeTable() const { return mShapes; } static PX_FORCE_INLINE size_t getShapeTableOffset() { return PX_OFFSET_OF_RT(NpShapeManager, mShapes); } private: Cm::PtrTable mShapes; Sq::PruningStructure* mPruningStructure; // Shape scene query data are pre-build in pruning structure // NpCompoundId mSqCompoundId; void releaseExclusiveUserReferences(); void setupSceneQuery_(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape); void addBVHShapes(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const Gu::BVH& bvh); }; } #endif
6,320
C
48.771653
197
0.743987
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpShapeManager.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 "NpShapeManager.h" #include "NpPtrTableStorageManager.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "ScBodySim.h" #include "GuBounds.h" #include "NpAggregate.h" #include "CmTransformUtils.h" #include "NpRigidStatic.h" #include "foundation/PxSIMDHelpers.h" using namespace physx; using namespace Sq; using namespace Gu; using namespace Cm; // PT: TODO: refactor if we keep it static void getSQGlobalPose(PxTransform& globalPose, const NpShape& npShape, const NpActor& npActor) { const PxTransform& shape2Actor = npShape.getCore().getShape2Actor(); PX_ALIGN(16, PxTransform) kinematicTarget; // PT: TODO: duplicated from SqBounds.cpp. Refactor. const NpType::Enum actorType = npActor.getNpType(); const PxTransform* actor2World; if(actorType==NpType::eRIGID_STATIC) { actor2World = &static_cast<const NpRigidStatic&>(npActor).getCore().getActor2World(); if(npShape.getCore().getCore().mShapeCoreFlags.isSet(PxShapeCoreFlag::eIDT_TRANSFORM)) { PX_ASSERT(shape2Actor.p.isZero() && shape2Actor.q.isIdentity()); globalPose = *actor2World; return; } } else { PX_ASSERT(actorType==NpType::eBODY || actorType == NpType::eBODY_FROM_ARTICULATION_LINK); const PxU16 sqktFlags = PxRigidBodyFlag::eKINEMATIC | PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES; // PT: TODO: revisit this once the dust has settled const Sc::BodyCore& core = actorType==NpType::eBODY ? static_cast<const NpRigidDynamic&>(npActor).getCore() : static_cast<const NpArticulationLink&>(npActor).getCore(); const bool useTarget = (PxU16(core.getFlags()) & sqktFlags) == sqktFlags; const PxTransform& body2World = (useTarget && core.getKinematicTarget(kinematicTarget)) ? kinematicTarget : core.getBody2World(); if(!core.getCore().hasIdtBody2Actor()) { Cm::getDynamicGlobalPoseAligned(body2World, shape2Actor, core.getBody2Actor(), globalPose); return; } actor2World = &body2World; } Cm::getStaticGlobalPoseAligned(*actor2World, shape2Actor, globalPose); } static PX_FORCE_INLINE bool isSceneQuery(const NpShape& shape) { return shape.getFlagsFast() & PxShapeFlag::eSCENE_QUERY_SHAPE; } static PX_FORCE_INLINE bool isDynamicActor(const PxRigidActor& actor) { const PxType actorType = actor.getConcreteType(); return actorType != PxConcreteType::eRIGID_STATIC; } static PX_FORCE_INLINE bool isDynamicActor(const NpActor& actor) { const NpType::Enum actorType = actor.getNpType(); return actorType != NpType::eRIGID_STATIC; } NpShapeManager::NpShapeManager() : mPruningStructure (NULL) { setCompoundID(NP_INVALID_COMPOUND_ID); } // PX_SERIALIZATION NpShapeManager::NpShapeManager(const PxEMPTY) : mShapes (PxEmpty) { } NpShapeManager::~NpShapeManager() { PX_ASSERT(!mPruningStructure); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); mShapes.clear(sm); } void NpShapeManager::preExportDataReset() { } void NpShapeManager::exportExtraData(PxSerializationContext& stream) { mShapes.exportExtraData(stream); } void NpShapeManager::importExtraData(PxDeserializationContext& context) { mShapes.importExtraData(context); } //~PX_SERIALIZATION static PX_INLINE void onShapeAttach(NpActor& ro, NpShape& shape) { // * if the shape is exclusive, set its Sc control state appropriately. // * add the shape to pvd. NpScene* npScene = ro.getNpScene(); if(!npScene) return; PX_ASSERT(!npScene->isAPIWriteForbidden()); if(!(ro.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) ro.getScRigidCore().addShapeToScene(shape.getCore()); #if PX_SUPPORT_PVD npScene->getScenePvdClientInternal().createPvdInstance(&shape, *ro.getScRigidCore().getPxActor()); #endif shape.setSceneIfExclusive(npScene); } static PX_INLINE void onShapeDetach(NpActor& ro, NpShape& shape, bool wakeOnLostTouch) { // see comments in onShapeAttach NpScene* npScene = ro.getNpScene(); if(!npScene) return; PX_ASSERT(!npScene->isAPIWriteForbidden()); #if PX_SUPPORT_PVD npScene->getScenePvdClientInternal().releasePvdInstance(&shape, *ro.getScRigidCore().getPxActor()); #endif if(!(ro.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) ro.getScRigidCore().removeShapeFromScene(shape.getCore(), wakeOnLostTouch); shape.setSceneIfExclusive(NULL); } void NpShapeManager::attachShape(NpShape& shape, PxRigidActor& actor) { PX_ASSERT(!mPruningStructure); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); const PxU32 index = getNbShapes(); mShapes.add(&shape, sm); NpActor& ro = NpActor::getFromPxActor(actor); NpScene* scene = NpActor::getNpSceneFromActor(actor); if(scene && isSceneQuery(shape)) { // PT: SQ_CODEPATH2 setupSceneQuery_(scene->getSQAPI(), ro, actor, shape); } onShapeAttach(ro, shape); PxAggregate* agg = ro.getAggregate(); if(agg) static_cast<NpAggregate*>(agg)->incShapeCount(); PX_ASSERT(!shape.isExclusive() || shape.getActor()==NULL); shape.onActorAttach(actor); shape.setShapeManagerArrayIndex(index); } bool NpShapeManager::detachShape(NpShape& s, PxRigidActor& actor, bool wakeOnLostTouch) { PX_ASSERT(!mPruningStructure); const PxU32 index = s.getShapeManagerArrayIndex(mShapes); if(index==0xffffffff) return false; NpScene* scene = NpActor::getNpSceneFromActor(actor); if(scene && isSceneQuery(s)) { scene->getSQAPI().removeSQShape(actor, s); // if this is the last shape of a compound shape, we have to remove the compound id // and in case of a dynamic actor, remove it from the active list if(isSqCompound() && (mShapes.getCount() == 1)) { setCompoundID(NP_INVALID_COMPOUND_ID); const PxType actorType = actor.getConcreteType(); // for PxRigidDynamic and PxArticulationLink we need to remove the compound rigid flag and remove them from active list if(actorType == PxConcreteType::eRIGID_DYNAMIC) static_cast<NpRigidDynamic&>(actor).getCore().getSim()->disableCompound(); else if(actorType == PxConcreteType::eARTICULATION_LINK) static_cast<NpArticulationLink&>(actor).getCore().getSim()->disableCompound(); } } NpActor& ro = NpActor::getFromPxActor(actor); onShapeDetach(ro, s, wakeOnLostTouch); PxAggregate* agg = ro.getAggregate(); if (agg) static_cast<NpAggregate*>(agg)->decShapeCount(); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); void** ptrs = mShapes.getPtrs(); PX_ASSERT(reinterpret_cast<NpShape*>(ptrs[index]) == &s); const PxU32 last = mShapes.getCount() - 1; if (index != last) { NpShape* moved = reinterpret_cast<NpShape*>(ptrs[last]); PX_ASSERT(moved->checkShapeManagerArrayIndex(mShapes)); moved->setShapeManagerArrayIndex(index); } mShapes.replaceWithLast(index, sm); s.clearShapeManagerArrayIndex(); s.onActorDetach(); return true; } void NpShapeManager::detachAll(PxSceneQuerySystem* pxsq, const PxRigidActor& actor) { // assumes all SQ data has been released, which is currently the responsibility of the owning actor const PxU32 nbShapes = getNbShapes(); NpShape*const *shapes = getShapes(); if(pxsq) teardownAllSceneQuery(*pxsq, actor); // actor cleanup in Sc will remove any outstanding references corresponding to sim objects, so we don't need to do that here. for(PxU32 i=0;i<nbShapes;i++) shapes[i]->onActorDetach(); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); mShapes.clear(sm); } PxU32 NpShapeManager::getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex) const { return getArrayOfPointers(buffer, bufferSize, startIndex, getShapes(), getNbShapes()); } // PT: this one is only used by the API getWorldBounds() functions PxBounds3 NpShapeManager::getWorldBounds_(const PxRigidActor& actor) const { PxBounds3 bounds(PxBounds3::empty()); const PxU32 nbShapes = getNbShapes(); NpShape*const* PX_RESTRICT shapes = getShapes(); const PxTransform32 actorPose(actor.getGlobalPose()); for(PxU32 i=0;i<nbShapes;i++) { PxTransform32 shapeAbsPose; aos::transformMultiply<true, true>(shapeAbsPose, actorPose, shapes[i]->getLocalPoseFast()); bounds.include(computeBounds(shapes[i]->getCore().getGeometry(), shapeAbsPose)); } return bounds; } void NpShapeManager::clearShapesOnRelease(NpScene& s, PxRigidActor& r) { PX_ASSERT(NpActor::getFromPxActor(r).getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)); const PxU32 nbShapes = getNbShapes(); #if PX_SUPPORT_PVD NpShape*const* PX_RESTRICT shapes = getShapes(); #endif for(PxU32 i=0;i<nbShapes;i++) { #if PX_SUPPORT_PVD s.getScenePvdClientInternal().releasePvdInstance(shapes[i], r); #else PX_UNUSED(s); PX_UNUSED(r); #endif } } void NpShapeManager::releaseExclusiveUserReferences() { // when the factory is torn down, release any shape owner refs that are still outstanding const PxU32 nbShapes = getNbShapes(); NpShape*const* PX_RESTRICT shapes = getShapes(); for(PxU32 i=0;i<nbShapes;i++) { if(shapes[i]->isExclusiveFast() && shapes[i]->getReferenceCount()>1) shapes[i]->release(); } } void NpShapeManager::setupSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape) { PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE); setupSceneQuery_(pxsq, npActor, actor, shape); } // PT: TODO: function called from a single place? void NpShapeManager::teardownSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const NpShape& shape) { pxsq.removeSQShape(actor, shape); } void NpShapeManager::setupAllSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const PruningStructure* ps, const PxBounds3* bounds, bool isDynamic) { const PxU32 nbShapes = getNbShapes(); NpShape*const *shapes = getShapes(); for(PxU32 i=0;i<nbShapes;i++) { if(isSceneQuery(*shapes[i])) setupSQShape(pxsq, *shapes[i], npActor, actor, isDynamic, bounds ? bounds + i : NULL, ps); } } void NpShapeManager::setupAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const PruningStructure* ps, const PxBounds3* bounds, const BVH* bvh) { // if BVH was provided, we add shapes into compound pruner if(bvh) addBVHShapes(pxsq, actor, *bvh); else setupAllSceneQuery(pxsq, NpActor::getFromPxActor(actor), actor, ps, bounds, isDynamicActor(actor)); } void NpShapeManager::teardownAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor) { NpShape*const *shapes = getShapes(); const PxU32 nbShapes = getNbShapes(); if(isSqCompound()) { pxsq.removeSQCompound(getCompoundID()); setCompoundID(NP_INVALID_COMPOUND_ID); } else { for(PxU32 i=0;i<nbShapes;i++) { if(isSceneQuery(*shapes[i])) pxsq.removeSQShape(actor, *shapes[i]); } } } void NpShapeManager::markShapeForSQUpdate(PxSceneQuerySystem& pxsq, const PxShape& shape, const PxRigidActor& actor) { // PT: SQ_CODEPATH4 PX_ALIGN(16, PxTransform) transform; const NpShape& nbShape = static_cast<const NpShape&>(shape); const NpActor& npActor = NpActor::getFromPxActor(actor); if(getCompoundID() == NP_INVALID_COMPOUND_ID) getSQGlobalPose(transform, nbShape, npActor); else transform = nbShape.getCore().getShape2Actor(); pxsq.updateSQShape(actor, shape, transform); } void NpShapeManager::markActorForSQUpdate(PxSceneQuerySystem& pxsq, const PxRigidActor& actor) { // PT: SQ_CODEPATH5 if(isSqCompound()) { pxsq.updateSQCompound(getCompoundID(), actor.getGlobalPose()); } else { const NpActor& npActor = NpActor::getFromPxActor(actor); const PxU32 nbShapes = getNbShapes(); for(PxU32 i=0;i<nbShapes;i++) { const NpShape& npShape = *getShapes()[i]; if(isSceneQuery(npShape)) { PX_ALIGN(16, PxTransform) transform; getSQGlobalPose(transform, npShape, npActor); pxsq.updateSQShape(actor, npShape, transform); } } } } // // internal methods // #include "NpBounds.h" void NpShapeManager::addBVHShapes(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const BVH& bvh) { const PxU32 nbShapes = getNbShapes(); PX_ALLOCA(scShapes, const PxShape*, nbShapes); PxU32 numSqShapes = 0; { for(PxU32 i=0; i<nbShapes; i++) { const NpShape& shape = *getShapes()[i]; if(isSceneQuery(shape)) scShapes[numSqShapes++] = &shape; } PX_ASSERT(numSqShapes == bvh.getNbBounds()); } PX_ALLOCA(transforms, PxTransform, numSqShapes); for(PxU32 i=0; i<numSqShapes; i++) { const NpShape* npShape = static_cast<const NpShape*>(scShapes[i]); transforms[i] = npShape->getLocalPoseFast(); } const PxSQCompoundHandle cid = pxsq.addSQCompound(actor, scShapes, bvh, transforms); setCompoundID(cid); } void NpShapeManager::setupSQShape(PxSceneQuerySystem& pxsq, const NpShape& shape, const NpActor& npActor, const PxRigidActor& actor, bool dynamic, const PxBounds3* bounds, const PruningStructure* ps) { PX_ALIGN(16, PxTransform) transform; PxBounds3 b; if(getCompoundID() == NP_INVALID_COMPOUND_ID) { if(bounds) inflateBounds<true>(b, *bounds, SQ_PRUNER_EPSILON); else (gComputeBoundsTable[dynamic])(b, shape, npActor); // PT: TODO: don't recompute it? getSQGlobalPose(transform, shape, npActor); } else { const PxTransform& shape2Actor = shape.getCore().getShape2Actor(); Gu::computeBounds(b, shape.getCore().getGeometry(), shape2Actor, 0.0f, SQ_PRUNER_INFLATION); transform = shape2Actor; } const NpCompoundId cid = getCompoundID(); pxsq.addSQShape(actor, shape, b, transform, &cid, ps!=NULL); } void NpShapeManager::setupSceneQuery_(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape) { const bool isDynamic = isDynamicActor(npActor); setupSQShape(pxsq, shape, npActor, actor, isDynamic, NULL, NULL); }
15,376
C++
29.815631
199
0.744927
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationReducedCoordinate.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_ARTICULATION_RC_H #define NP_ARTICULATION_RC_H #include "PxArticulationReducedCoordinate.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif #include "NpArticulationLink.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationTendon.h" #include "ScArticulationCore.h" namespace physx { class NpArticulationLink; class NpScene; class PxAggregate; class PxConstraint; class NpArticulationSpatialTendon; class NpArticulationFixedTendon; class NpArticulationSensor; class NpArticulationReducedCoordinate : public PxArticulationReducedCoordinate, public NpBase { public: virtual ~NpArticulationReducedCoordinate(); // PX_SERIALIZATION NpArticulationReducedCoordinate(PxBaseFlags baseFlags) : PxArticulationReducedCoordinate(baseFlags), NpBase(PxEmpty), mCore(PxEmpty), mArticulationLinks(PxEmpty), mLoopJoints(PxEmpty), mSpatialTendons(PxEmpty), mFixedTendons(PxEmpty), mSensors(PxEmpty) { } void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpArticulationReducedCoordinate* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION virtual void release(); //--------------------------------------------------------------------------------- // PxArticulationReducedCoordinate implementation //--------------------------------------------------------------------------------- virtual PxScene* getScene() const { return NpBase::getNpScene(); } virtual void setSleepThreshold(PxReal threshold); virtual PxReal getSleepThreshold() const; virtual void setStabilizationThreshold(PxReal threshold); virtual PxReal getStabilizationThreshold() const; virtual void setWakeCounter(PxReal wakeCounterValue); virtual PxReal getWakeCounter() const; virtual void setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters);// { mImpl.setSolverIterationCounts(positionIters, velocityIters); } virtual void getSolverIterationCounts(PxU32 & positionIters, PxU32 & velocityIters) const;// { mImpl.getSolverIterationCounts(positionIters, velocityIters); } virtual bool isSleeping() const; virtual void wakeUp(); virtual void putToSleep(); virtual void setMaxCOMLinearVelocity(const PxReal maxLinearVelocity); virtual PxReal getMaxCOMLinearVelocity() const; virtual void setMaxCOMAngularVelocity(const PxReal maxAngularVelocity); virtual PxReal getMaxCOMAngularVelocity() const; virtual PxU32 getNbLinks() const; virtual PxU32 getLinks(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; /*{ return mImpl.getLinks(userBuffer, bufferSize, startIndex); } */ virtual PxU32 getNbShapes() const; virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const; virtual PxAggregate* getAggregate() const; // Debug name virtual void setName(const char* name); virtual const char* getName() const; virtual PxArticulationLink* createLink(PxArticulationLink* parent, const PxTransform& pose); virtual void setArticulationFlags(PxArticulationFlags flags); virtual void setArticulationFlag(PxArticulationFlag::Enum flag, bool value); virtual PxArticulationFlags getArticulationFlags() const; virtual PxU32 getDofs() const; virtual PxArticulationCache* createCache() const; virtual PxU32 getCacheDataSize() const; virtual void zeroCache(PxArticulationCache& cache) const; virtual void applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags, bool autowake); virtual void copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags) const; virtual void packJointData(const PxReal* maximum, PxReal* reduced) const; virtual void unpackJointData(const PxReal* reduced, PxReal* maximum) const; virtual void commonInit() const; virtual void computeGeneralizedGravityForce(PxArticulationCache& cache) const; virtual void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const; virtual void computeGeneralizedExternalForce(PxArticulationCache& cache) const; virtual void computeJointAcceleration(PxArticulationCache& cache) const; virtual void computeJointForce(PxArticulationCache& cache) const; virtual void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const; virtual void computeCoefficientMatrix(PxArticulationCache& cache) const; virtual bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* const jointTorque, const PxU32 maxIter) const; virtual void computeGeneralizedMassMatrix(PxArticulationCache& cache) const; virtual void addLoopJoint(PxConstraint* joint); virtual void removeLoopJoint(PxConstraint* constraint); virtual PxU32 getNbLoopJoints() const; virtual PxU32 getLoopJoints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getCoefficientMatrixSize() const; virtual void setRootGlobalPose(const PxTransform& pose, bool autowake = true); virtual PxTransform getRootGlobalPose() const; virtual void setRootLinearVelocity(const PxVec3& velocity, bool autowake = true); virtual void setRootAngularVelocity(const PxVec3& velocity, bool autowake = true); virtual PxVec3 getRootLinearVelocity() const; virtual PxVec3 getRootAngularVelocity() const; virtual PxSpatialVelocity getLinkAcceleration(const PxU32 linkId); virtual PxU32 getGpuArticulationIndex(); virtual const char* getConcreteTypeName() const { return "PxArticulationReducedCoordinate"; } virtual PxArticulationSpatialTendon* createSpatialTendon(); virtual PxU32 getSpatialTendons(PxArticulationSpatialTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbSpatialTendons(); NpArticulationSpatialTendon* getSpatialTendon(const PxU32 index) const; virtual PxArticulationFixedTendon* createFixedTendon(); virtual PxU32 getFixedTendons(PxArticulationFixedTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbFixedTendons(); NpArticulationFixedTendon* getFixedTendon(const PxU32 index) const; virtual PxArticulationSensor* createSensor(PxArticulationLink* link, const PxTransform& relativePose); virtual void releaseSensor(PxArticulationSensor& sensor); virtual PxU32 getSensors(PxArticulationSensor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbSensors(); NpArticulationSensor* getSensor(const PxU32 index) const; virtual void updateKinematic(PxArticulationKinematicFlags flags); PX_FORCE_INLINE PxArray<NpArticulationSpatialTendon*>& getSpatialTendons() { return mSpatialTendons; } PX_FORCE_INLINE PxArray<NpArticulationFixedTendon*>& getFixedTendons() { return mFixedTendons; } PX_FORCE_INLINE PxArray<NpArticulationSensor*>& getSensors() { return mSensors; } //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpArticulationReducedCoordinate(); virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationReducedCoordinate", PxBase); } PxArticulationJointReducedCoordinate* createArticulationJoint(PxArticulationLink& parent, const PxTransform& parentFrame, PxArticulationLink& child, const PxTransform& childFrame); PX_INLINE void incrementShapeCount() { mNumShapes++; } PX_INLINE void decrementShapeCount() { mNumShapes--; } //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- PX_INLINE void addToLinkList(NpArticulationLink& link) { mArticulationLinks.pushBack(&link); mNumShapes += link.getNbShapes(); } PX_INLINE bool removeLinkFromList(NpArticulationLink& link) { PX_ASSERT(mArticulationLinks.find(&link) != mArticulationLinks.end()); mTopologyChanged = true; return mArticulationLinks.findAndReplaceWithLast(&link); } PX_FORCE_INLINE NpArticulationLink* const* getLinks() { return mArticulationLinks.begin(); } NpArticulationLink* getRoot(); void setAggregate(PxAggregate* a); void wakeUpInternal(bool forceWakeUp, bool autowake); void autoWakeInternal(); void setGlobalPose(); PX_FORCE_INLINE Sc::ArticulationCore& getCore() { return mCore; } PX_FORCE_INLINE const Sc::ArticulationCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpArticulationReducedCoordinate, mCore); } PX_INLINE void scSetSolverIterationCounts(PxU16 v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setSolverIterationCounts(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetSleepThreshold(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setSleepThreshold(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetFreezeThreshold(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setFreezeThreshold(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetWakeCounter(PxReal counter) { PX_ASSERT(!isAPIWriteForbiddenExceptSplitSim()); mCore.setWakeCounter(counter); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE void scSetArticulationFlags(PxArticulationFlags flags) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setArticulationFlags(flags); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE void scWakeUpInternal(PxReal wakeCounter) { PX_ASSERT(getNpScene()); PX_ASSERT(!isAPIWriteForbiddenExceptSplitSim()); mCore.wakeUp(wakeCounter); } PX_FORCE_INLINE void scSetMaxLinearVelocity(PxReal maxLinearVelocity) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMaxLinearVelocity(maxLinearVelocity); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE void scSetMaxAngularVelocity(PxReal maxAngularVelocity) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMaxAngularVelocity(maxAngularVelocity); UPDATE_PVD_PROPERTY } void recomputeLinkIDs(); #if PX_ENABLE_DEBUG_VISUALIZATION public: void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif Sc::ArticulationCore mCore; NpArticulationLinkArray mArticulationLinks; PxU32 mNumShapes; NpAggregate* mAggregate; const char* mName; PxU32 mCacheVersion; bool mTopologyChanged; private: void removeSpatialTendonInternal(NpArticulationSpatialTendon* tendon); void removeFixedTendonInternal(NpArticulationFixedTendon* tendon); void removeSensorInternal(NpArticulationSensor* sensor); PxArray<NpConstraint*> mLoopJoints; PxArray<NpArticulationSpatialTendon*> mSpatialTendons; PxArray<NpArticulationFixedTendon*> mFixedTendons; PxArray<NpArticulationSensor*> mSensors; friend class NpScene; }; } #endif
13,700
C
37.378151
167
0.711971
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidDynamic.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 "NpRigidDynamic.h" #include "NpRigidActorTemplateInternal.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// NpRigidDynamic::NpRigidDynamic(const PxTransform& bodyPose) : NpRigidDynamicT(PxConcreteType::eRIGID_DYNAMIC, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, PxActorType::eRIGID_DYNAMIC, NpType::eBODY, bodyPose) {} NpRigidDynamic::~NpRigidDynamic() { } // PX_SERIALIZATION void NpRigidDynamic::requiresObjects(PxProcessPxBaseCallback& c) { NpRigidDynamicT::requiresObjects(c); } void NpRigidDynamic::preExportDataReset() { NpRigidDynamicT::preExportDataReset(); if (isKinematic() && getNpScene()) { //Restore dynamic data in case the actor is configured as a kinematic. //otherwise we would loose the data for switching the kinematic actor back to dynamic //after deserialization. Not necessary if the kinematic is not yet part of //a scene since the dynamic data will still hold the original values. mCore.restoreDynamicData(); } } NpRigidDynamic* NpRigidDynamic::createObject(PxU8*& address, PxDeserializationContext& context) { NpRigidDynamic* obj = PX_PLACEMENT_NEW(address, NpRigidDynamic(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpRigidDynamic); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpRigidDynamic::release() { if(releaseRigidActorT<PxRigidDynamic>(*this)) { PX_ASSERT(!isAPIWriteForbidden()); // the code above should return false in that case NpDestroyRigidDynamic(this); } } void NpRigidDynamic::setGlobalPose(const PxTransform& pose, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidDynamic::setGlobalPose: pose is not valid."); #if PX_CHECKED if(npScene) npScene->checkPositionSanity(*this, pose, "PxRigidDynamic::setGlobalPose"); #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setGlobalPose() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setGlobalPose(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } const PxTransform newPose = pose.getNormalized(); //AM: added to fix 1461 where users read and write orientations for no reason. const PxTransform body2World = newPose * mCore.getBody2Actor(); scSetBody2World(body2World); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, *static_cast<PxRigidActor*>(this), newPose.p); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, *static_cast<PxRigidActor*>(this), newPose.q); OMNI_PVD_WRITE_SCOPE_END if(npScene) mShapeManager.markActorForSQUpdate(npScene->getSQAPI(), *this); // invalidate the pruning structure if the actor bounds changed if(mShapeManager.getPruningStructure()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setGlobalPose: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } if(npScene && autowake && !(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) wakeUpInternal(); } PX_FORCE_INLINE void NpRigidDynamic::setKinematicTargetInternal(const PxTransform& targetPose) { // The target is actor related. Transform to body related target const PxTransform bodyTarget = targetPose * mCore.getBody2Actor(); scSetKinematicTarget(bodyTarget); NpScene* scene = getNpScene(); if((mCore.getFlags() & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) && scene) mShapeManager.markActorForSQUpdate(scene->getSQAPI(), *this); } void NpRigidDynamic::setKinematicTarget(const PxTransform& destination) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(destination.isSane(), "PxRigidDynamic::setKinematicTarget: destination is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::setKinematicTarget: Body must be in a scene!"); PX_CHECK_AND_RETURN((mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setKinematicTarget: Body must be kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setKinematicTarget: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); #if PX_CHECKED if(npScene) npScene->checkPositionSanity(*this, destination, "PxRigidDynamic::setKinematicTarget"); #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setKinematicTarget() not allowed while simulation is running. Call will be ignored.") setKinematicTargetInternal(destination.getNormalized()); } bool NpRigidDynamic::getKinematicTarget(PxTransform& target) const { NP_READ_CHECK(getNpScene()); if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { PxTransform bodyTarget; if(mCore.getKinematicTarget(bodyTarget)) { // The internal target is body related. Transform to actor related target target = bodyTarget * mCore.getBody2Actor().getInverse(); return true; } } return false; } void NpRigidDynamic::setCMassLocalPose(const PxTransform& pose) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidDynamic::setCMassLocalPose pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setCMassLocalPose() not allowed while simulation is running. Call will be ignored.") const PxTransform p = pose.getNormalized(); const PxTransform oldBody2Actor = mCore.getBody2Actor(); NpRigidDynamicT::setCMassLocalPoseInternal(p); if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { PxTransform bodyTarget; if(mCore.getKinematicTarget(bodyTarget)) { PxTransform actorTarget = bodyTarget * oldBody2Actor.getInverse(); // get old target pose for the actor from the body target setKinematicTargetInternal(actorTarget); } } } void NpRigidDynamic::setLinearVelocity(const PxVec3& velocity, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(velocity.isFinite(), "PxRigidDynamic::setLinearVelocity: velocity is not valid."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setLinearVelocity: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setLinearVelocity: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setLinearVelocity() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setLinearVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } scSetLinearVelocity(velocity); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, *static_cast<PxRigidBody*>(this), velocity); if(npScene) wakeUpInternalNoKinematicTest((!velocity.isZero()), autowake); } void NpRigidDynamic::setAngularVelocity(const PxVec3& velocity, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(velocity.isFinite(), "PxRigidDynamic::setAngularVelocity: velocity is not valid."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setAngularVelocity: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setAngularVelocity: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setAngularVelocity() not allowed while simulation is running. Call will be ignored.") scSetAngularVelocity(velocity); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, *static_cast<PxRigidBody*>(this), velocity); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setAngularVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } if(npScene) wakeUpInternalNoKinematicTest((!velocity.isZero()), autowake); } void NpRigidDynamic::addForce(const PxVec3& force, PxForceMode::Enum mode, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(force.isFinite(), "PxRigidDynamic::addForce: force is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::addForce: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::addForce: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::addForce() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::addForce: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::addForce(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } addSpatialForce(&force, NULL, mode); wakeUpInternalNoKinematicTest(!force.isZero(), autowake); } void NpRigidDynamic::setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(force.isFinite(), "PxRigidDynamic::setForceAndTorque: force is not valid."); PX_CHECK_AND_RETURN(torque.isFinite(), "PxRigidDynamic::setForceAndTorque: torque is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::setForceAndTorque: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setForceAndTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setForceAndTorque() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setForceAndTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::setForceAndTorque: Body must be non-kinematic!"); return; } setSpatialForce(&force, &torque, mode); wakeUpInternalNoKinematicTest(!force.isZero(), true); } void NpRigidDynamic::addTorque(const PxVec3& torque, PxForceMode::Enum mode, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(torque.isFinite(), "PxRigidDynamic::addTorque: torque is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::addTorque: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::addTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::addTorque() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::addTorque: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::addTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } addSpatialForce(NULL, &torque, mode); wakeUpInternalNoKinematicTest(!torque.isZero(), autowake); } void NpRigidDynamic::clearForce(PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::clearForce: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::clearForce: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::clearForce() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::clearForce: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::clearForce(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } clearSpatialForce(mode, true, false); } void NpRigidDynamic::clearTorque(PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::clearTorque: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::clearTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::clearTorque() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::clearTorque: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::clearTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } clearSpatialForce(mode, false, true); } bool NpRigidDynamic::isSleeping() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::isSleeping: Body must be in a scene.", true); PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::isSleeping() not allowed while simulation is running.", true); return mCore.isSleeping(); } void NpRigidDynamic::setSleepThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setSleepThreshold: invalid float."); PX_CHECK_AND_RETURN(threshold>=0.0f, "PxRigidDynamic::setSleepThreshold: threshold must be non-negative!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setSleepThreshold() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, sleepThreshold, static_cast<PxRigidDynamic&>(*this), threshold); // @@@ mCore.setSleepThreshold(threshold); UPDATE_PVD_PROPERTY_BODY } PxReal NpRigidDynamic::getSleepThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getSleepThreshold(); } void NpRigidDynamic::setStabilizationThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setSleepThreshold: invalid float."); PX_CHECK_AND_RETURN(threshold>=0.0f, "PxRigidDynamic::setSleepThreshold: threshold must be non-negative!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setStabilizationThreshold() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, stabilizationThreshold, static_cast<PxRigidDynamic&>(*this), threshold); // @@@ mCore.setFreezeThreshold(threshold); UPDATE_PVD_PROPERTY_BODY } PxReal NpRigidDynamic::getStabilizationThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getFreezeThreshold(); } void NpRigidDynamic::setWakeCounter(PxReal wakeCounterValue) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(wakeCounterValue), "PxRigidDynamic::setWakeCounter: invalid float."); PX_CHECK_AND_RETURN(wakeCounterValue>=0.0f, "PxRigidDynamic::setWakeCounter: wakeCounterValue must be non-negative!"); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setWakeCounter: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setWakeCounter: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setWakeCounter() not allowed while simulation is running. Call will be ignored.") scSetWakeCounter(wakeCounterValue); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, wakeCounter, static_cast<PxRigidDynamic&>(*this), wakeCounterValue); // @@@ } PxReal NpRigidDynamic::getWakeCounter() const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::getWakeCounter() not allowed while simulation is running.", 0.0f); return mCore.getWakeCounter(); } void NpRigidDynamic::wakeUp() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::wakeUp: Body must be in a scene."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::wakeUp: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::wakeUp: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::wakeUp() not allowed while simulation is running. Call will be ignored.") scWakeUp(); } void NpRigidDynamic::putToSleep() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::putToSleep: Body must be in a scene."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::putToSleep: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::putToSleep: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::putToSleep() not allowed while simulation is running. Call will be ignored.") scPutToSleep(); } void NpRigidDynamic::setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(positionIters > 0, "PxRigidDynamic::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(positionIters <= 255, "PxRigidDynamic::setSolverIterationCounts: positionIters must be no greater than 255!"); PX_CHECK_AND_RETURN(velocityIters <= 255, "PxRigidDynamic::setSolverIterationCounts: velocityIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") scSetSolverIterationCounts((velocityIters & 0xff) << 8 | (positionIters & 0xff)); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, positionIterations, static_cast<PxRigidDynamic&>(*this), positionIters); // @@@ OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, velocityIterations, static_cast<PxRigidDynamic&>(*this), velocityIters); // @@@ OMNI_PVD_WRITE_SCOPE_END } void NpRigidDynamic::getSolverIterationCounts(PxU32 & positionIters, PxU32 & velocityIters) const { NP_READ_CHECK(getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); velocityIters = PxU32(x >> 8); positionIters = PxU32(x & 0xff); } void NpRigidDynamic::setContactReportThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setContactReportThreshold: invalid float."); PX_CHECK_AND_RETURN(threshold >= 0.0f, "PxRigidDynamic::setContactReportThreshold: Force threshold must be greater than zero!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setContactReportThreshold() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, contactReportThreshold, static_cast<PxRigidDynamic&>(*this), threshold); // @@@ mCore.setContactReportThreshold(threshold<0 ? 0 : threshold); UPDATE_PVD_PROPERTY_BODY } PxReal NpRigidDynamic::getContactReportThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getContactReportThreshold(); } PxU32 physx::NpRigidDynamicGetShapes(NpRigidDynamic& actor, NpShape* const*& shapes, bool* isCompound) { NpShapeManager& sm = actor.getShapeManager(); shapes = sm.getShapes(); if(isCompound) *isCompound = sm.isSqCompound(); return sm.getNbShapes(); } void NpRigidDynamic::switchToNoSim() { NpActor::scSwitchToNoSim(); scPutToSleepInternal(); } void NpRigidDynamic::switchFromNoSim() { NpActor::scSwitchFromNoSim(); } void NpRigidDynamic::wakeUpInternalNoKinematicTest(bool forceWakeUp, bool autowake) { NpScene* scene = getNpScene(); PX_ASSERT(scene); PxReal wakeCounterResetValue = scene->getWakeCounterResetValueInternal(); PxReal wakeCounter = mCore.getWakeCounter(); bool needsWakingUp = mCore.isSleeping() && (autowake || forceWakeUp); if (autowake && (wakeCounter < wakeCounterResetValue)) { wakeCounter = wakeCounterResetValue; needsWakingUp = true; } if (needsWakingUp) scWakeUpInternal(wakeCounter); } PxRigidDynamicLockFlags NpRigidDynamic::getRigidDynamicLockFlags() const { return mCore.getRigidDynamicLockFlags(); } void NpRigidDynamic::setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxRigidDynamic::setRigidDynamicLockFlags() not allowed while simulation is running. Call will be ignored.") scSetLockFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, rigidDynamicLockFlags, static_cast<PxRigidDynamic&>(*this), flags); // @@@ } void NpRigidDynamic::setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxRigidDynamic::setRigidDynamicLockFlag() not allowed while simulation is running. Call will be ignored.") PxRigidDynamicLockFlags flags = mCore.getRigidDynamicLockFlags(); if (value) flags = flags | flag; else flags = flags & (~flag); scSetLockFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, rigidDynamicLockFlags, static_cast<PxRigidDynamic&>(*this), flags); // @@@ }
25,543
C++
41.502496
183
0.763379
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPBDMaterial.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 "NpPBDMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX using namespace physx; using namespace Cm; NpPBDMaterial::NpPBDMaterial(const PxsPBDMaterialCore& desc) : PxPBDMaterial(PxConcreteType::ePBD_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpPBDMaterial::~NpPBDMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpPBDMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: missing line here? } void NpPBDMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releasePBDMaterialToPool(*this); } else this->~NpPBDMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpPBDMaterial* NpPBDMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpPBDMaterial* obj = PX_PLACEMENT_NEW(address, NpPBDMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpPBDMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpPBDMaterial::release() { RefCountable_decRefCount(*this); } void NpPBDMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpPBDMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpPBDMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setFriction: invalid float"); mMaterial.friction = x; updateMaterial(); } PxReal NpPBDMaterial::getFriction() const { return mMaterial.friction; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setViscosity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setViscosity: invalid float"); mMaterial.viscosity = x; updateMaterial(); } PxReal NpPBDMaterial::getViscosity() const { return mMaterial.viscosity; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpPBDMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setLift(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setLift: invalid float"); mMaterial.lift = x; updateMaterial(); } PxReal NpPBDMaterial::getLift() const { return mMaterial.lift; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setDrag(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setDrag: invalid float"); mMaterial.drag = x; updateMaterial(); } PxReal NpPBDMaterial::getDrag() const { return mMaterial.drag; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setCFLCoefficient(PxReal x) { PX_CHECK_AND_RETURN(x >= 1.f, "PxPBDMaterial::setCFLCoefficient: invalid float"); mMaterial.cflCoefficient = x; updateMaterial(); } PxReal NpPBDMaterial::getCFLCoefficient() const { return mMaterial.cflCoefficient; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setVorticityConfinement(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setVorticityConfinement: invalid float"); mMaterial.vorticityConfinement = x; updateMaterial(); } PxReal NpPBDMaterial::getVorticityConfinement() const { return mMaterial.vorticityConfinement; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setSurfaceTension(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setSurfaceTension: invalid float"); mMaterial.surfaceTension = x; updateMaterial(); } PxReal NpPBDMaterial::getSurfaceTension() const { return mMaterial.surfaceTension; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setCohesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setCohesion: invalid float"); mMaterial.cohesion = x; updateMaterial(); } PxReal NpPBDMaterial::getCohesion() const { return mMaterial.cohesion; } ////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setAdhesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.adhesion = x; updateMaterial(); } PxReal NpPBDMaterial::getAdhesion() const { return mMaterial.adhesion; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setGravityScale(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.gravityScale = x; updateMaterial(); } PxReal NpPBDMaterial::getGravityScale() const { return mMaterial.gravityScale; } ////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setAdhesionRadiusScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setAdhesionRadiusScale: invalid float"); mMaterial.adhesionRadiusScale = x; updateMaterial(); } PxReal NpPBDMaterial::getAdhesionRadiusScale() const { return mMaterial.adhesionRadiusScale; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setParticleFrictionScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setParticleFrictionScale: invalid float"); mMaterial.particleFrictionScale = x; updateMaterial(); } PxReal NpPBDMaterial::getParticleFrictionScale() const { return mMaterial.particleFrictionScale; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setParticleAdhesionScale(PxReal adhesionScale) { PX_CHECK_AND_RETURN(adhesionScale >= 0.f, "PxPBDMaterial::setParticleAdhesionScale: adhesion value must be >= 0"); mMaterial.particleAdhesionScale = adhesionScale; updateMaterial(); } PxReal NpPBDMaterial::getParticleAdhesionScale() const { return mMaterial.particleAdhesionScale; } /////////////////////////////////////////////////////////////////////////////// #endif
8,691
C++
25.419453
115
0.655276
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSoftBody.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_SOFTBODY_H #define NP_SOFTBODY_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxSoftBody.h" #include "ScSoftBodyCore.h" #include "NpActorTemplate.h" #include "GuTetrahedronMesh.h" namespace physx { class NpScene; class NpShape; class NpSoftBody : public NpActorTemplate<PxSoftBody> { public: NpSoftBody(PxCudaContextManager& cudaContextManager); NpSoftBody(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager); virtual ~NpSoftBody() {} void exportData(PxSerializationContext& /*context*/) const{} //external API virtual PxActorType::Enum getType() const { return PxActorType::eSOFTBODY; } virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const; virtual PxU32 getGpuSoftBodyIndex(); virtual void setSoftBodyFlag(PxSoftBodyFlag::Enum flag, bool val); virtual void setSoftBodyFlags(PxSoftBodyFlags flags); virtual PxSoftBodyFlags getSoftBodyFlag() const; virtual void setParameter(PxFEMParameters paramters); virtual PxFEMParameters getParameter() const; virtual PxVec4* getPositionInvMassBufferD(); virtual PxVec4* getRestPositionBufferD(); virtual PxVec4* getSimPositionInvMassBufferD(); virtual PxVec4* getSimVelocityBufferD(); virtual void markDirty(PxSoftBodyDataFlags flags); virtual void setKinematicTargetBufferD(const PxVec4* positions, PxSoftBodyFlags flags); virtual PxCudaContextManager* getCudaContextManager() const; virtual void setWakeCounter(PxReal wakeCounterValue); virtual PxReal getWakeCounter() const; virtual bool isSleeping() const; virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters); virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const; virtual PxShape* getShape(); virtual PxTetrahedronMesh* getCollisionMesh(); virtual const PxTetrahedronMesh* getCollisionMesh() const; virtual PxTetrahedronMesh* getSimulationMesh() { return mSimulationMesh; } virtual const PxTetrahedronMesh* getSimulationMesh() const { return mSimulationMesh; } virtual PxSoftBodyAuxData* getSoftBodyAuxData() { return mSoftBodyAuxData; } virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const { return mSoftBodyAuxData; } virtual bool attachShape(PxShape& shape); virtual bool attachSimulationMesh(PxTetrahedronMesh& simulationMesh, PxSoftBodyAuxData& softBodyAuxData); virtual void detachShape(); virtual void detachSimulationMesh(); virtual void release(); PX_FORCE_INLINE const Sc::SoftBodyCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::SoftBodyCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpSoftBody, mCore); } virtual void addParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId); virtual void removeParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId); virtual PxU32 addParticleAttachment(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId, const PxVec4& barycentric); virtual void removeParticleAttachment(PxPBDParticleSystem* particlesystem, PxU32 handle); virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle); virtual void addTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx); virtual void removeTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx); virtual PxU32 addTetRigidAttachment(PxRigidActor* actor, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void addSoftBodyFilter(PxSoftBody* softbody0, PxU32 tetIdx0, PxU32 tetIdx1); virtual void removeSoftBodyFilter(PxSoftBody* softbody0, PxU32 tetIdx0, PxU32 tetIdx1); virtual void addSoftBodyFilters(PxSoftBody* softbody0, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); virtual void removeSoftBodyFilters(PxSoftBody* softbody0, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); virtual PxU32 addSoftBodyAttachment(PxSoftBody* softbody0, PxU32 tetIdx0, const PxVec4& tetBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset); virtual void removeSoftBodyAttachment(PxSoftBody* softbody0, PxU32 handle); virtual void addClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx); virtual void removeClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx); virtual void addVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx); virtual void removeVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx); virtual PxU32 addClothAttachment(PxFEMCloth* cloth, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset); virtual void removeClothAttachment(PxFEMCloth* cloth, PxU32 handle); // Debug name void setName(const char*); const char* getName() const; void updateMaterials(); private: NpShape* mShape; //soft body should just have one shape. The geometry type should be tetrahedron mesh Gu::TetrahedronMesh* mSimulationMesh; Gu::SoftBodyAuxData* mSoftBodyAuxData; Sc::SoftBodyCore mCore; PxCudaContextManager* mCudaContextManager; }; } #endif #endif
7,805
C
47.185185
169
0.747598
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdMetaDataPvdBinding.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 PVD_META_DATA_PVD_BINDING_H #define PVD_META_DATA_PVD_BINDING_H #if PX_SUPPORT_PVD #include "PxPhysXConfig.h" #include "foundation/PxArray.h" namespace physx { namespace pvdsdk { class PsPvd; class PvdDataStream; struct PvdMetaDataBindingData; } } namespace physx { namespace Sc { struct Contact; } namespace Vd { using namespace physx::pvdsdk; class PvdVisualizer { protected: virtual ~PvdVisualizer() { } public: virtual void visualize(PxArticulationLink& link) = 0; }; class PvdMetaDataBinding { PvdMetaDataBindingData* mBindingData; public: PvdMetaDataBinding(); ~PvdMetaDataBinding(); void registerSDKProperties(PvdDataStream& inStream); void sendAllProperties(PvdDataStream& inStream, const PxPhysics& inPhysics); void sendAllProperties(PvdDataStream& inStream, const PxScene& inScene); // per frame update void sendBeginFrame(PvdDataStream& inStream, const PxScene* inScene, PxReal simulateElapsedTime); void sendContacts(PvdDataStream& inStream, const PxScene& inScene, PxArray<Sc::Contact>& inContacts); void sendContacts(PvdDataStream& inStream, const PxScene& inScene); void sendStats(PvdDataStream& inStream, const PxScene* inScene); void sendSceneQueries(PvdDataStream& inStream, const PxScene& inScene, PsPvd* pvd); void sendEndFrame(PvdDataStream& inStream, const PxScene* inScene); void createInstance(PvdDataStream& inStream, const PxMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial, const PxPhysics& ownerPhysics); // jcarius: Commented-out until FEMCloth is not under construction anymore // void createInstance(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial, const PxPhysics& ownerPhysics); // void sendAllProperties(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial); // void destroyInstance(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxPBDMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxPBDMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxPBDMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxFLIPMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxFLIPMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxFLIPMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxMPMMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxMPMMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxMPMMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxHeightField& inData, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxHeightField& inData); void destroyInstance(PvdDataStream& inStream, const PxHeightField& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxConvexMesh& inData, const PxPhysics& ownerPhysics); void destroyInstance(PvdDataStream& inStream, const PxConvexMesh& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxTetrahedronMesh& inData, const PxPhysics& ownerPhysics); void destroyInstance(PvdDataStream& inStream, const PxTetrahedronMesh& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxTriangleMesh& inData, const PxPhysics& ownerPhysics); void destroyInstance(PvdDataStream& inStream, const PxTriangleMesh& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxRigidStatic& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxRigidStatic& inObj); void destroyInstance(PvdDataStream& inStream, const PxRigidStatic& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxRigidDynamic& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxRigidDynamic& inObj); void destroyInstance(PvdDataStream& inStream, const PxRigidDynamic& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxSoftBody& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxSoftBody& inObj); void destroyInstance(PvdDataStream& inStream, const PxSoftBody& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxFEMCloth& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxFEMCloth& inObj); void destroyInstance(PvdDataStream& inStream, const PxFEMCloth& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxPBDParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxPBDParticleSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxPBDParticleSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxMPMParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxMPMParticleSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxMPMParticleSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxHairSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxHairSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxHairSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj); void destroyInstance(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxArticulationLink& inObj, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxArticulationLink& inObj); void destroyInstance(PvdDataStream& inStream, const PxArticulationLink& inObj); void createInstance(PvdDataStream& inStream, const PxShape& inObj, const PxRigidActor& owner, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxShape& inObj); void releaseAndRecreateGeometry(PvdDataStream& inStream, const PxShape& inObj, PxPhysics& ownerPhysics, PsPvd* pvd); void updateMaterials(PvdDataStream& inStream, const PxShape& inObj, PsPvd* pvd); void destroyInstance(PvdDataStream& inStream, const PxShape& inObj, const PxRigidActor& owner); // These are created as part of the articulation link's creation process, so outside entities don't need to // create them. void sendAllProperties(PvdDataStream& inStream, const PxArticulationJointReducedCoordinate& inObj); // per frame update void updateDynamicActorsAndArticulations(PvdDataStream& inStream, const PxScene* inScene, PvdVisualizer* linkJointViz); // Origin Shift void originShift(PvdDataStream& inStream, const PxScene* inScene, PxVec3 shift); void createInstance(PvdDataStream& inStream, const PxAggregate& inObj, const PxScene& ownerScene); void sendAllProperties(PvdDataStream& inStream, const PxAggregate& inObj); void destroyInstance(PvdDataStream& inStream, const PxAggregate& inObj, const PxScene& ownerScene); void detachAggregateActor(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor); void attachAggregateActor(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor); template <typename TDataType> void registrarPhysicsObject(PvdDataStream&, const TDataType&, PsPvd*); }; } } #endif #endif
10,880
C
53.405
162
0.809375
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpHairSystem.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "NpHairSystem.h" #include "NpCheck.h" #include "NpScene.h" #include "ScHairSystemSim.h" #include "NpFactory.h" #include "NpRigidDynamic.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationLink.h" #include "ScBodyCore.h" #include "ScBodySim.h" #include "geometry/PxHairSystemDesc.h" #include "PxsMemoryManager.h" #include "NpSoftBody.h" #include "PxPhysXGpu.h" #include "PxvGlobals.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #include "GuTetrahedronMeshUtils.h" using namespace physx; namespace physx { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpHairSystem::NpHairSystem(PxCudaContextManager& cudaContextManager) : NpActorTemplate(PxConcreteType::eHAIR_SYSTEM, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, NpType::eHAIRSYSTEM), mCudaContextManager(&cudaContextManager), mMemoryManager(NULL), mHostMemoryAllocator(NULL), mDeviceMemoryAllocator(NULL) { init(); } NpHairSystem::NpHairSystem(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager) : NpActorTemplate(baseFlags), mCudaContextManager(&cudaContextManager), mMemoryManager(NULL), mHostMemoryAllocator(NULL), mDeviceMemoryAllocator(NULL) { init(); } NpHairSystem::~NpHairSystem() { releaseAllocator(); } void NpHairSystem::init() { mCore.getShapeCore().createBuffers(mCudaContextManager); createAllocator(); mSoftbodyAttachments.getAllocator().setCallback(mHostMemoryAllocator); } void NpHairSystem::releaseAllocator() { // destroy internal buffers if they exist before destroying allocators if(mStrandPastEndIndicesInternal.size() > 0) mStrandPastEndIndicesInternal.reset(); if (mPosInvMassInternal.size() > 0) mPosInvMassInternal.reset(); if (mVelInternal.size() > 0) mVelInternal.reset(); if (mParticleRigidAttachmentsInternal.size() > 0) mParticleRigidAttachmentsInternal.reset(); if (mRestPositionsInternal.size() > 0) mRestPositionsInternal.reset(); mSoftbodyAttachments.reset(); if (mMemoryManager != NULL) { mMemoryManager->~PxsMemoryManager(); mHostMemoryAllocator = NULL; // released by memory manager mDeviceMemoryAllocator = NULL; // released by memory manager PX_FREE(mMemoryManager); } } PxBounds3 NpHairSystem::getWorldBounds(float inflation) const { NP_READ_CHECK(getNpScene()); if (!getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Querying bounds of a PxHairSystem which is not part of a PxScene is not supported."); return PxBounds3::empty(); } const Sc::HairSystemSim* sim = mCore.getSim(); PX_ASSERT(sim); PX_SIMD_GUARD; PxBounds3 bounds = sim->getBounds(); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpHairSystem::visualize(PxRenderOutput& out, NpScene& scene) const { if(!(mCore.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; const Sc::Scene& scScene = scene.getScScene(); const bool visualizeAABBs = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AABBS) != 0.0f; if(visualizeAABBs) { out << PxU32(PxDebugColor::eARGB_YELLOW) << PxMat44(PxIdentity); Cm::renderOutputDebugBox(out, mCore.getSim()->getBounds()); } } #endif void NpHairSystem::setHairSystemFlag(PxHairSystemFlag::Enum flag, bool val) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setHairSystemFlag() not allowed while simulation is running. Call will be ignored."); PxHairSystemFlags flags = mCore.getFlags(); if (val) { flags.raise(flag); } else { flags.clear(flag); } mCore.setFlags(flags); mCore.getShapeCore().getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setReadRequestFlag(PxHairSystemData::Enum flag, bool val) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setReadRequestFlag() not allowed while simulation is running. Call will be ignored."); if (val) { mCore.getShapeCore().getLLCore().mReadRequests.raise(flag); } else { mCore.getShapeCore().getLLCore().mReadRequests.clear(flag); } } void NpHairSystem::setReadRequestFlags(PxHairSystemDataFlags flags) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setReadRequestFlag() not allowed while simulation is running. Call will be ignored."); mCore.getShapeCore().getLLCore().mReadRequests = flags; } PxHairSystemDataFlags NpHairSystem::getReadRequestFlags() const { NP_READ_CHECK(getNpScene()); return mCore.getShapeCore().getLLCore().mReadRequests; } void NpHairSystem::setPositionsInvMass(PxVec4* vertexPositionsInvMass, const PxBounds3& bounds) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(vertexPositionsInvMass != NULL, "PxHairSystem::setPositionsInvMass vertexPositionsInvMass must not be NULL.") PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexPositionsInvMass) & 15), "PxHairSystem::setPositionsInvMass vertexPositionInvMass not aligned to 16 bytes"); PX_CHECK_AND_RETURN(!bounds.isEmpty(), "PxHairSystem::setPositionsInvMass bounds must not be empty"); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mNumVertices > 0, "PxHairSystem::setPositionsInvMass numVertices must be greater than zero. Use setTopology().") PX_CHECK_AND_RETURN(llCore.mNumStrands > 0, "PxHairSystem::setPositionsInvMass numStrands must be greater than zero. Use setTopology().") PX_CHECK_AND_RETURN(llCore.mStrandPastEndIndices != NULL, "PxHairSystem::setPositionsInvMass StrandPastEndIndices are not set. Use setTopology().") setLlGridSize(bounds); llCore.mPositionInvMass = vertexPositionsInvMass; // release internal buffers if they're not needed anymore if (vertexPositionsInvMass != mPosInvMassInternal.begin()) mPosInvMassInternal.reset(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePOSITIONS_VELOCITIES_MASS | Dy::HairSystemDirtyFlag::eGRID_SIZE; } void NpHairSystem::setVelocities(PxVec4* vertexVelocities) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(vertexVelocities != NULL, "PxHairSystem::setVelocities vertexVelocities must not be NULL.") PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexVelocities) & 15), "PxHairSystem::setVelocities vertexVelocities not aligned to 16 bytes"); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mNumVertices > 0, "PxHairSystem::setPositionsInvMass numVertices must be greater than zero. Use setTopology().") // release internal buffers if they're not needed anymore if (vertexVelocities != mVelInternal.begin()) mVelInternal.reset(); llCore.mVelocity = vertexVelocities; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePOSITIONS_VELOCITIES_MASS; } void NpHairSystem::setBendingRestAngles(const PxReal* bendingRestAngles, PxReal bendingCompliance) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(bendingRestAngles || llCore.mRestPositionsD, "PxHairSystem::setBendingRestAngles() NULL bendingRestAngles only allowed if restPositions have been set."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setBendingRestAngles() not allowed while simulation is running. Call will be ignored."); llCore.mBendingRestAngles = bendingRestAngles; llCore.mParams.mBendingCompliance = bendingCompliance; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eBENDING_REST_ANGLES | Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setTwistingCompliance(PxReal twistingCompliance) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setTwistingCompliance() not allowed while simulation is running. Call will be ignored.") Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mTwistingCompliance = twistingCompliance; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::getTwistingRestPositions(PxReal* buffer) { NP_READ_CHECK(getNpScene()); PxScopedCudaLock lock(*mCudaContextManager); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); mCudaContextManager->getCudaContext()->memcpyDtoH(buffer, reinterpret_cast<CUdeviceptr>(llCore.mTwistingRestPositionsGpuSim), sizeof(float) * llCore.mNumVertices); } void NpHairSystem::setWakeCounter(PxReal wakeCounterValue) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setWakeCounter() not allowed while simulation is running. Call will be ignored.") mCore.setWakeCounter(wakeCounterValue); mCore.getShapeCore().getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getWakeCounter() const { NP_READ_CHECK(getNpScene()); return mCore.getWakeCounter(); } bool NpHairSystem::isSleeping() const { NP_READ_CHECK(getNpScene()); return mCore.isSleeping(); } void NpHairSystem::setSolverIterationCounts(PxU32 iters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(iters > 0, "PxHairSystem::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(iters <= 255, "PxHairSystem::setSolverIterationCounts: positionIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") mCore.setSolverIterationCounts(static_cast<PxU16>(iters)); } PxU32 NpHairSystem::getSolverIterationCounts() const { NP_READ_CHECK(getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); return x; } void NpHairSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); if (npScene) { npScene->scRemoveHairSystem(*this); npScene->removeFromHairSystemList(*this); } // detachShape(); PX_ASSERT(!isAPIWriteForbidden()); mCore.getShapeCore().releaseBuffers(); releaseAllocator(); NpDestroyHairSystem(this); } void NpHairSystem::addRigidAttachment(const PxRigidBody& rigidBody) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "PxHairSystem::addRigidAttachment: Hair system must be inserted into the scene."); PX_CHECK_AND_RETURN(rigidBody.getScene() != NULL, "PxHairSystem::addRigidAttachment: Actor not part of a scene."); PX_CHECK_AND_RETURN(getScene() == rigidBody.getScene(), "PxHairSystem::addRigidAttachment: Actor and hair must be part of the same scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::addRigidAttachment: Illegal to call while simulation is running."); const Sc::BodyCore* attachmentBodyCore = getBodyCore(&rigidBody); PX_CHECK_AND_RETURN(attachmentBodyCore != NULL, "PxHairSystem::addRigidAttachment: Attachment body must be rigid dynamic or articulation link."); if(attachmentBodyCore != NULL) { const Sc::BodySim* bodySim = attachmentBodyCore->getSim(); if(bodySim) mCore.addAttachment(*bodySim); } } void NpHairSystem::removeRigidAttachment(const PxRigidBody& rigidBody) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "PxHairSystem::removeRigidAttachment: Hair system must be inserted into the scene."); PX_CHECK_AND_RETURN(rigidBody.getScene() != NULL, "PxHairSystem::removeRigidAttachment: Actor not part of a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::removeRigidAttachment: Illegal to call while simulation is running."); const Sc::BodyCore* attachmentBodyCore = getBodyCore(&rigidBody); if(attachmentBodyCore != NULL) { const Sc::BodySim* bodySim = attachmentBodyCore->getSim(); if(bodySim) mCore.removeAttachment(*bodySim); } } void NpHairSystem::setRigidAttachments(PxParticleRigidAttachment* attachments, PxU32 numAttachments, bool isGpuPtr) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "PxHairSystem::setRigidAttachments: Hair system must be inserted into the scene."); PX_CHECK_AND_RETURN(attachments != NULL || numAttachments == 0, "PxHairSystem::setRigidAttachments: attachments must not be NULL if numAttachments > 0."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::setRigidAttachments: Illegal to call while simulation is running."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mNumRigidAttachments = numAttachments; if(!isGpuPtr) { // create fresh buffer mParticleRigidAttachmentsInternal.reset(); mParticleRigidAttachmentsInternal.setAllocatorCallback(mDeviceMemoryAllocator); mParticleRigidAttachmentsInternal.allocate(numAttachments); llCore.mRigidAttachments = mParticleRigidAttachmentsInternal.begin(); // copy H2D PxScopedCudaLock lock(*mCudaContextManager); PxCUresult result = mCudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(llCore.mRigidAttachments), attachments, sizeof(PxParticleRigidAttachment) * numAttachments); PX_ASSERT(result == 0); PX_UNUSED(result); } else if (mParticleRigidAttachmentsInternal.begin() != attachments) { mParticleRigidAttachmentsInternal.reset(); llCore.mRigidAttachments = attachments; } // Don't clear mParticleRigidAttachmentsInternal if isGpuPtr==true and user has passed in the same pointer again llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eRIGID_ATTACHMENTS; } PxParticleRigidAttachment* NpHairSystem::getRigidAttachmentsGpu(PxU32* numAttachments) { NP_READ_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); if(numAttachments) *numAttachments = llCore.mNumRigidAttachments; return llCore.mRigidAttachments; } PxU32 NpHairSystem::addSoftbodyAttachment(const PxSoftBody& softbody, const PxU32* tetIds, const PxVec4* tetmeshBarycentrics, const PxU32* hairVertices, PxConeLimitedConstraint* constraints, PxReal* constraintOffsets, PxU32 numAttachments) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxHairSystem::addSoftbodyAttachment: Illegal to call while simulation is running.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(tetIds != NULL, "PxHairSystem::addSoftbodyAttachment: tetIds must not be null.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(tetmeshBarycentrics != NULL, "PxHairSystem::addSoftbodyAttachment: tetmeshBarycentrics must not be null.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(hairVertices != NULL, "PxHairSystem::addSoftbodyAttachment: hairVertices must not be null.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(softbody.getScene() != NULL, "PxHairSystem::addSoftbodyAttachment: Softbody must be inserted into the scene.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(getScene() == softbody.getScene(), "PxHairSystem::addSoftbodyAttachment: Softbody and hair must be part of the same scene.", 0xffFFffFF); if(numAttachments == 0) return 0xffFFffFF; Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); const NpSoftBody& npSoftbody = static_cast<const NpSoftBody&>(softbody); const PxU32 softbodyIdx = npSoftbody.getCore().getGpuSoftBodyIndex(); const PxTetrahedronMesh* simMesh = softbody.getSimulationMesh(); PX_CHECK_AND_RETURN_VAL(NULL != simMesh, "PxHairSystem::addSoftbodyAttachment: The softbody doesn't have a valid simulation mesh.", 0xffFFffFF); const PxSoftBodyAuxData* auxData = softbody.getSoftBodyAuxData(); PX_CHECK_AND_RETURN_VAL(auxData->getConcreteType() == PxConcreteType::eSOFT_BODY_STATE, "PxHairSystem::addSoftbodyAttachment: The softbodies aux data must be of type Gu::SoftBodyAuxData.", 0xffFFffFF); const Gu::SoftBodyAuxData* guAuxData = static_cast<const Gu::SoftBodyAuxData*>(auxData); // Gu::BVTetrahedronMesh does not have a concrete type const PxTetrahedronMesh* collisionMesh = softbody.getCollisionMesh(); const Gu::BVTetrahedronMesh* bvCollisionMesh = static_cast<const Gu::BVTetrahedronMesh*>(collisionMesh); // assign handle by finding the first nonexistent key in the hashmap PxU32 handle = PX_MAX_U32; for(PxU32 i = 0; i < PX_MAX_U32; i++) { if(mSoftbodyAttachmentsOffsets.find(i) == NULL) { handle = i; break; } } PX_ASSERT(handle != PX_MAX_U32); // new attachments will be added to the end of the contiguous array mSoftbodyAttachmentsOffsets[handle] = PxPair<PxU32, PxU32>(mSoftbodyAttachments.size(), numAttachments); mSoftbodyAttachments.reserve(mSoftbodyAttachments.size() + numAttachments); for(PxU32 i=0; i<numAttachments; i++) { // convert to sim mesh tets/barycentrics PxU32 simTetId; PxVec4 simBarycentric; Gu::convertSoftbodyCollisionToSimMeshTets(*simMesh, *guAuxData, *bvCollisionMesh, tetIds[i], tetmeshBarycentrics[i], simTetId, simBarycentric); Dy::SoftbodyHairAttachment attachment; attachment.hairVtxIdx = hairVertices[i]; attachment.softbodyNodeIdx = softbodyIdx; attachment.tetBarycentric = simBarycentric; attachment.tetId = simTetId; if(constraints) { const PxConeLimitedConstraint* constraint = constraints + i; attachment.constraintOffset = constraintOffsets ? constraintOffsets[i] : 0.0f; attachment.low_high_angle = PxVec4(constraint->mLowLimit, constraint->mHighLimit, constraint->mAngle, 0.f); if(constraint->mAngle >= 0.f) { attachment.attachmentBarycentric = Gu::addAxisToSimMeshBarycentric(*simMesh, simTetId, simBarycentric, constraint->mAxis.getNormalized()); } else { attachment.attachmentBarycentric = PxVec4(0.f, 0.f, 0.f, 0.f); } } else { attachment.low_high_angle = PxVec4(-1.f, -1.f, -1.f, 0.f); attachment.attachmentBarycentric = PxVec4(0.f, 0.f, 0.f, 0.f); } mSoftbodyAttachments.pushBack(attachment); } mCore.addAttachment(*npSoftbody.getCore().getSim()); // add edge for island generation llCore.mSoftbodyAttachments = mSoftbodyAttachments.begin(); llCore.mNumSoftbodyAttachments = mSoftbodyAttachments.size(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eSOFTBODY_ATTACHMENTS; return handle; } void NpHairSystem::removeSoftbodyAttachment(const PxSoftBody& softbody, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::removeSoftbodyAttachment: Illegal to call while simulation is running."); PX_CHECK_AND_RETURN(softbody.getScene() != NULL, "PxHairSystem::removeSoftbodyAttachment: Softbody must still be inserted into the scene."); const PxPair<const PxU32, PxPair<PxU32, PxU32>>* handleOffsetSize = mSoftbodyAttachmentsOffsets.find(handle); PX_ASSERT(handleOffsetSize != NULL); if(handleOffsetSize == NULL) return; PX_ASSERT(handle == handleOffsetSize->first); const PxU32 offset = handleOffsetSize->second.first; const PxU32 numRemoved = handleOffsetSize->second.second; const PxU32 totSize = mSoftbodyAttachments.size(); // shift all subsequent elements in the attachment array to the left for(PxU32 i=offset; i + numRemoved < totSize; i++) { mSoftbodyAttachments[i] = mSoftbodyAttachments[i+numRemoved]; } mSoftbodyAttachments.resize(mSoftbodyAttachments.size() - numRemoved); // correct all offsets of the still existing attachments and delete the current handle mSoftbodyAttachmentsOffsets.erase(handle); for(PxHashMap<PxU32, PxPair<PxU32, PxU32>>::Iterator it = mSoftbodyAttachmentsOffsets.getIterator(); !it.done(); it++) { if(it->second.first > offset) it->second.first -= numRemoved; } const NpSoftBody& npSoftbody = static_cast<const NpSoftBody&>(softbody); mCore.removeAttachment(*npSoftbody.getCore().getSim()); // remove edge for island generation Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mSoftbodyAttachments = mSoftbodyAttachments.begin(); llCore.mNumSoftbodyAttachments = mSoftbodyAttachments.size(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eSOFTBODY_ATTACHMENTS; } void NpHairSystem::setRestPositions(PxVec4* restPos, bool isGpuPtr) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::setRestPositions: Illegal to call while simulation is running."); if(restPos == NULL) isGpuPtr = false; Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); if(!isGpuPtr) { // create fresh buffer mRestPositionsInternal.reset(); mRestPositionsInternal.setAllocatorCallback(mDeviceMemoryAllocator); mRestPositionsInternal.allocate(llCore.mNumVertices); llCore.mRestPositionsD = mRestPositionsInternal.begin(); // use user-provided restPos if available, otherwise current positions mCudaContextManager->copyHToD<PxVec4>(llCore.mRestPositionsD, restPos ? restPos : llCore.mPositionInvMass, llCore.mNumVertices); } else if (mRestPositionsInternal.begin() != restPos) { mRestPositionsInternal.reset(); llCore.mRestPositionsD = restPos; } // Don't clear mRestPositionsInternal if isGpuPtr==true and user has passed in the same pointer again llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eREST_POSITIONS; } PxVec4* NpHairSystem::getRestPositionsGpu() { NP_READ_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mRestPositionsD; } void NpHairSystem::setLlGridSize(const PxBounds3& bounds) { // give system some space to expand: create a grid to accomodate at least 1.5 times the initial size Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); const PxVec3 dimensions = bounds.getDimensions(); const PxReal maxXZ = PxMax(dimensions.x, dimensions.z); // rotations in plane perpendicular to gravity are very likely const PxReal cellSize = llCore.mParams.getCellSize(); const PxU32 tightGridSizeXZ = static_cast<PxU32>(maxXZ / cellSize) + 1; const PxU32 tightGridSizeY = static_cast<PxU32>(dimensions.y / cellSize) + 1; PxU32 gridSizeXZ = PxNextPowerOfTwo(tightGridSizeXZ); PxU32 gridSizeY = PxNextPowerOfTwo(tightGridSizeY); if(gridSizeXZ < 1.5f * tightGridSizeXZ) gridSizeXZ *= 2; if(gridSizeY < 1.5f * tightGridSizeY) gridSizeY *= 2; llCore.mParams.mGridSize[0] = gridSizeXZ; llCore.mParams.mGridSize[1] = gridSizeY; llCore.mParams.mGridSize[2] = llCore.mParams.mGridSize[0]; if (static_cast<PxU32>(dimensions.maxElement() / cellSize) > 512) PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL, "Grid of hair system appears very large (%i by %i by %i). Double check ratio of segment" " length (%f) to extent of the hair system defined by the vertices (%f, %f, %f).", llCore.mParams.mGridSize[0], llCore.mParams.mGridSize[1], llCore.mParams.mGridSize[2], static_cast<double>(llCore.mParams.mSegmentLength), static_cast<double>(dimensions.x), static_cast<double>(dimensions.y), static_cast<double>(dimensions.z)); } void NpHairSystem::createAllocator() { if (!mMemoryManager) { PxPhysXGpu* physXGpu = PxvGetPhysXGpu(true); PX_ASSERT(physXGpu != NULL); mMemoryManager = physXGpu->createGpuMemoryManager(mCudaContextManager); mHostMemoryAllocator = mMemoryManager->getHostMemoryAllocator(); mDeviceMemoryAllocator = mMemoryManager->getDeviceMemoryAllocator(); } PX_ASSERT(mMemoryManager != NULL); PX_ASSERT(mHostMemoryAllocator != NULL); PX_ASSERT(mDeviceMemoryAllocator != NULL); } void NpHairSystem::initFromDesc(const PxHairSystemDesc& desc) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(desc.isValid(), "PxHairSystem::initFromDesc desc is not valid."); PX_ASSERT(mCudaContextManager != NULL); // destroy internal buffers if they exist because we might switch allocators if(mStrandPastEndIndicesInternal.size() > 0) mStrandPastEndIndicesInternal.reset(); if (mPosInvMassInternal.size() > 0) mPosInvMassInternal.reset(); if (mVelInternal.size() > 0) mVelInternal.reset(); // create internal buffers if (desc.flags.isSet(PxHairSystemDescFlag::eDEVICE_MEMORY)) { mPosInvMassInternal.setAllocatorCallback(mDeviceMemoryAllocator); mVelInternal.setAllocatorCallback(mDeviceMemoryAllocator); mStrandPastEndIndicesInternal.setAllocatorCallback(mDeviceMemoryAllocator); } else { mPosInvMassInternal.setAllocatorCallback(mHostMemoryAllocator); mVelInternal.setAllocatorCallback(mHostMemoryAllocator); mStrandPastEndIndicesInternal.setAllocatorCallback(mHostMemoryAllocator); } PxScopedCudaLock lock(*mCudaContextManager); // StrandPastEndIndices MemoryWithAlloc<PxU32> strandPastEndIndicesLocal; strandPastEndIndicesLocal.setAllocatorCallback(mHostMemoryAllocator); strandPastEndIndicesLocal.allocate(desc.numStrands); const PxU32* hostStrandPastEndIndices = strandPastEndIndicesLocal.begin(); PxU32 numVertices = 0; for (PxU32 strandIdx = 0; strandIdx < desc.numStrands; strandIdx++) { PxU32 strandLength = desc.numVerticesPerStrand.at<PxU32>(strandIdx); numVertices += strandLength; strandPastEndIndicesLocal[strandIdx] = numVertices; } if (desc.flags.isSet(PxHairSystemDescFlag::eDEVICE_MEMORY)) { mStrandPastEndIndicesInternal.allocate(desc.numStrands); mCudaContextManager->getCudaContext()->memcpyHtoD( reinterpret_cast<CUdeviceptr>(mStrandPastEndIndicesInternal.begin()), strandPastEndIndicesLocal.begin(), desc.numStrands * sizeof(PxU32)); } else { strandPastEndIndicesLocal.swap(mStrandPastEndIndicesInternal); } // positions, velocities const bool onlyRootPositionsGiven = desc.numStrands == desc.vertices.count; const bool velocitiesGiven = desc.velocities.count > 0; MemoryWithAlloc<PxVec4> posInvMassLocal, velLocal; posInvMassLocal.setAllocatorCallback(mHostMemoryAllocator); posInvMassLocal.allocate(numVertices); velLocal.setAllocatorCallback(mHostMemoryAllocator); velLocal.allocate(numVertices); PxBounds3 bounds = PxBounds3::empty(); PxU32 overallVertexIdx = 0; for (PxU32 strandIdx = 0; strandIdx < desc.numStrands; strandIdx++) { for (; overallVertexIdx < hostStrandPastEndIndices[strandIdx]; overallVertexIdx++) { const PxU32 inputVertexIdx = onlyRootPositionsGiven ? strandIdx : overallVertexIdx; posInvMassLocal[overallVertexIdx] = desc.vertices.at<PxVec4>(inputVertexIdx); velLocal[overallVertexIdx] = velocitiesGiven ? desc.velocities.at<PxVec4>(overallVertexIdx) : PxVec4(PxZero); bounds.include(desc.vertices.at<PxVec4>(inputVertexIdx).getXYZ()); } } PX_ASSERT(overallVertexIdx == numVertices); if (desc.flags.isSet(PxHairSystemDescFlag::eDEVICE_MEMORY)) { mPosInvMassInternal.allocate(numVertices); mVelInternal.allocate(numVertices); mCudaContextManager->getCudaContext()->memcpyHtoD( reinterpret_cast<CUdeviceptr>(mPosInvMassInternal.begin()), posInvMassLocal.begin(), numVertices * sizeof(PxVec4)); mCudaContextManager->getCudaContext()->memcpyHtoD( reinterpret_cast<CUdeviceptr>(mVelInternal.begin()), velLocal.begin(), numVertices * sizeof(PxVec4)); } else { posInvMassLocal.swap(mPosInvMassInternal); velLocal.swap(mVelInternal); } setTopology(mPosInvMassInternal.begin(), mVelInternal.begin(), mStrandPastEndIndicesInternal.begin(), desc.segmentLength, desc.segmentRadius, numVertices, desc.numStrands, bounds); } void NpHairSystem::setTopology(PxVec4* vertexPositionsInvMass, PxVec4* vertexVelocities, const PxU32* strandPastEndIndices, PxReal segmentLength, PxReal segmentRadius, PxU32 numVertices, PxU32 numStrands, const PxBounds3& bounds) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(numVertices > 0, "PxHairSystem::setTopology numVertices must be greater than zero"); PX_CHECK_AND_RETURN(numStrands > 0, "PxHairSystem::setTopology numStrands must be greater than zero"); PX_CHECK_AND_RETURN(segmentLength > 0.0f, "PxHairSystem::setTopology segmentLength must be greater than zero"); PX_CHECK_AND_RETURN(segmentRadius > 0.0f, "PxHairSystem::setTopology segmentRadius must be greater than zero"); PX_CHECK_AND_RETURN(2.0f * segmentRadius < segmentLength, "PxHairSystem::setTopology segmentRadius must be smaller than half of segmentLength. Call ignored"); PX_CHECK_AND_RETURN(!bounds.isEmpty(), "PxHairSystem::setTopology bounds must not be empty"); PX_CHECK_AND_RETURN((vertexPositionsInvMass != NULL && vertexVelocities != NULL), "PxHairSystem::setTopology positions and velocities must not be NULL") PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexPositionsInvMass) & 15), "PxHairSystem::setTopology vertexPositionInvMass not aligned to 16 bytes"); PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexVelocities) & 15), "PxHairSystem::setTopology vertexVelocities not aligned to 16 bytes"); PX_CHECK_AND_RETURN(numVertices < (1 << 24), "PxHairSystem::setTopology numVertices must be smaller than 1<<24"); // due to encoding compressedVtxIndex with hairsystem index Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); // release internal buffers if they're not needed anymore if (vertexPositionsInvMass != mPosInvMassInternal.begin()) mPosInvMassInternal.reset(); if (vertexVelocities != mVelInternal.begin()) mVelInternal.reset(); if (strandPastEndIndices != mStrandPastEndIndicesInternal.begin()) mStrandPastEndIndicesInternal.reset(); llCore.mParams.mSegmentLength = segmentLength; setSegmentRadius(segmentRadius); llCore.mParams.mSegmentRadius = segmentRadius; llCore.mNumVertices = numVertices; llCore.mNumStrands = numStrands; llCore.mStrandPastEndIndices = strandPastEndIndices; llCore.mPositionInvMass = vertexPositionsInvMass; llCore.mVelocity = vertexVelocities; // reset rest positions setRestPositions(NULL, false); setLlGridSize(bounds); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eNUM_STRANDS_OR_VERTS | Dy::HairSystemDirtyFlag::ePOSITIONS_VELOCITIES_MASS | Dy::HairSystemDirtyFlag::ePARAMETERS | Dy::HairSystemDirtyFlag::eSTRAND_LENGTHS | Dy::HairSystemDirtyFlag::eGRID_SIZE; } void NpHairSystem::setLevelOfDetailGradations(const PxReal* proportionOfStrands, const PxReal* proportionOfVertices, PxU32 numLevels) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(numLevels > 0, "PxHairSystem::defineLevelOfDetailGradations Must specify at least one level."); for (PxU32 i = 0; i < numLevels; i++) { PX_CHECK_AND_RETURN(proportionOfStrands[i] <= 1.0f && proportionOfStrands[i] > 0.0f, "PxHairSystem::defineLevelOfDetailGradations proportionOfStrands must be in (0, 1] "); PX_CHECK_AND_RETURN(proportionOfVertices[i] <= 1.0f && proportionOfVertices[i] > 0.0f, "PxHairSystem::defineLevelOfDetailGradations proportionOfStrands must be in (0, 1] "); } // deep copy because user buffers may go out of scope / deallocate mLodProportionOfStrands.assign(proportionOfStrands, proportionOfStrands + numLevels); mLodProportionOfVertices.assign(proportionOfVertices, proportionOfVertices + numLevels); // TODO(jcarius) check that hair system is initialized already Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mLodNumLevels = numLevels; llCore.mLodProportionOfStrands = mLodProportionOfStrands.begin(); llCore.mLodProportionOfVertices = mLodProportionOfVertices.begin(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eLOD_DATA; // in case the level that we were on got removed switch to closest one if(llCore.mLodLevel > numLevels) { llCore.mLodLevel = numLevels; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eLOD_SWITCH; } } void NpHairSystem::setLevelOfDetail(PxU32 level) { NP_WRITE_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(level == 0 || llCore.mLodNumLevels >= level, "PxHairSystem::setLevelOfDetail Invalid level given"); llCore.mLodLevel = level; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eLOD_SWITCH; } PxU32 NpHairSystem::getLevelOfDetail(PxU32* numLevels) const { NP_READ_CHECK(getNpScene()); if(numLevels != NULL) { *numLevels = mCore.getShapeCore().getLLCore().mLodNumLevels; } return mCore.getShapeCore().getLLCore().mLodLevel; } void NpHairSystem::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); mName = debugName; } const char* NpHairSystem::getName() const { NP_READ_CHECK(getNpScene()); return mName; } void NpHairSystem::getSegmentDimensions(PxReal& length, PxReal& radius) const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); length = llCore.mParams.mSegmentLength; radius = llCore.mParams.mSegmentRadius; } void NpHairSystem::setSegmentRadius(PxReal radius) { NP_WRITE_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(2.0f * radius < llCore.mParams.mSegmentLength, "PxHairSystem::setSegmentRadius radius must be smaller than half of segment length. Call ignored"); llCore.mParams.mSegmentRadius = radius; mCore.setContactOffset(2.0f * radius); // sensible default llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setWind(const PxVec3& wind) { NP_WRITE_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PxVec3 windNormalized = wind; const PxReal magnitude = windNormalized.normalize(); llCore.mWind = PxVec4(windNormalized, magnitude); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxVec3 NpHairSystem::getWind() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mWind.getXYZ() * llCore.mWind.w; } void NpHairSystem::setAerodynamicDrag(PxReal dragCoefficient) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(dragCoefficient >= 0.0f, "PxHairSystem::setAerodynamicDrag: dragCoefficient must be greater or equal zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mAeroDrag = dragCoefficient; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setAerodynamicLift(PxReal liftCoefficient) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(liftCoefficient >= 0.0f, "PxHairSystem::setAerodynamicLift: liftCoefficient must be greater or equal zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mAeroLift = liftCoefficient; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getAerodynamicDrag() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mAeroDrag; } PxReal NpHairSystem::getAerodynamicLift() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mAeroLift; } void NpHairSystem::setFrictionParameters(PxReal interHairVelDamping, PxReal frictionCoeff) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(interHairVelDamping >= 0.0f, "PxHairSystem::setFrictionParameters interHairVelDamping must be greater or equal zero."); PX_CHECK_AND_RETURN(interHairVelDamping <= 1.0f, "PxHairSystem::setFrictionParameters interHairVelDamping must be smaller or equal one."); PX_CHECK_AND_RETURN(frictionCoeff >= 0.0f, "PxHairSystem::setFrictionParameters frictionCoeff must be greater or equal zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mInterHairVelocityDamping = interHairVelDamping; llCore.mParams.mFrictionCoeff = frictionCoeff; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::getFrictionParameters(PxReal& interHairVelDamping, PxReal& frictionCoeff) const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); interHairVelDamping = llCore.mParams.mInterHairVelocityDamping; frictionCoeff = llCore.mParams.mFrictionCoeff; } void NpHairSystem::setMaxDepenetrationVelocity(PxReal maxDepenetrationVelocity) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(maxDepenetrationVelocity > 0.0f, "PxHairSystem::setMaxDepenetrationVelocity maxDepenetrationVelocity must be larger than zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mMaxDepenetrationVelocity = maxDepenetrationVelocity; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getMaxDepenetrationVelocity() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mMaxDepenetrationVelocity; } void NpHairSystem::setShapeCompliance(PxReal startCompliance, PxReal strandRatio) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(strandRatio >= 0.0f, "PxHairSystem::setShapeCompliance strandRatio must not be negative."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mRestPositionsD, "PxHairSystem::setShapeCompliance restPositions must be set before enabling shape compliance"); llCore.mParams.mShapeCompliance[0] = startCompliance; llCore.mParams.mShapeCompliance[1] = strandRatio; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::getShapeCompliance(PxReal& startCompliance, PxReal& strandRatio) const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); startCompliance = llCore.mParams.mShapeCompliance[0]; strandRatio = llCore.mParams.mShapeCompliance[1]; } void NpHairSystem::setInterHairRepulsion(PxReal repulsion) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(repulsion >= 0.0f, "PxHairSystem::setInterHairRepulsion repulsion must not be negative."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mInterHairRepulsion = repulsion; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getInterHairRepulsion() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mInterHairRepulsion; } void NpHairSystem::setSelfCollisionRelaxation(PxReal relaxation) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(relaxation > 0.0f, "PxHairSystem::setSelfCollisionRelaxation relaxation must be greater zero."); PX_CHECK_AND_RETURN(relaxation <= 1.0f, "PxHairSystem::setSelfCollisionRelaxation relaxation must not be greater 1.0."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mSelfCollisionRelaxation = relaxation; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getSelfCollisionRelaxation() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mSelfCollisionRelaxation; } void NpHairSystem::setStretchingRelaxation(PxReal relaxation) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(relaxation > 0.0f, "PxHairSystem::setStretchingRelaxation relaxation must be greater zero."); PX_CHECK_AND_RETURN(relaxation <= 1.0f, "PxHairSystem::setStretchingRelaxation relaxation must not be greater 1.0."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mLraRelaxation = relaxation; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getStretchingRelaxation() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mLraRelaxation; } void NpHairSystem::setContactOffset(PxReal contactOffset) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(contactOffset >= 0.0f, "PxHairSystem::setContactOffset contactOffset must not be negative."); mCore.setContactOffset(contactOffset); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getContactOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getContactOffset(); } void NpHairSystem::setHairContactOffset(PxReal hairContactOffset) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(hairContactOffset >= 1.0f, "PxHairSystem::setHairContactOffset hairContactOffset must not be below 1.0."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mSelfCollisionContactDist = hairContactOffset; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getHairContactOffset() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mSelfCollisionContactDist; } void NpHairSystem::setShapeMatchingParameters(PxReal compliance, PxReal linearStretching, PxU16 numVerticesPerGroup, PxU16 numVerticesOverlap) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(linearStretching >= 0.0f, "PxHairSystem::setShapeMatchingParameters linearStretching must not be below 0.0."); PX_CHECK_AND_RETURN(linearStretching <= 1.0f, "PxHairSystem::setShapeMatchingParameters linearStretching must not be above 1.0."); PX_CHECK_AND_RETURN(numVerticesPerGroup > 1, "PxHairSystem::setShapeMatchingParameters numVerticesPerGroup must be greater 1."); PX_CHECK_AND_RETURN(numVerticesPerGroup >= 2 * numVerticesOverlap, "PxHairSystem::setShapeMatchingParameters numVerticesOverlap must at most be numVerticesPerGroup/2."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mRestPositionsD, "PxHairSystem::setShapeMatchingParameters restPositions must be set before enabling shape compliance"); llCore.mParams.mShapeMatchingCompliance = compliance; llCore.mParams.mShapeMatchingBeta = linearStretching; llCore.mParams.mShapeMatchingNumVertsPerGroup = numVerticesPerGroup; llCore.mParams.mShapeMatchingNumVertsOverlap = numVerticesOverlap; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eSHAPE_MATCHING_SIZES; } PxReal NpHairSystem::getShapeMatchingCompliance() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mShapeMatchingCompliance; } #endif } // namespace physx #endif //PX_SUPPORT_GPU_PHYSX
44,510
C++
38.706512
203
0.763941
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpParticleSystem.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "NpParticleSystem.h" #include "foundation/PxAllocator.h" #include "foundation/PxArray.h" #include "foundation/PxMath.h" #include "foundation/PxMemory.h" #include "foundation/PxSort.h" #include "common/PxPhysXCommonConfig.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxGridParticleSystem.h" #endif #include "PxRigidActor.h" #include "PxsSimulationController.h" #include "NpArticulationLink.h" #include "NpRigidDynamic.h" #include "NpScene.h" #include "NpCheck.h" #include "ScBodyCore.h" #include "ScParticleSystemCore.h" #include "ScParticleSystemSim.h" #include "ScParticleSystemShapeCore.h" #include "DyParticleSystemCore.h" #include "CmVisualization.h" #define PARTICLE_MAX_NUM_PARTITIONS_TEMP 32 #define PARTICLE_MAX_NUM_PARTITIONS_FINAL 8 using namespace physx; namespace physx { #if PX_ENABLE_DEBUG_VISUALIZATION static void visualizeParticleSystem(PxRenderOutput& out, NpScene& npScene, const Sc::ParticleSystemCore& core) { if (!(core.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; const Sc::Scene& scScene = npScene.getScScene(); const bool visualizeAABBs = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AABBS) != 0.0f; if (visualizeAABBs) { out << PxU32(PxDebugColor::eARGB_YELLOW) << PxMat44(PxIdentity); Cm::renderOutputDebugBox(out, core.getSim()->getBounds()); } } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif //////////////////////////////////////////////////////////////////////////////////////// PxPartitionedParticleCloth::PxPartitionedParticleCloth() { PxMemZero(this, sizeof(*this)); } PxPartitionedParticleCloth::~PxPartitionedParticleCloth() { if (mCudaManager) { PxScopedCudaLock lock(*mCudaManager); PxCudaContext* context = mCudaManager->getCudaContext(); if (context) { context->memFreeHost(accumulatedSpringsPerPartitions); context->memFreeHost(accumulatedCopiesPerParticles); context->memFreeHost(remapOutput); context->memFreeHost(orderedSprings); context->memFreeHost(sortedClothStartIndices); context->memFreeHost(cloths); } } } void PxPartitionedParticleCloth::allocateBuffers(PxU32 nbParticles, PxCudaContextManager* cudaManager) { mCudaManager = cudaManager; PxScopedCudaLock lock(*mCudaManager); PxCudaContext* context = mCudaManager->getCudaContext(); const unsigned int CU_MEMHOSTALLOC_DEVICEMAP = 0x02; const unsigned int CU_MEMHOSTALLOC_PORTABLE = 0x01; PxCUresult result = context->memHostAlloc(reinterpret_cast<void**>(&accumulatedSpringsPerPartitions), size_t(sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_FINAL), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); // TODO AD: WTF where does 32 come from? result = context->memHostAlloc(reinterpret_cast<void**>(&accumulatedCopiesPerParticles), size_t(sizeof(PxU32) * nbParticles), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&orderedSprings), size_t(sizeof(PxParticleSpring) * nbSprings), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&remapOutput), size_t(sizeof(PxU32) * nbSprings * 2), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&sortedClothStartIndices), size_t(sizeof(PxU32) * nbCloths), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&cloths), size_t(sizeof(PxParticleCloth) * nbCloths), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); } //////////////////////////////////////////////////////////////////////////////////////// PxU32 NpParticleClothPreProcessor::computeSpringPartition(const PxParticleSpring& spring, const PxU32 partitionStartIndex, PxU32* partitionProgresses) { PxU32 partitionA = partitionProgresses[spring.ind0]; PxU32 partitionB = partitionProgresses[spring.ind1]; const PxU32 combinedMask = (~partitionA & ~partitionB); PxU32 availablePartition = combinedMask == 0 ? PARTICLE_MAX_NUM_PARTITIONS_TEMP : PxLowestSetBit(combinedMask); if (availablePartition == PARTICLE_MAX_NUM_PARTITIONS_TEMP) { return 0xFFFFFFFF; } const PxU32 partitionBit = (1u << availablePartition); partitionA |= partitionBit; partitionB |= partitionBit; availablePartition += partitionStartIndex; partitionProgresses[spring.ind0] = partitionA; partitionProgresses[spring.ind1] = partitionB; return availablePartition; } void NpParticleClothPreProcessor::writeSprings(const PxParticleSpring* springs, PxU32* partitionProgresses, PxU32* tempSprings, PxU32* orderedSprings, PxU32* accumulatedSpringsPerPartition) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); PxU32 numUnpartitionedSprings = 0; // Goes through all the springs and assigns them to a partition. This code is exactly the same as in classifySprings // except that we now know the start indices of all the partitions so we can write THEIR INDEX into the ordered spring // index list. // AD: All of this relies on the fact that we partition exactly the same way twice. Remember that when changing anything // here. for (PxU32 i = 0; i < mNumSprings; ++i) { const PxParticleSpring& spring = springs[i]; const PxU32 availablePartition = computeSpringPartition(spring, 0, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { tempSprings[numUnpartitionedSprings++] = i; continue; } //output springs orderedSprings[accumulatedSpringsPerPartition[availablePartition]++] = i; } PxU32 partitionStartIndex = 0; // handle the overflow of springs we couldn't partition above. while (numUnpartitionedSprings > 0) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); partitionStartIndex += PARTICLE_MAX_NUM_PARTITIONS_TEMP; PxU32 newNumUnpartitionedSprings = 0; for (PxU32 i = 0; i < numUnpartitionedSprings; ++i) { const PxU32 springInd = tempSprings[i]; const PxParticleSpring& spring = springs[springInd]; const PxU32 availablePartition = computeSpringPartition(spring, partitionStartIndex, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { tempSprings[newNumUnpartitionedSprings++] = springInd; continue; } //output springs orderedSprings[accumulatedSpringsPerPartition[availablePartition]++] = springInd; } numUnpartitionedSprings = newNumUnpartitionedSprings; } // at this point all of the springs are partitioned and in the ordered list. } void NpParticleClothPreProcessor::classifySprings(const PxParticleSpring* springs, PxU32* partitionProgresses, PxU32* tempSprings, physx::PxArray<PxU32>& tempSpringsPerPartition) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); PxU32 numUnpartitionedSprings = 0; // Goes through all the springs and tries to partition, but will max out at 32 partitions (because we only have 32 bits) for (PxU32 i = 0; i < mNumSprings; ++i) { const PxParticleSpring& spring = springs[i]; // will return the first partition where it's possible to place this spring. const PxU32 availablePartition = computeSpringPartition(spring, 0, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { // we couldn't find a partition, so we add the index to this list for later. tempSprings[numUnpartitionedSprings++] = i; continue; } // tracks how many springs we have in each partition. tempSpringsPerPartition[availablePartition]++; } PxU32 partitionStartIndex = 0; // handle the overflow of the springs we couldn't partition above // we work in batches of 32 bits. while (numUnpartitionedSprings > 0) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); partitionStartIndex += PARTICLE_MAX_NUM_PARTITIONS_TEMP; //Keep partitioning the un-partitioned constraints and blat the whole thing to 0! tempSpringsPerPartition.resize(PARTICLE_MAX_NUM_PARTITIONS_TEMP + tempSpringsPerPartition.size()); PxMemZero(tempSpringsPerPartition.begin() + partitionStartIndex, sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_TEMP); PxU32 newNumUnpartitionedSprings = 0; for (PxU32 i = 0; i < numUnpartitionedSprings; ++i) { const PxU32 springInd = tempSprings[i]; const PxParticleSpring& spring = springs[springInd]; const PxU32 availablePartition = computeSpringPartition(spring, partitionStartIndex, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { tempSprings[newNumUnpartitionedSprings++] = springInd; continue; } tempSpringsPerPartition[availablePartition]++; } numUnpartitionedSprings = newNumUnpartitionedSprings; } // after all of this we have the number of springs per partition in tempSpringsPerPartition. we don't really know what spring will // go where yet, that will follow later. } PxU32* NpParticleClothPreProcessor::partitions(const PxParticleSpring* springs, PxU32* orderedSpringIndices) { //each particle has a partition progress counter PxU32* tempPartitionProgresses = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumParticles, "tempPartitionProgresses")); //this stores the spring index for the unpartitioned springs PxU32* tempSprings = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumSprings, "tempSprings")); PxArray<PxU32> tempSpringsPerPartition; tempSpringsPerPartition.reserve(PARTICLE_MAX_NUM_PARTITIONS_TEMP); tempSpringsPerPartition.forceSize_Unsafe(PARTICLE_MAX_NUM_PARTITIONS_TEMP); PxMemZero(tempSpringsPerPartition.begin(), sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_TEMP); classifySprings(springs, tempPartitionProgresses, tempSprings, tempSpringsPerPartition); //compute number of partitions PxU32 maxPartitions = 0; for (PxU32 a = 0; a < tempSpringsPerPartition.size(); ++a, maxPartitions++) { if (tempSpringsPerPartition[a] == 0) break; } PxU32* tempAccumulatedSpringsPerPartition = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * maxPartitions, "mAccumulatedSpringsPerPartition")); mNbPartitions = maxPartitions; // save the current number of partitions //compute run sum PxU32 accumulation = 0; for (PxU32 a = 0; a < maxPartitions; ++a) { PxU32 count = tempSpringsPerPartition[a]; tempAccumulatedSpringsPerPartition[a] = accumulation; accumulation += count; } PX_ASSERT(accumulation == mNumSprings); // this will assign the springs to partitions writeSprings(springs, tempPartitionProgresses, tempSprings, orderedSpringIndices, tempAccumulatedSpringsPerPartition); #if 0 && PX_CHECKED //validate spring partitions for (PxU32 i = 0; i < mNumSprings; ++i) { PxU32 springInd = orderedSprings[i]; for (PxU32 j = i + 1; j < mNumSprings; ++j) { PxU32 otherSpringInd = orderedSprings[j]; PX_ASSERT(springInd != otherSpringInd); } } PxArray<bool> mFound(mNumParticles); PxU32 startIndex = 0; for (PxU32 i = 0; i < maxPartition; ++i) { PxU32 endIndex = tempAccumulatedSpringsPerPartition[i]; PxMemZero(mFound.begin(), sizeof(bool) * mNumParticles); for (PxU32 j = startIndex; j < endIndex; ++j) { PxU32 tetrahedronIdx = orderedSprings[j]; const PxParticleSpring& spring = springs[tetrahedronIdx]; PX_ASSERT(!mFound[spring.ind0]); PX_ASSERT(!mFound[spring.ind1]); mFound[spring.ind0] = true; mFound[spring.ind1] = true; } startIndex = endIndex; } #endif PX_FREE(tempPartitionProgresses); PX_FREE(tempSprings); return tempAccumulatedSpringsPerPartition; } PxU32 NpParticleClothPreProcessor::combinePartitions(const PxParticleSpring* springs, const PxU32* orderedSpringIndices, const PxU32* accumulatedSpringsPerPartition, PxU32* accumulatedSpringsPerCombinedPartition, PxParticleSpring* orderedSprings, PxU32* accumulatedCopiesPerParticles, PxU32* remapOutput) { // reduces the number of partitions from mNbPartitions to PARTICLE_MAX_NUM_PARTITIONS_FINAL const PxU32 nbPartitions = mNbPartitions; mNbPartitions = PARTICLE_MAX_NUM_PARTITIONS_FINAL; PxMemZero(accumulatedSpringsPerCombinedPartition, sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_FINAL); // ceil(nbPartitions/maxPartitions) -basically the number of "repetitions" before combining. Example, MAX_FINAL is 8, we have 20 total, so this is 3. const PxU32 maxAccumulatedCP = (nbPartitions + PARTICLE_MAX_NUM_PARTITIONS_FINAL - 1) / PARTICLE_MAX_NUM_PARTITIONS_FINAL; // enough space for all partitions. const PxU32 partitionArraySize = maxAccumulatedCP * PARTICLE_MAX_NUM_PARTITIONS_FINAL; // for each particle, have a table of all partitions. const PxU32 nbPartitionTables = partitionArraySize * mNumParticles; // per-particle, stores whether particle is part of partition PxU32* tempPartitionTablePerVert = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * nbPartitionTables, "tempPartitionTablePerVert")); // per-particle, stores remapping ????? PxU32* tempRemapTablePerVert = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * nbPartitionTables, "tempRemapTablePerVert")); // per-particle, stores the number of copies for each particle. PxU32* tempNumCopiesEachVerts = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumParticles, "tempNumCopiesEachVerts")); PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * mNumParticles); //initialize partitionTablePerVert for (PxU32 i = 0; i < nbPartitionTables; ++i) { tempPartitionTablePerVert[i] = 0xffffffff; tempRemapTablePerVert[i] = 0xffffffff; } // combine partitions: // let PARTICLE_MAX_NUM_PARTITIONS_FINAL be 8 and the current number of partitions be 20 // this will merge partition 0, 8, 16 into the first partition, // then put 1, 9, 17 into the second partition, etc. // we move all the springs of partition x*PARTICLE_MAX_NUM_PARTITION_FINAL to the end of partition x, // using the count variable. // output of this stage // orderedSprings - has springs per partition // accumulatedSpringsPerCombinedPartition - has number of springs of each partition // tempPartitionTablePerVert - has spring index of spring that connects to this particle in this partition. mMaxSpringsPerPartition = 0; PxU32 count = 0; for (PxU32 i = 0; i < PARTICLE_MAX_NUM_PARTITIONS_FINAL; ++i) { PxU32 totalSpringsInPartition = 0; for (PxU32 j = 0; j < maxAccumulatedCP; ++j) { PxU32 partitionId = i + PARTICLE_MAX_NUM_PARTITIONS_FINAL * j; if (partitionId < nbPartitions) { const PxU32 startInd = partitionId == 0 ? 0 : accumulatedSpringsPerPartition[partitionId - 1]; const PxU32 endInd = accumulatedSpringsPerPartition[partitionId]; const PxU32 index = i * maxAccumulatedCP + j; for (PxU32 k = startInd; k < endInd; ++k) { const PxU32 springInd = orderedSpringIndices[k]; const PxParticleSpring& spring = springs[springInd]; orderedSprings[count] = spring; PX_ASSERT(spring.ind0 != spring.ind1); tempPartitionTablePerVert[spring.ind0 * partitionArraySize + index] = count; tempPartitionTablePerVert[spring.ind1 * partitionArraySize + index] = count + mNumSprings; count++; } totalSpringsInPartition += (endInd - startInd); } } accumulatedSpringsPerCombinedPartition[i] = count; mMaxSpringsPerPartition = PxMax(mMaxSpringsPerPartition, totalSpringsInPartition); } PX_ASSERT(count == mNumSprings); PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * mNumParticles); bool* tempHasOccupied = reinterpret_cast<bool*>(PX_ALLOC(sizeof(bool) * partitionArraySize, "tempOrderedSprings")); // compute num of copies and remap index // // remap table - builds a chain of indices of the same particle across partitions // if particle x is at index y in partition 1, we build a table such that particle x in partition 2 can look up the index in partition 1 // This basically maintains the gauss-seidel part of the solver, where each partition works on the results of the another partition. // This remap table is build across combined partitions. So there will never be a remap into the same partition. // // numCopies is then the number of final copies, meaning all copies of each particle that don't have a remap into one of the following // partitions. // for (PxU32 i = 0; i < mNumParticles; ++i) { // for each particle, use this list to track which partition is occupied. PxMemZero(tempHasOccupied, sizeof(bool) * partitionArraySize); // partition table has size numPartitions for each particle, tells you the spring index for this partition const PxU32* partitionTable = &tempPartitionTablePerVert[i * partitionArraySize]; // remapTable is still empty (0xFFFFFFFF) PxU32* remapTable = &tempRemapTablePerVert[i * partitionArraySize]; // for all of the final partitions. for (PxU32 j = 0; j < PARTICLE_MAX_NUM_PARTITIONS_FINAL; ++j) { // start index of this combined partition in the initial partition array const PxU32 startInd = j * maxAccumulatedCP; // start index if the next combined partition in the initial partition array PxU32 nextStartInd = (j + 1) * maxAccumulatedCP; // for our 8/20 example, that would be startInd 0, nextStartInd 3 because every // final partition will be combined from 3 partitions. // go through the indices of this combined partition (0-2) for (PxU32 k = 0; k < maxAccumulatedCP; ++k) { const PxU32 index = startInd + k; if (partitionTable[index] != 0xffffffff) { // there is a spring in this partition connected to this particle bool found = false; // look at the next partition, potentially also further ahead to figure out if there is any other partition having this particle index. for (PxU32 h = nextStartInd; h < partitionArraySize; ++h) { // check if any of the partitions in this combined partition is occupied. const PxU32 remapInd = partitionTable[h]; if (remapInd != 0xffffffff && !tempHasOccupied[h]) { // if it is, and none of the other partitions in the partition before already remapped to that one remapTable[index] = remapInd; // maps from partition i to one of the next ones. found = true; tempHasOccupied[h] = true; // mark as occupied nextStartInd++; // look one more (initial!) partition ahead for next remap. break; } } if (!found) { tempNumCopiesEachVerts[i]++; // if not found, add one more copy as there won't be any follow-up partition taking this position as an input. } } } } } const PxU32 totalNumVerts = mNumSprings * 2; // compute a runSum for the number of copies for each particle PxU32 totalCopies = 0; for (PxU32 i = 0; i < mNumParticles; ++i) { totalCopies += tempNumCopiesEachVerts[i]; accumulatedCopiesPerParticles[i] = totalCopies; } const PxU32 remapOutputSize = totalNumVerts + totalCopies; // fill the output of the remap // // for all particle copies that are at the end of a remap chain, calculate the remap // into the final accumulation buffer. // // the final accumulation buffer will have numCopies entries for each particle. // for (PxU32 i = 0; i < mNumParticles; ++i) { const PxU32 index = i * partitionArraySize; const PxU32* partitionTable = &tempPartitionTablePerVert[index]; PxU32* remapTable = &tempRemapTablePerVert[index]; PxU32 accumulatedCount = 0; for (PxU32 j = 0; j < partitionArraySize; ++j) { const PxU32 vertInd = partitionTable[j]; if (vertInd != 0xffffffff) { PxU32 remapInd = remapTable[j]; //this remap is in the accumulation buffer if (remapInd == 0xffffffff) { const PxU32 start = i == 0 ? 0 : accumulatedCopiesPerParticles[i - 1]; remapInd = totalNumVerts + start + accumulatedCount; accumulatedCount++; } PX_ASSERT(remapInd < remapOutputSize); remapOutput[vertInd] = remapInd; } } } PX_FREE(tempHasOccupied); PX_FREE(tempPartitionTablePerVert); PX_FREE(tempRemapTablePerVert); PX_FREE(tempNumCopiesEachVerts); return remapOutputSize; } void NpParticleClothPreProcessor::partitionSprings(const PxParticleClothDesc& clothDesc, PxPartitionedParticleCloth& output) { mNumSprings = clothDesc.nbSprings; mNumParticles = clothDesc.nbParticles; // prepare the output output.nbSprings = clothDesc.nbSprings; output.nbCloths = clothDesc.nbCloths; output.allocateBuffers(mNumParticles, mCudaContextManager); // will create a temp partitioning with too many partitions PxU32* orderedSpringIndices = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumSprings, "orderedSpringIndices")); PxU32* accumulatedSpringsPerPartitionTemp = partitions(clothDesc.springs, orderedSpringIndices); // combine these partitions to a max of PARTICLE_MAX_NUM_PARTITIONS_FINAL // build remap chains and accumulation buffer. output.remapOutputSize = combinePartitions(clothDesc.springs, orderedSpringIndices, accumulatedSpringsPerPartitionTemp, output.accumulatedSpringsPerPartitions, output.orderedSprings, output.accumulatedCopiesPerParticles, output.remapOutput); // get the max number of partitions for each cloth // AD Todo: figure out why blendScale is computed like this. PxParticleCloth* cloths = clothDesc.cloths; for (PxU32 i = 0; i < clothDesc.nbCloths; ++i) { PxU32 maxPartitions = 0; for (PxU32 p = cloths[i].startVertexIndex, endIndex = cloths[i].startVertexIndex + cloths[i].numVertices; p < endIndex; p++) { PxU32 copyStart = p == 0 ? 0 : output.accumulatedCopiesPerParticles[p - 1]; PxU32 copyEnd = output.accumulatedCopiesPerParticles[p]; maxPartitions = PxMax(maxPartitions, copyEnd - copyStart); } cloths[i].clothBlendScale = 1.f / (maxPartitions + 1); } // sort the cloths in this clothDesc according to their startVertexIndex into the particle list. PxSort(cloths, clothDesc.nbCloths); // reorder such that things still match after the sorting. for (PxU32 i = 0; i < clothDesc.nbCloths; ++i) { output.sortedClothStartIndices[i] = cloths[i].startVertexIndex; output.cloths[i] = cloths[i]; } output.nbPartitions = mNbPartitions; output.maxSpringsPerPartition = mMaxSpringsPerPartition; PX_FREE(accumulatedSpringsPerPartitionTemp); PX_FREE(orderedSpringIndices); } void NpParticleClothPreProcessor::release() { PX_DELETE_THIS; } /////////////////////////////////////////////////////////////////////////////////////// NpPBDParticleSystem::NpPBDParticleSystem(PxU32 maxNeighborhood, PxCudaContextManager& cudaContextManager) : NpParticleSystem<PxPBDParticleSystem>(cudaContextManager, PxConcreteType::ePBD_PARTICLESYSTEM, NpType::ePBD_PARTICLESYSTEM, PxActorType::ePBD_PARTICLESYSTEM) { //PX_ASSERT(mCudaContextManager); setSolverType(PxParticleSolverType::ePBD); mCore.getShapeCore().initializeLLCoreData(maxNeighborhood); enableCCD(false); } PxU32 NpPBDParticleSystem::createPhase(PxParticleMaterial* material, const PxParticlePhaseFlags flags) { if (material->getConcreteType() == PxConcreteType::ePBD_MATERIAL) { Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); Dy::ParticleSystemCore& core = shapeCore.getLLCore(); PxU16 materialHandle = static_cast<NpPBDMaterial*>(material)->mMaterial.mMaterialIndex; const PxU32 groupID = mNextPhaseGroupID++; core.mPhaseGroupToMaterialHandle.pushBack(materialHandle); PxU16* foundHandle = core.mUniqueMaterialHandles.find(materialHandle); if(foundHandle == core.mUniqueMaterialHandles.end()) { core.mUniqueMaterialHandles.pushBack(materialHandle); } if (mCore.getSim()) mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PHASE; return (groupID & PxParticlePhaseFlag::eParticlePhaseGroupMask) | (PxU32(flags) & PxParticlePhaseFlag::eParticlePhaseFlagsMask); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxPBDParticleSystem:createPhase(): the provided material is not supported by this type of particle system."); return 0; } } void NpPBDParticleSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveParticleSystem(*this); npScene->removeFromParticleSystemList(*this); } PX_ASSERT(!isAPIWriteForbidden()); NpDestroyParticleSystem(this); } PxU32 NpPBDParticleSystem::getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return getParticleMaterialsInternal<NpPBDMaterial>(userBuffer, bufferSize, startIndex); } void NpPBDParticleSystem::addParticleBuffer(PxParticleBuffer* clothBuffer) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpPBDParticleSystem::addParticleBuffer: this function cannot be called when the particle system is not inserted into the scene!"); mCore.getShapeCore().addParticleBuffer(clothBuffer); } void NpPBDParticleSystem::removeParticleBuffer(PxParticleBuffer* clothBuffer) { mCore.getShapeCore().removeParticleBuffer(clothBuffer); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpPBDParticleSystem::visualize(PxRenderOutput& out, NpScene& npScene) const { visualizeParticleSystem(out, npScene, mCore); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif static void internalAddRigidAttachment(PxRigidActor* actor, Sc::ParticleSystemCore& psCore) { Sc::BodyCore* core = getBodyCore(actor); psCore.addRigidAttachment(core); } static void internalRemoveRigidAttachment(PxRigidActor* actor, Sc::ParticleSystemCore& psCore) { Sc::BodyCore* core = getBodyCore(actor); psCore.removeRigidAttachment(core); } void NpPBDParticleSystem::addRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpPBDParticleSystem::addRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpPBDParticleSystem::addRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpPBDParticleSystem::addRigidAttachment: Illegal to call while simulation is running."); internalAddRigidAttachment(actor, mCore); } void NpPBDParticleSystem::removeRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpPBDParticleSystem::removeRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpPBDParticleSystem::removeRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpPBDParticleSystem::removeRigidAttachment: Illegal to call while simulation is running."); internalRemoveRigidAttachment(actor, mCore); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFLIPParticleSystem::NpFLIPParticleSystem(PxCudaContextManager& cudaContextManager) : NpParticleSystem<PxFLIPParticleSystem>(cudaContextManager, PxConcreteType::eFLIP_PARTICLESYSTEM, NpType::eFLIP_PARTICLESYSTEM, PxActorType::eFLIP_PARTICLESYSTEM) { //PX_ASSERT(mCudaContextManager); setSolverType(PxParticleSolverType::eFLIP); mCore.getShapeCore().initializeLLCoreData(0); enableCCD(false); } PxU32 NpFLIPParticleSystem::createPhase(PxParticleMaterial* material, const PxParticlePhaseFlags flags) { if (material->getConcreteType() == PxConcreteType::eFLIP_MATERIAL) { Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); Dy::ParticleSystemCore& core = shapeCore.getLLCore(); PxU16 materialHandle = static_cast<NpFLIPMaterial*>(material)->mMaterial.mMaterialIndex; const PxU32 groupID = mNextPhaseGroupID++; core.mPhaseGroupToMaterialHandle.pushBack(materialHandle); PxU16* foundHandle = core.mUniqueMaterialHandles.find(materialHandle); if(foundHandle == core.mUniqueMaterialHandles.end()) { core.mUniqueMaterialHandles.pushBack(materialHandle); } if (mCore.getSim()) mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PHASE; return (groupID & PxParticlePhaseFlag::eParticlePhaseGroupMask) | (PxU32(flags) & PxParticlePhaseFlag::eParticlePhaseFlagsMask); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxFLIPParticleSystem:createPhase(): the provided material is not supported by this type of particle system."); return 0; } } void NpFLIPParticleSystem::getSparseGridCoord(PxI32& x, PxI32& y, PxI32& z, PxU32 id) { const PxI32 iid = static_cast<PxI32>(id); x = iid % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; y = (iid / MAX_SPARSEGRID_DIM) % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; z = iid / MAX_SPARSEGRID_DIM / MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; } void NpFLIPParticleSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveParticleSystem(*this); npScene->removeFromParticleSystemList(*this); } PX_ASSERT(!isAPIWriteForbidden()); NpDestroyParticleSystem(this); } void* NpFLIPParticleSystem::getSparseGridDataPointer(PxSparseGridDataFlag::Enum flags) { NpScene* scene = getNpScene(); if (!scene) return NULL; if ((flags & (PxSparseGridDataFlag::eSUBGRID_MASK | PxSparseGridDataFlag::eSUBGRID_ID | PxSparseGridDataFlag::eGRIDCELL_SOLID_GRADIENT_AND_SDF | PxSparseGridDataFlag::eGRIDCELL_SOLID_VELOCITY | PxSparseGridDataFlag::eGRIDCELL_FLUID_SDF | PxSparseGridDataFlag::eGRIDCELL_FLUID_VELOCITY )) == 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxParticleSystem::getSparseGridDataPointer, specified data is not available."); return NULL; } NP_READ_CHECK(scene); return scene->getSimulationController()->getSparseGridDataPointer(*getCore().getSim()->getLowLevelParticleSystem(), flags, getCore().getSolverType()); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpFLIPParticleSystem::visualize(PxRenderOutput& out, NpScene& npScene) const { visualizeParticleSystem(out, npScene, mCore); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif PxU32 NpFLIPParticleSystem::getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return getParticleMaterialsInternal<NpFLIPMaterial>(userBuffer, bufferSize, startIndex); } void NpFLIPParticleSystem::addParticleBuffer(PxParticleBuffer* particleBuffer) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFLIPParticleSystem::addParticleBuffer: this function cannot be called when the particle system is not inserted into the scene!"); PxType type = particleBuffer->getConcreteType(); if (type == PxConcreteType::ePARTICLE_BUFFER || type == PxConcreteType::ePARTICLE_DIFFUSE_BUFFER) { mCore.getShapeCore().addParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpFLIPParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } void NpFLIPParticleSystem::removeParticleBuffer(PxParticleBuffer* particleBuffer) { PxType type = particleBuffer->getConcreteType(); if (type == PxConcreteType::ePARTICLE_BUFFER || type == PxConcreteType::ePARTICLE_DIFFUSE_BUFFER) { mCore.getShapeCore().removeParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpFLIPParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// NpMPMParticleSystem::NpMPMParticleSystem(PxCudaContextManager& cudaContextManager) : NpParticleSystem<PxMPMParticleSystem>(cudaContextManager, PxConcreteType::eMPM_PARTICLESYSTEM, NpType::eMPM_PARTICLESYSTEM, PxActorType::eMPM_PARTICLESYSTEM) { //PX_ASSERT(mCudaContextManager); setSolverType(PxParticleSolverType::eMPM); mCore.getShapeCore().initializeLLCoreData(0); enableCCD(false); } PxU32 NpMPMParticleSystem::createPhase(PxParticleMaterial* material, const PxParticlePhaseFlags flags) { if (material->getConcreteType() == PxConcreteType::eMPM_MATERIAL) { Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); Dy::ParticleSystemCore& core = shapeCore.getLLCore(); PxU16 materialHandle = static_cast<NpMPMMaterial*>(material)->mMaterial.mMaterialIndex; const PxU32 groupID = mNextPhaseGroupID++; core.mPhaseGroupToMaterialHandle.pushBack(materialHandle); PxU16* foundHandle = core.mUniqueMaterialHandles.find(materialHandle); if(foundHandle == core.mUniqueMaterialHandles.end()) { core.mUniqueMaterialHandles.pushBack(materialHandle); } if (mCore.getSim()) mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PHASE; return (groupID & PxParticlePhaseFlag::eParticlePhaseGroupMask) | (PxU32(flags) & PxParticlePhaseFlag::eParticlePhaseFlagsMask); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMPMParticleSystem:createPhase(): the provided material is not supported by this type of particle system."); return 0; } } void NpMPMParticleSystem::getSparseGridCoord(PxI32& x, PxI32& y, PxI32& z, PxU32 id) { const PxI32 iid = static_cast<PxI32>(id); x = iid % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; y = (iid / MAX_SPARSEGRID_DIM) % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; z = iid / MAX_SPARSEGRID_DIM / MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; } void NpMPMParticleSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveParticleSystem(*this); npScene->removeFromParticleSystemList(*this); } PX_ASSERT(!isAPIWriteForbidden()); NpDestroyParticleSystem(this); } void* NpMPMParticleSystem::getSparseGridDataPointer(PxSparseGridDataFlag::Enum flags) { if ((flags & (PxSparseGridDataFlag::eSUBGRID_MASK | PxSparseGridDataFlag::eSUBGRID_ID | PxSparseGridDataFlag::eGRIDCELL_SOLID_GRADIENT_AND_SDF | PxSparseGridDataFlag::eGRIDCELL_SOLID_VELOCITY | PxSparseGridDataFlag::eGRIDCELL_FLUID_SDF | PxSparseGridDataFlag::eGRIDCELL_FLUID_VELOCITY )) == 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxParticleSystem::getSparseGridDataPointer, specified data is not available."); return NULL; } NP_READ_CHECK(getNpScene()); NpScene* scene = getNpScene(); return scene->getSimulationController()->getSparseGridDataPointer(*getCore().getSim()->getLowLevelParticleSystem(), flags, getCore().getSolverType()); } void* NpMPMParticleSystem::getMPMDataPointer(PxMPMParticleDataFlag::Enum flags) { NpScene* scene = getNpScene(); if (!scene) return NULL; if ((flags & (PxMPMParticleDataFlag::eMPM_AFFINE_C1 | PxMPMParticleDataFlag::eMPM_AFFINE_C2 | PxMPMParticleDataFlag::eMPM_AFFINE_C3 | PxMPMParticleDataFlag::eMPM_DEFORMATION_GRADIENT_F1 | PxMPMParticleDataFlag::eMPM_DEFORMATION_GRADIENT_F2 | PxMPMParticleDataFlag::eMPM_DEFORMATION_GRADIENT_F3)) == 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxMPMParticleSystem::copyData, specified data is not available."); return NULL; } NP_READ_CHECK(scene); return scene->getSimulationController()->getMPMDataPointer(*getCore().getSim()->getLowLevelParticleSystem(), flags); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpMPMParticleSystem::visualize(PxRenderOutput& out, NpScene& npScene) const { visualizeParticleSystem(out, npScene, mCore); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif PxU32 NpMPMParticleSystem::getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return getParticleMaterialsInternal<NpMPMMaterial>(userBuffer, bufferSize, startIndex); } void NpMPMParticleSystem::addParticleBuffer(PxParticleBuffer* particleBuffer) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpMPMParticleSystem::addParticleBuffer: this function cannot be called when the particle system is not inserted into the scene!"); if (particleBuffer->getConcreteType() == PxConcreteType::ePARTICLE_BUFFER) { mCore.getShapeCore().addParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpMPMParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } void NpMPMParticleSystem::removeParticleBuffer(PxParticleBuffer* particleBuffer) { if (particleBuffer->getConcreteType() == PxConcreteType::ePARTICLE_BUFFER) { mCore.getShapeCore().removeParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpMPMParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } void NpMPMParticleSystem::addRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpMPMParticleSystem::addRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpMPMParticleSystem::addRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpMPMParticleSystem::addRigidAttachment: Illegal to call while simulation is running."); internalAddRigidAttachment(actor, mCore); } void NpMPMParticleSystem::removeRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpMPMParticleSystem::removeRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpMPMParticleSystem::removeRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpMPMParticleSystem::removeRigidAttachment: Illegal to call while simulation is running."); internalRemoveRigidAttachment(actor, mCore); } #endif } physx::PxParticleClothPreProcessor* PxCreateParticleClothPreProcessor(physx::PxCudaContextManager* cudaContextManager) { physx::PxParticleClothPreProcessor* processor = PX_NEW(physx::NpParticleClothPreProcessor)(cudaContextManager); return processor; } #endif //PX_SUPPORT_GPU_PHYSX
41,369
C++
37.27012
258
0.739563
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdPhysicsClient.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. // PX_DUMMY_SYMBOL #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_PVD #include "pvd/PxPvdTransport.h" #include "PxPhysics.h" #include "PxPvdClient.h" #include "PxPvdDataStream.h" #include "PxPvdObjectModelBaseTypes.h" #include "PvdPhysicsClient.h" #include "PvdTypeNames.h" using namespace physx; using namespace physx::Vd; PvdPhysicsClient::PvdPhysicsClient(PsPvd* pvd) : mPvd(pvd), mPvdDataStream(NULL), mIsConnected(false) { } PvdPhysicsClient::~PvdPhysicsClient() { mPvd->removeClient(this); } PvdDataStream* PvdPhysicsClient::getDataStream() { return mPvdDataStream; } bool PvdPhysicsClient::isConnected() const { return mIsConnected; } void PvdPhysicsClient::onPvdConnected() { if(mIsConnected || !mPvd) return; mIsConnected = true; mPvdDataStream = PvdDataStream::create(mPvd); sendEntireSDK(); } void PvdPhysicsClient::onPvdDisconnected() { if(!mIsConnected) return; mIsConnected = false; mPvdDataStream->release(); mPvdDataStream = NULL; } void PvdPhysicsClient::flush() { } void PvdPhysicsClient::sendEntireSDK() { PxPhysics& physics = PxGetPhysics(); mMetaDataBinding.registerSDKProperties(*mPvdDataStream); mPvdDataStream->createInstance(&physics); mPvdDataStream->setIsTopLevelUIElement(&physics, true); mMetaDataBinding.sendAllProperties(*mPvdDataStream, physics); #define SEND_BUFFER_GROUP(type, name) \ { \ physx::PxArray<type*> buffers; \ PxU32 numBuffers = physics.getNb##name(); \ buffers.resize(numBuffers); \ physics.get##name(buffers.begin(), numBuffers); \ for(PxU32 i = 0; i < numBuffers; i++) \ { \ if(mPvd->registerObject(buffers[i])) \ createPvdInstance(buffers[i]); \ } \ } SEND_BUFFER_GROUP(PxMaterial, Materials); SEND_BUFFER_GROUP(PxTriangleMesh, TriangleMeshes); SEND_BUFFER_GROUP(PxConvexMesh, ConvexMeshes); SEND_BUFFER_GROUP(PxTetrahedronMesh, TetrahedronMeshes); SEND_BUFFER_GROUP(PxHeightField, HeightFields); } void PvdPhysicsClient::destroyPvdInstance(const PxPhysics* physics) { if(mPvdDataStream) mPvdDataStream->destroyInstance(physics); } void PvdPhysicsClient::createPvdInstance(const PxTriangleMesh* triMesh) { mMetaDataBinding.createInstance(*mPvdDataStream, *triMesh, PxGetPhysics()); } void PvdPhysicsClient::destroyPvdInstance(const PxTriangleMesh* triMesh) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *triMesh, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxTetrahedronMesh* tetMesh) { mMetaDataBinding.createInstance(*mPvdDataStream, *tetMesh, PxGetPhysics()); } void PvdPhysicsClient::destroyPvdInstance(const PxTetrahedronMesh* tetMesh) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *tetMesh, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxConvexMesh* convexMesh) { mMetaDataBinding.createInstance(*mPvdDataStream, *convexMesh, PxGetPhysics()); } void PvdPhysicsClient::destroyPvdInstance(const PxConvexMesh* convexMesh) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *convexMesh, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxHeightField* heightField) { mMetaDataBinding.createInstance(*mPvdDataStream, *heightField, PxGetPhysics()); } void PvdPhysicsClient::destroyPvdInstance(const PxHeightField* heightField) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *heightField, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxMaterial* mat) { mMetaDataBinding.createInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::updatePvdProperties(const PxMaterial* mat) { mMetaDataBinding.sendAllProperties(*mPvdDataStream, *mat); } void PvdPhysicsClient::destroyPvdInstance(const PxMaterial* mat) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxFEMSoftBodyMaterial* mat) { mMetaDataBinding.createInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::updatePvdProperties(const PxFEMSoftBodyMaterial* mat) { mMetaDataBinding.sendAllProperties(*mPvdDataStream, *mat); } void PvdPhysicsClient::destroyPvdInstance(const PxFEMSoftBodyMaterial* mat) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxFEMClothMaterial* /*mat*/) { // jcarius: Commented-out until FEMCloth is not under construction anymore PX_ASSERT(0); // mMetaDataBinding.createInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::updatePvdProperties(const PxFEMClothMaterial* /*mat*/) { // jcarius: Commented-out until FEMCloth is not under construction anymore PX_ASSERT(0); // mMetaDataBinding.sendAllProperties(*mPvdDataStream, *mat); } void PvdPhysicsClient::destroyPvdInstance(const PxFEMClothMaterial* /*mat*/) { // jcarius: Commented-out until FEMCloth is not under construction anymore PX_ASSERT(0); // mMetaDataBinding.destroyInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::createPvdInstance(const PxPBDMaterial* mat) { mMetaDataBinding.createInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::updatePvdProperties(const PxPBDMaterial* mat) { mMetaDataBinding.sendAllProperties(*mPvdDataStream, *mat); } void PvdPhysicsClient::destroyPvdInstance(const PxPBDMaterial* mat) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *mat, PxGetPhysics()); } void PvdPhysicsClient::onMeshFactoryBufferRelease(const PxBase* object, PxType typeID) { if(!mIsConnected || !mPvd) return; if(mPvd->unRegisterObject(object)) { switch(typeID) { case PxConcreteType::eHEIGHTFIELD: destroyPvdInstance(static_cast<const PxHeightField*>(object)); break; case PxConcreteType::eCONVEX_MESH: destroyPvdInstance(static_cast<const PxConvexMesh*>(object)); break; case PxConcreteType::eTRIANGLE_MESH_BVH33: case PxConcreteType::eTRIANGLE_MESH_BVH34: destroyPvdInstance(static_cast<const PxTriangleMesh*>(object)); break; case PxConcreteType::eTETRAHEDRON_MESH: destroyPvdInstance(static_cast<const PxTetrahedronMesh*>(object)); break; default: break; } } } void PvdPhysicsClient::reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) { if(mIsConnected) { mPvdDataStream->sendErrorMessage(code, message, file, PxU32(line)); } } #endif // PX_SUPPORT_PVD
8,266
C++
28.952898
107
0.755021
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpScene.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 "NpScene.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationTendon.h" #include "NpArticulationSensor.h" #include "NpAggregate.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #include "NpFEMCloth.h" #include "NpHairSystem.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #endif #include "ScArticulationSim.h" #include "ScArticulationTendonSim.h" #include "CmCollection.h" #include "PxsSimulationController.h" #include "common/PxProfileZone.h" #include "BpBroadPhase.h" #include "BpAABBManagerBase.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; // enable thread checks in all debug builds #if PX_DEBUG || PX_CHECKED #define NP_ENABLE_THREAD_CHECKS 1 #else #define NP_ENABLE_THREAD_CHECKS 0 #endif using namespace Sq; using namespace Gu; /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_PVD #define CREATE_PVD_INSTANCE(obj) \ { \ if(mScenePvdClient.checkPvdDebugFlag()) \ { \ PX_PROFILE_ZONE("PVD.createPVDInstance", mScene.getContextId());\ mScenePvdClient.createPvdInstance(obj); \ } \ } #define RELEASE_PVD_INSTANCE(obj) \ { \ if(mScenePvdClient.checkPvdDebugFlag()) \ { \ PX_PROFILE_ZONE("PVD.releasePVDInstance", mScene.getContextId());\ mScenePvdClient.releasePvdInstance(obj); \ } \ } #define UPDATE_PVD_PROPERTIES(obj) \ { \ if(mScenePvdClient.checkPvdDebugFlag()) \ { \ PX_PROFILE_ZONE("PVD.updatePVDProperties", mScene.getContextId());\ mScenePvdClient.updatePvdProperties(obj); \ } \ } #define PVD_ORIGIN_SHIFT(shift) \ { \ if(mScenePvdClient.checkPvdDebugFlag()) \ { \ PX_PROFILE_ZONE("PVD.originShift", mScene.getContextId());\ mScenePvdClient.originShift(shift); \ } \ } #else #define CREATE_PVD_INSTANCE(obj) {} #define RELEASE_PVD_INSTANCE(obj) {} #define UPDATE_PVD_PROPERTIES(obj) {} #define PVD_ORIGIN_SHIFT(shift){} #endif /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE bool removeFromSceneCheck(NpScene* npScene, PxScene* scene, const char* name) { if(scene == static_cast<PxScene*>(npScene)) return true; else return PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "%s not assigned to scene or assigned to another scene. Call will be ignored!", name); } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_OMNI_PVD static void SleepingStateChanged(PxRigidDynamic& actor, bool sleeping) { OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, isSleeping, actor, sleeping) } #endif NpScene::NpScene(const PxSceneDesc& desc, NpPhysics& physics) : mNpSQ (desc, #if PX_SUPPORT_PVD &mScenePvdClient, #else NULL, #endif getContextId()), mSceneQueriesStaticPrunerUpdate (getContextId(), 0, "NpScene.sceneQueriesStaticPrunerUpdate"), mSceneQueriesDynamicPrunerUpdate(getContextId(), 0, "NpScene.sceneQueriesDynamicPrunerUpdate"), mRigidDynamics ("sceneRigidDynamics"), mRigidStatics ("sceneRigidStatics"), mArticulations ("sceneArticulations"), mAggregates ("sceneAggregates"), mSanityBounds (desc.sanityBounds), mNbClients (1), //we always have the default client. mSceneCompletion (getContextId(), mPhysicsDone), mCollisionCompletion (getContextId(), mCollisionDone), mSceneQueriesCompletion (getContextId(), mSceneQueriesDone), mSceneExecution (getContextId(), 0, "NpScene.execution"), mSceneCollide (getContextId(), 0, "NpScene.collide"), mSceneAdvance (getContextId(), 0, "NpScene.solve"), mStaticBuildStepHandle (NULL), mDynamicBuildStepHandle (NULL), mControllingSimulation (false), mIsAPIReadForbidden (false), mIsAPIWriteForbidden (false), mSimThreadStackSize (0), mConcurrentWriteCount (0), mConcurrentReadCount (0), mConcurrentErrorCount (0), mCurrentWriter (0), mSQUpdateRunning (false), mBetweenFetchResults (false), mBuildFrozenActors (false), mScene (desc, getContextId()), #if PX_SUPPORT_PVD mScenePvdClient (*this), #endif mWakeCounterResetValue (desc.wakeCounterResetValue), mPhysics (physics), mName (NULL) { mGpuDynamicsConfig = desc.gpuDynamicsConfig; mSceneQueriesStaticPrunerUpdate.setObject(this); mSceneQueriesDynamicPrunerUpdate.setObject(this); mPrunerType[0] = desc.staticStructure; mPrunerType[1] = desc.dynamicStructure; mSceneExecution.setObject(this); mSceneCollide.setObject(this); mSceneAdvance.setObject(this); mTaskManager = mScene.getTaskManagerPtr(); mCudaContextManager = mScene.getCudaContextManager(); mThreadReadWriteDepth = PxTlsAlloc(); updatePhysXIndicator(); createInOmniPVD(desc); #if PX_SUPPORT_OMNI_PVD if (NpPhysics::getInstance().mOmniPvdSampler) mScene.mOnSleepingStateChanged = SleepingStateChanged; #endif } NpScene::~NpScene() { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxScene, static_cast<PxScene &>(*this)) // PT: we need to do that one first, now that we don't release the objects anymore. Otherwise we end up with a sequence like: // - actor is part of an aggregate, and part of a scene // - actor gets removed from the scene. This does *not* remove it from the aggregate. // - aggregate gets removed from the scene, sees that one contained actor ain't in the scene => we get a warning message PxU32 aggregateCount = mAggregates.size(); while(aggregateCount--) removeAggregate(*mAggregates.getEntries()[aggregateCount], false); PxU32 rigidDynamicCount = mRigidDynamics.size(); while(rigidDynamicCount--) removeRigidDynamic(*mRigidDynamics[rigidDynamicCount], false, true); PxU32 rigidStaticCount = mRigidStatics.size(); while(rigidStaticCount--) removeRigidStatic(*mRigidStatics[rigidStaticCount], false, true); PxU32 articCount = mArticulations.size(); while(articCount--) removeArticulation(*mArticulations.getEntries()[articCount], false); #if PX_SUPPORT_GPU_PHYSX PxU32 particleCount = mPBDParticleSystems.size(); while(particleCount--) removeParticleSystem(*mPBDParticleSystems.getEntries()[particleCount], false); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION particleCount = mFLIPParticleSystems.size(); while (particleCount--) removeParticleSystem(*mFLIPParticleSystems.getEntries()[particleCount], false); particleCount = mMPMParticleSystems.size(); while (particleCount--) removeParticleSystem(*mMPMParticleSystems.getEntries()[particleCount], false); #endif PxU32 softBodyCount = mSoftBodies.size(); while(softBodyCount--) removeSoftBody(*mSoftBodies.getEntries()[softBodyCount], false); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxU32 femClothCount = mFEMCloths.size(); while (femClothCount--) removeFEMCloth(*mFEMCloths.getEntries()[femClothCount], false); PxU32 hairSystemsCount = mHairSystems.size(); while (hairSystemsCount--) removeHairSystem(*mHairSystems.getEntries()[hairSystemsCount], false); #endif #endif bool unlock = mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK; #if PX_SUPPORT_PVD mNpSQ.getSingleSqCollector().release(); #endif #if PX_SUPPORT_PVD mScenePvdClient.releasePvdInstance(); #endif mScene.release(); // unlock the lock taken in release(), must unlock before // mRWLock is destroyed otherwise behavior is undefined if (unlock) unlockWrite(); PxTlsFree(mThreadReadWriteDepth); } /////////////////////////////////////////////////////////////////////////////// void NpScene::release() { // need to acquire lock for release, note this is unlocked in the destructor if (mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK) lockWrite(PX_FL); // It will be hard to do a write check here since all object release calls in the scene destructor do it and would mess // up the test. If we really want it on scene destruction as well, we need to either have internal and external release // calls or come up with a different approach (for example using thread ID as detector variable). if(getSimulationStage() != Sc::SimulationStage::eCOMPLETE) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::release(): Scene is still being simulated! PxScene::fetchResults() is called implicitly."); if(getSimulationStage() == Sc::SimulationStage::eCOLLIDE) fetchCollision(true); if(getSimulationStage() == Sc::SimulationStage::eFETCHCOLLIDE) // need to call getSimulationStage() again beacause fetchCollision() might change the value. { // this is for split sim advance(NULL); } fetchResults(true, NULL); } NpPhysics::getInstance().releaseSceneInternal(*this); } /////////////////////////////////////////////////////////////////////////////// bool NpScene::loadFromDesc(const PxSceneDesc& desc) { if (desc.limits.maxNbBodies) mRigidDynamics.reserve(desc.limits.maxNbBodies); if (desc.limits.maxNbActors) mRigidStatics.reserve(desc.limits.maxNbActors); // to be consistent with code below (but to match previous interpretation // it would rather be desc.limits.maxNbActors - desc.limits.maxNbBodies) mScene.preAllocate(desc.limits.maxNbActors, desc.limits.maxNbBodies, desc.limits.maxNbStaticShapes, desc.limits.maxNbDynamicShapes); userData = desc.userData; return true; } /////////////////////////////////////////////////////////////////////////////// void NpScene::setGravity(const PxVec3& g) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setGravity() not allowed while simulation is running. Call will be ignored.") mScene.setGravity(g); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, gravity, static_cast<PxScene&>(*this), g) updatePvdProperties(); } PxVec3 NpScene::getGravity() const { NP_READ_CHECK(this); return mScene.getGravity(); } /////////////////////////////////////////////////////////////////////////////// void NpScene::setBounceThresholdVelocity(const PxReal t) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((t>0.0f), "PxScene::setBounceThresholdVelocity(): threshold value has to be in (0, PX_MAX_F32)!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setBounceThresholdVelocity() not allowed while simulation is running. Call will be ignored.") mScene.setBounceThresholdVelocity(t); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, bounceThresholdVelocity, static_cast<PxScene&>(*this), t) } PxReal NpScene::getBounceThresholdVelocity() const { NP_READ_CHECK(this) return mScene.getBounceThresholdVelocity(); } /////////////////////////////////////////////////////////////////////////////// void NpScene::setLimits(const PxSceneLimits& limits) { NP_WRITE_CHECK(this); if (limits.maxNbBodies) mRigidDynamics.reserve(limits.maxNbBodies); if (limits.maxNbActors) mRigidStatics.reserve(limits.maxNbActors); // to be consistent with code below (but to match previous interpretation // it would rather be desc.limits.maxNbActors - desc.limits.maxNbBodies) mScene.preAllocate(limits.maxNbActors, limits.maxNbBodies, limits.maxNbStaticShapes, limits.maxNbDynamicShapes); mScene.setLimits(limits); // PT: TODO: there is no guarantee that all simulation shapes will be SQ shapes so this is wrong getSQAPI().preallocate(PX_SCENE_PRUNER_STATIC, limits.maxNbStaticShapes); getSQAPI().preallocate(PX_SCENE_PRUNER_DYNAMIC, limits.maxNbDynamicShapes); updatePvdProperties(); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbActors, static_cast<PxScene&>(*this), limits.maxNbActors) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbBodies, static_cast<PxScene&>(*this), limits.maxNbBodies) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbStaticShapes, static_cast<PxScene&>(*this), limits.maxNbStaticShapes) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbDynamicShapes, static_cast<PxScene&>(*this), limits.maxNbDynamicShapes) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbAggregates, static_cast<PxScene&>(*this), limits.maxNbAggregates) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbConstraints, static_cast<PxScene&>(*this), limits.maxNbConstraints) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbRegions, static_cast<PxScene&>(*this), limits.maxNbRegions) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbBroadPhaseOverlaps, static_cast<PxScene&>(*this), limits.maxNbBroadPhaseOverlaps) OMNI_PVD_WRITE_SCOPE_END } ////////////////////////////////////////////////////////////////////////// PxSceneLimits NpScene::getLimits() const { NP_READ_CHECK(this); return mScene.getLimits(); } /////////////////////////////////////////////////////////////////////////////// void NpScene::setFlag(PxSceneFlag::Enum flag, bool value) { NP_WRITE_CHECK(this); // this call supports mutable flags only PX_CHECK_AND_RETURN(PxSceneFlags(flag) & PxSceneFlags(PxSceneFlag::eMUTABLE_FLAGS), "PxScene::setFlag: This flag is not mutable - you can only set it once in PxSceneDesc at startup!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setFlag() not allowed while simulation is running. Call will be ignored.") PxSceneFlags currentFlags = mScene.getFlags(); if(value) currentFlags |= flag; else currentFlags &= ~PxSceneFlags(flag); mScene.setFlags(currentFlags); const bool pcm = (currentFlags & PxSceneFlag::eENABLE_PCM); mScene.setPCM(pcm); const bool contactCache = !(currentFlags & PxSceneFlag::eDISABLE_CONTACT_CACHE); mScene.setContactCache(contactCache); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, flags, static_cast<PxScene&>(*this), getFlags()) } PxSceneFlags NpScene::getFlags() const { NP_READ_CHECK(this); return mScene.getFlags(); } void NpScene::setName(const char* name) { mName = name; #if PX_SUPPORT_OMNI_PVD PxScene & s = *this; streamSceneName(s, mName); #endif } const char* NpScene::getName() const { return mName; } /////////////////////////////////////////////////////////////////////////////// template<class actorT> static PX_NOINLINE bool doRigidActorChecks(const actorT& actor, const PruningStructure* ps, const NpScene* scene) { if(!ps && actor.getShapeManager().getPruningStructure()) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActors(): actor is in a pruning structure and cannot be added to a scene directly, use addActors(const PxPruningStructure& )"); if(actor.getNpScene()) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActors(): Actor already assigned to a scene. Call will be ignored!"); #if PX_CHECKED if(!actor.checkConstraintValidity()) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActors(): actor has invalid constraint and may not be added to scene"); scene->checkPositionSanity(actor, actor.getGlobalPose(), "PxScene::addActors"); #else PX_UNUSED(scene); #endif return true; } // PT: make sure we always add to array and set the array index properly / at the same time template<class T> static PX_FORCE_INLINE void addRigidActorToArray(T& a, PxArray<T*>& rigidActors, Cm::IDPool& idPool) { a.setRigidActorArrayIndex(rigidActors.size()); rigidActors.pushBack(&a); a.setRigidActorSceneIndex(idPool.getNewID()); } bool NpScene::addActor(PxActor& actor, const PxBVH* bvh) { PX_PROFILE_ZONE("API.addActor", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::addActor() not allowed while simulation is running. Call will be ignored.", false) PX_SIMD_GUARD; NpScene* scene = NpActor::getFromPxActor(actor).getNpScene(); if (scene) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActor(): Actor already assigned to a scene. Call will be ignored!"); return addActorInternal(actor, bvh); } bool NpScene::addActorInternal(PxActor& actor, const PxBVH* bvh) { if(bvh) { PxRigidActor* ra = &static_cast<PxRigidActor&>(actor); if(!ra || bvh->getNbBounds() == 0 || bvh->getNbBounds() > ra->getNbShapes()) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidActor::setBVH: BVH is empty or does not match shapes in the actor."); } PxType type = actor.getConcreteType(); switch (type) { case (PxConcreteType::eRIGID_STATIC): { NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor); if (!doRigidActorChecks(npStatic, NULL, this)) return false; return addRigidStatic(npStatic, static_cast<const BVH*>(bvh)); } case (PxConcreteType::eRIGID_DYNAMIC): { NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor); if (!doRigidActorChecks(npDynamic, NULL, this)) return false; return addRigidDynamic(npDynamic, static_cast<const BVH*>(bvh)); } case (PxConcreteType::eARTICULATION_LINK): { return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::addActor(): Individual articulation links can not be added to the scene"); } #if PX_SUPPORT_GPU_PHYSX case (PxConcreteType::eSOFT_BODY): { return addSoftBody(static_cast<PxSoftBody&>(actor)); } case (PxConcreteType::eFEM_CLOTH): { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION return addFEMCloth(static_cast<PxFEMCloth&>(actor)); #else return false; #endif } case (PxConcreteType::ePBD_PARTICLESYSTEM): case (PxConcreteType::eFLIP_PARTICLESYSTEM): case (PxConcreteType::eMPM_PARTICLESYSTEM): { return addParticleSystem(static_cast<PxParticleSystem&>(actor)); } case (PxConcreteType::eHAIR_SYSTEM): { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION return addHairSystem(static_cast<PxHairSystem&>(actor)); #else return false; #endif } #endif default: PX_ASSERT(false); // should not happen return false; } } static void updateScStateAndSetupSq(NpScene* scene, PxSceneQuerySystem& sqManager, NpActor& npActor, const PxRigidActor& actor, NpShapeManager& shapeManager, bool actorDynamic, const PxBounds3* bounds, const PruningStructure* ps) { npActor.setNpScene(scene); NpShape*const * shapes = shapeManager.getShapes(); PxU32 nbShapes = shapeManager.getNbShapes(); for(PxU32 i=0;i<nbShapes;i++) shapes[i]->setSceneIfExclusive(scene); shapeManager.setupAllSceneQuery(sqManager, npActor, actor, ps, bounds, actorDynamic); } bool NpScene::addActors(PxActor*const* actors, PxU32 nbActors) { return addActorsInternal(actors, nbActors, NULL); } bool NpScene::addActors(const PxPruningStructure& ps) { const PruningStructure& prunerStructure = static_cast<const PruningStructure&>(ps); if(!prunerStructure.isValid()) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::addActors(): Provided pruning structure is not valid."); return addActorsInternal(prunerStructure.getActors(), prunerStructure.getNbActors(), &prunerStructure); } ///////////// bool NpScene::addActorsInternal(PxActor*const* PX_RESTRICT actors, PxU32 nbActors, const PruningStructure* ps) { NP_WRITE_CHECK(this); PX_PROFILE_ZONE("API.addActors", getContextId()); PX_SIMD_GUARD; if(getSimulationStage() != Sc::SimulationStage::eCOMPLETE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActors() not allowed while simulation is running. Call will be ignored."); Sc::Scene& scScene = mScene; PxU32 actorsDone; Sc::BatchInsertionState scState; scScene.startBatchInsertion(scState); scState.staticActorOffset = ptrdiff_t(NpRigidStatic::getCoreOffset()); scState.staticShapeTableOffset = ptrdiff_t(NpRigidStatic::getNpShapeManagerOffset() + NpShapeManager::getShapeTableOffset()); scState.dynamicActorOffset = ptrdiff_t(NpRigidDynamic::getCoreOffset()); scState.dynamicShapeTableOffset = ptrdiff_t(NpRigidDynamic::getNpShapeManagerOffset() + NpShapeManager::getShapeTableOffset()); scState.shapeOffset = ptrdiff_t(NpShape::getCoreOffset()); PxInlineArray<PxBounds3, 8> shapeBounds; for(actorsDone=0; actorsDone<nbActors; actorsDone++) { if(actorsDone+1<nbActors) PxPrefetch(actors[actorsDone+1], sizeof(NpRigidDynamic)); // worst case: PxRigidStatic is smaller const PxType type = actors[actorsDone]->getConcreteType(); if(type == PxConcreteType::eRIGID_STATIC) { NpRigidStatic& a = *static_cast<NpRigidStatic*>(actors[actorsDone]); if(!doRigidActorChecks(a, ps, this)) break; if(!(a.getCore().getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) { shapeBounds.resizeUninitialized(a.NpRigidStatic::getNbShapes()+1); // PT: +1 for safe reads in addPrunerData/inflateBounds scScene.addStatic(&a, scState, shapeBounds.begin()); // PT: must call this one before doing SQ calls addRigidActorToArray(a, mRigidStatics, mRigidActorIndexPool); updateScStateAndSetupSq(this, getSQAPI(), a, a, a.getShapeManager(), false, shapeBounds.begin(), ps); a.addConstraintsToScene(); } else addRigidStatic(a, NULL, ps); } else if(type == PxConcreteType::eRIGID_DYNAMIC) { NpRigidDynamic& a = *static_cast<NpRigidDynamic*>(actors[actorsDone]); if(!doRigidActorChecks(a, ps, this)) break; if(!(a.getCore().getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) { shapeBounds.resizeUninitialized(a.NpRigidDynamic::getNbShapes()+1); // PT: +1 for safe reads in addPrunerData/inflateBounds scScene.addBody(&a, scState, shapeBounds.begin(), false); // PT: must call this one before doing SQ calls addRigidActorToArray(a, mRigidDynamics, mRigidActorIndexPool); updateScStateAndSetupSq(this, getSQAPI(), a, a, a.getShapeManager(), true, shapeBounds.begin(), ps); a.addConstraintsToScene(); } else addRigidDynamic(a, NULL, ps); } else { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "PxScene::addActors(): Batch addition is not permitted for this actor type, aborting at index %u!", actorsDone); break; } } // merge sq PrunerStructure if(ps) { getSQAPI().merge(*ps); } scScene.finishBatchInsertion(scState); // if we failed, still complete everything for the successful inserted actors before backing out #if PX_SUPPORT_PVD for(PxU32 i=0;i<actorsDone;i++) { if ((actors[i]->getConcreteType()==PxConcreteType::eRIGID_STATIC) && (!(static_cast<NpRigidStatic*>(actors[i])->getCore().getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)))) mScenePvdClient.addStaticAndShapesToPvd(*static_cast<NpRigidStatic*>(actors[i])); else if ((actors[i]->getConcreteType() == PxConcreteType::eRIGID_DYNAMIC) && (!(static_cast<NpRigidDynamic*>(actors[i])->getCore().getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)))) mScenePvdClient.addBodyAndShapesToPvd(*static_cast<NpRigidDynamic*>(actors[i])); } #endif if(actorsDone<nbActors) // Everything is consistent up to the failure point, so just use removeActor to back out gracefully if necessary { for(PxU32 j=0;j<actorsDone;j++) removeActorInternal(*actors[j], false, true); return false; } return true; } /////////////////////////////////////////////////////////////////////////////// template<typename T> static PX_FORCE_INLINE void removeFromRigidActorListT(T& rigidActor, PxArray<T*>& rigidActorList, Cm::IDPool& idPool) { const PxU32 index = rigidActor.getRigidActorArrayIndex(); PX_ASSERT(index != 0xFFFFFFFF); PX_ASSERT(index < rigidActorList.size()); const PxU32 size = rigidActorList.size() - 1; rigidActorList.replaceWithLast(index); if (size && size != index) { T& swappedActor = *rigidActorList[index]; swappedActor.setRigidActorArrayIndex(index); } idPool.freeID(rigidActor.getRigidActorSceneIndex()); rigidActor.setRigidActorSceneIndex(NP_UNUSED_BASE_INDEX); } // PT: TODO: inline this one in the header for consistency void NpScene::removeFromRigidDynamicList(NpRigidDynamic& rigidDynamic) { removeFromRigidActorListT(rigidDynamic, mRigidDynamics, mRigidActorIndexPool); } // PT: TODO: inline this one in the header for consistency void NpScene::removeFromRigidStaticList(NpRigidStatic& rigidStatic) { removeFromRigidActorListT(rigidStatic, mRigidStatics, mRigidActorIndexPool); } /////////////////////////////////////////////////////////////////////////////// template<class ActorT> static void removeActorT(NpScene* npScene, ActorT& actor, PxArray<ActorT*>& actors, bool wakeOnLostTouch) { const PxActorFlags actorFlags = actor.getCore().getActorFlags(); if(actor.getShapeManager().getNbShapes()) PxPrefetch(actor.getShapeManager().getShapes()[0],sizeof(NpShape)); PxPrefetch(actors[actors.size()-1],sizeof(ActorT)); const bool noSim = actorFlags.isSet(PxActorFlag::eDISABLE_SIMULATION); if (!noSim) actor.removeConstraintsFromScene(); actor.getShapeManager().teardownAllSceneQuery(npScene->getSQAPI(), actor); npScene->scRemoveActor(actor, wakeOnLostTouch, noSim); removeFromRigidActorListT(actor, actors, npScene->mRigidActorIndexPool); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxScene, actors, static_cast<PxScene &>(*npScene), static_cast<PxActor &>(actor)) } void NpScene::removeActors(PxActor*const* PX_RESTRICT actors, PxU32 nbActors, bool wakeOnLostTouch) { PX_PROFILE_ZONE("API.removeActors", getContextId()); NP_WRITE_CHECK(this); Sc::Scene& scScene = mScene; // resize the bitmap so it does not allocate each remove actor call scScene.resizeReleasedBodyIDMaps(mRigidDynamics.size() + mRigidStatics.size(), nbActors); Sc::BatchRemoveState removeState; scScene.setBatchRemove(&removeState); for(PxU32 actorsDone=0; actorsDone<nbActors; actorsDone++) { if(actorsDone+1<nbActors) PxPrefetch(actors[actorsDone+1], sizeof(NpRigidDynamic)); // worst case: PxRigidStatic is smaller PxType type = actors[actorsDone]->getConcreteType(); if(!removeFromSceneCheck(this, actors[actorsDone]->getScene(), "PxScene::removeActors(): Actor")) break; removeState.bufferedShapes.clear(); removeState.removedShapes.clear(); if(type == PxConcreteType::eRIGID_STATIC) { NpRigidStatic& actor = *static_cast<NpRigidStatic*>(actors[actorsDone]); removeActorT(this, actor, mRigidStatics, wakeOnLostTouch); } else if(type == PxConcreteType::eRIGID_DYNAMIC) { NpRigidDynamic& actor = *static_cast<NpRigidDynamic*>(actors[actorsDone]); removeActorT(this, actor, mRigidDynamics, wakeOnLostTouch); } else { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "PxScene::removeActor(): Batch removal is not supported for this actor type, aborting at index %u!", actorsDone); break; } } scScene.setBatchRemove(NULL); } void NpScene::removeActor(PxActor& actor, bool wakeOnLostTouch) { if(0) // PT: repro for PX-1999 { PxActor* toRemove = &actor; removeActors(&toRemove, 1, wakeOnLostTouch); return; } PX_PROFILE_ZONE("API.removeActor", getContextId()); NP_WRITE_CHECK(this); if(removeFromSceneCheck(this, actor.getScene(), "PxScene::removeActor(): Actor")) removeActorInternal(actor, wakeOnLostTouch, true); } void NpScene::removeActorInternal(PxActor& actor, bool wakeOnLostTouch, bool removeFromAggregate) { switch(actor.getType()) { case PxActorType::eRIGID_STATIC: { NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor); removeRigidStatic(npStatic, wakeOnLostTouch, removeFromAggregate); } break; case PxActorType::eRIGID_DYNAMIC: { NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor); removeRigidDynamic(npDynamic, wakeOnLostTouch, removeFromAggregate); } break; case PxActorType::eARTICULATION_LINK: { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::removeActor(): Individual articulation links can not be removed from the scene"); } break; #if PX_SUPPORT_GPU_PHYSX case PxActorType::eSOFTBODY: { NpSoftBody& npSoftBody = static_cast<NpSoftBody&>(actor); removeSoftBody(npSoftBody, wakeOnLostTouch); } break; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION case PxActorType::eFEMCLOTH: { NpFEMCloth& npFEMCloth= static_cast<NpFEMCloth&>(actor); removeFEMCloth(npFEMCloth, wakeOnLostTouch); } break; #endif case PxActorType::ePBD_PARTICLESYSTEM: { PxPBDParticleSystem& npParticleSystem = static_cast<PxPBDParticleSystem&>(actor); removeParticleSystem(npParticleSystem, wakeOnLostTouch); } break; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION case PxActorType::eFLIP_PARTICLESYSTEM: { PxFLIPParticleSystem& npParticleSystem = static_cast<PxFLIPParticleSystem&>(actor); removeParticleSystem(npParticleSystem, wakeOnLostTouch); } break; case PxActorType::eMPM_PARTICLESYSTEM: { PxMPMParticleSystem& npParticleSystem = static_cast<PxMPMParticleSystem&>(actor); removeParticleSystem(npParticleSystem, wakeOnLostTouch); } break; case PxActorType::eHAIRSYSTEM: { NpHairSystem& npHairSystem = static_cast<NpHairSystem&>(actor); removeHairSystem(npHairSystem, wakeOnLostTouch); } break; #endif #endif default: PX_ASSERT(0); } } /////////////////////////////////////////////////////////////////////////////// template<class T> static PX_FORCE_INLINE bool addRigidActorT(T& rigidActor, PxArray<T*>& rigidActorList, NpScene* scene, const BVH* bvh, const PruningStructure* ps) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(scene, "PxScene::addActor() not allowed while simulation is running. Call will be ignored.", false) #if PX_CHECKED if (!scene->getScScene().isUsingGpuDynamics()) { for (PxU32 i = 0; i < rigidActor.getShapeManager().getNbShapes(); ++i) { const NpShape* shape = rigidActor.getShapeManager().getShapes()[i]; const PxGeometry& geom = shape->getGeometry(); const PxGeometryType::Enum t = geom.getType(); if (t == PxGeometryType::eTRIANGLEMESH) { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); if (triGeom.triangleMesh->getSDF() != NULL) { return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addRigidActor(): Rigid actors with SDFs are currently only supported with GPU-accelerated scenes!"); } } } } #endif const bool isNoSimActor = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION); PxBounds3 bounds[8+1]; // PT: +1 for safe reads in addPrunerData/inflateBounds const bool canReuseBounds = !isNoSimActor && rigidActor.getShapeManager().getNbShapes()<=8; PxBounds3* uninflatedBounds = canReuseBounds ? bounds : NULL; scene->scAddActor(rigidActor, isNoSimActor, uninflatedBounds, bvh); // PT: must call this one before doing SQ calls addRigidActorToArray(rigidActor, rigidActorList, scene->mRigidActorIndexPool); // PT: SQ_CODEPATH1 rigidActor.getShapeManager().setupAllSceneQuery(scene->getSQAPI(), rigidActor, ps, uninflatedBounds, bvh); if(!isNoSimActor) rigidActor.addConstraintsToScene(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, worldBounds, static_cast<PxActor &>(rigidActor), rigidActor.getWorldBounds()) OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxScene, actors, static_cast<PxScene &>(*scene), static_cast<PxActor &>(rigidActor)) return true; } bool NpScene::addRigidStatic(NpRigidStatic& actor, const BVH* bvh, const PruningStructure* ps) { return addRigidActorT(actor, mRigidStatics, this, bvh, ps); } bool NpScene::addRigidDynamic(NpRigidDynamic& body, const BVH* bvh, const PruningStructure* ps) { return addRigidActorT(body, mRigidDynamics, this, bvh, ps); } /////////////////////////////////////////////////////////////////////////////// template<class T> static PX_FORCE_INLINE void removeRigidActorT(T& rigidActor, NpScene* scene, bool wakeOnLostTouch, bool removeFromAggregate) { PX_ASSERT(rigidActor.getNpScene() == scene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(scene, "PxScene::removeActor() not allowed while simulation is running. Call will be ignored.") const bool isNoSimActor = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION); if(removeFromAggregate) { PxU32 index = 0xffffffff; NpAggregate* aggregate = rigidActor.getNpAggregate(index); if(aggregate) { aggregate->removeActorAndReinsert(rigidActor, false); PX_ASSERT(!rigidActor.getAggregate()); } } rigidActor.getShapeManager().teardownAllSceneQuery(scene->getSQAPI(), rigidActor); if(!isNoSimActor) rigidActor.removeConstraintsFromScene(); scene->scRemoveActor(rigidActor, wakeOnLostTouch, isNoSimActor); scene->removeFromRigidActorList(rigidActor); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxScene, actors, static_cast<PxScene &>(*scene), static_cast<PxActor &>(rigidActor)) } void NpScene::removeRigidStatic(NpRigidStatic& actor, bool wakeOnLostTouch, bool removeFromAggregate) { removeRigidActorT(actor, this, wakeOnLostTouch, removeFromAggregate); } void NpScene::removeRigidDynamic(NpRigidDynamic& body, bool wakeOnLostTouch, bool removeFromAggregate) { removeRigidActorT(body, this, wakeOnLostTouch, removeFromAggregate); } /////////////////////////////////////////////////////////////////////////////// bool NpScene::addArticulation(PxArticulationReducedCoordinate& articulation) { PX_PROFILE_ZONE("API.addArticulation", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN_VAL(articulation.getNbLinks()>0, "PxScene::addArticulation: Empty articulations may not be added to a scene.", false); NpArticulationReducedCoordinate& npa = static_cast<NpArticulationReducedCoordinate&>(articulation); // check that any tendons are not empty #if PX_CHECKED for(PxU32 i = 0u; i < articulation.getNbFixedTendons(); ++i) { PX_CHECK_AND_RETURN_VAL(npa.getFixedTendon(i)->getNbTendonJoints() > 0u, "PxScene::addArticulation: Articulations with empty fixed tendons may not be added to a scene.", false) } for(PxU32 i = 0u; i < articulation.getNbSpatialTendons(); ++i) { PX_CHECK_AND_RETURN_VAL(npa.getSpatialTendon(i)->getNbAttachments() > 0u, "PxScene::addArticulation: Articulations with empty spatial tendons may not be added to a scene.", false) } #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::addArticulation() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if(this->getFlags() & PxSceneFlag::eENABLE_GPU_DYNAMICS && articulation.getConcreteType() != PxConcreteType::eARTICULATION_REDUCED_COORDINATE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addArticulation(): Only Reduced coordinate articulations are currently supported when PxSceneFlag::eENABLE_GPU_DYNAMICS is set!"); if(getSimulationStage() != Sc::SimulationStage::eCOMPLETE && articulation.getConcreteType() == PxConcreteType::eARTICULATION_REDUCED_COORDINATE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addArticulation(): this call is not allowed while the simulation is running. Call will be ignored!"); if(!npa.getNpScene()) return addArticulationInternal(articulation); else return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addArticulation(): Articulation already assigned to a scene. Call will be ignored!"); } static void checkArticulationLink(NpScene* scene, NpArticulationLink* link) { #if PX_CHECKED scene->checkPositionSanity(*link, link->getGlobalPose(), "PxScene::addArticulation or PxScene::addAggregate"); #else PX_UNUSED(scene); #endif if(link->getMass()==0.0f) { outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxScene::addArticulation(): Articulation link with zero mass added to scene; defaulting mass to 1"); link->setMass(1.0f); } const PxVec3 inertia0 = link->getMassSpaceInertiaTensor(); if(inertia0.x == 0.0f || inertia0.y == 0.0f || inertia0.z == 0.0f) { outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxScene::addArticulation(): Articulation link with zero moment of inertia added to scene; defaulting inertia to (1,1,1)"); link->setMassSpaceInertiaTensor(PxVec3(1.0f, 1.0f, 1.0f)); } } bool NpScene::addSpatialTendonInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim) { const PxU32 nbTendons = npaRC->getNbSpatialTendons(); PxU32 maxAttachments = 0; for (PxU32 i = 0; i < nbTendons; ++i) { NpArticulationSpatialTendon* tendon = npaRC->getSpatialTendon(i); const PxU32 numAttachments = tendon->getNbAttachments(); maxAttachments = PxMax(numAttachments, maxAttachments); } PxU32 stackSize = 1; // Add spatial tendons PX_ALLOCA(attachmentStack, NpArticulationAttachment*, maxAttachments); for (PxU32 i = 0; i < nbTendons; ++i) { NpArticulationSpatialTendon* tendon = npaRC->getSpatialTendon(i); scAddArticulationSpatialTendon(*tendon); //add tendon sim to articulation sim Sc::ArticulationSpatialTendonSim* tendonSim = tendon->getTendonCore().getSim(); scArtSim->addTendon(tendonSim); const PxU32 numAttachments = tendon->getNbAttachments(); // Np check on addArticulation does not allow empty tendons, but assert here. PX_ASSERT(numAttachments); NpArticulationAttachment* attachment = tendon->getAttachment(0); NpArticulationLink* pLink = static_cast<NpArticulationLink*>(attachment->mLink); Sc::ArticulationAttachmentCore& lcore = attachment->getCore(); lcore.mLLLinkIndex = pLink->getLinkIndex(); tendonSim->addAttachment(lcore); attachmentStack[0] = attachment; PxU32 curAttachment = 0; stackSize = 1; while (curAttachment < (numAttachments - 1)) { PX_ASSERT(curAttachment < stackSize); NpArticulationAttachment* p = attachmentStack[curAttachment]; const PxU32 numChildrens = p->getNumChildren(); NpArticulationAttachment*const* children = p->getChildren(); for (PxU32 j = 0; j < numChildrens; j++) { NpArticulationAttachment* child = children[j]; NpArticulationLink* cLink = static_cast<NpArticulationLink*>(child->mLink); Sc::ArticulationAttachmentCore& cCore = child->getCore(); cCore.mLLLinkIndex = cLink->getLinkIndex(); tendonSim->addAttachment(cCore); attachmentStack[stackSize] = child; stackSize++; } curAttachment++; } } return true; } bool NpScene::addFixedTendonInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim) { const PxU32 nbFixedTendons = npaRC->getNbFixedTendons(); PxU32 maxTendonJoints = 0; for (PxU32 i = 0; i < nbFixedTendons; ++i) { NpArticulationFixedTendon* tendon = npaRC->getFixedTendon(i); const PxU32 numTendonJoints = tendon->getNbTendonJoints(); maxTendonJoints = PxMax(numTendonJoints, maxTendonJoints); } PxU32 stackSize = 1; // Add fixed tendon joint PX_ALLOCA(tendonJointStack, NpArticulationTendonJoint*, maxTendonJoints); for (PxU32 i = 0; i < nbFixedTendons; ++i) { NpArticulationFixedTendon* tendon = npaRC->getFixedTendon(i); //addTendon(npaRC->getImpl(), *tendon); scAddArticulationFixedTendon(*tendon); //add tendon sim to articulation sim Sc::ArticulationFixedTendonSim* tendonSim = tendon->getTendonCore().getSim(); scArtSim->addTendon(tendonSim); const PxU32 numTendonJoints = tendon->getNbTendonJoints(); // Np check on addArticulation does not allow empty tendons, but assert here. PX_ASSERT(numTendonJoints); NpArticulationTendonJoint* tendonJoint = tendon->getTendonJoint(0); NpArticulationLink* pLink = static_cast<NpArticulationLink*>(tendonJoint->mLink); Sc::ArticulationTendonJointCore& lcore = tendonJoint->getCore(); lcore.mLLLinkIndex = pLink->getLinkIndex(); //add parent joint tendonSim->addTendonJoint(lcore); tendonJointStack[0] = tendonJoint; PxU32 curTendonJoint = 0; stackSize = 1; while (curTendonJoint < (numTendonJoints - 1)) { PX_ASSERT(curTendonJoint < stackSize); NpArticulationTendonJoint* p = tendonJointStack[curTendonJoint]; const PxU32 numChildrens = p->getNumChildren(); NpArticulationTendonJoint*const* children = p->getChildren(); for (PxU32 j = 0; j < numChildrens; j++) { NpArticulationTendonJoint* child = children[j]; NpArticulationLink* cLink = static_cast<NpArticulationLink*>(child->mLink); Sc::ArticulationTendonJointCore& cCore = child->getCore(); cCore.mLLLinkIndex = cLink->getLinkIndex(); tendonSim->addTendonJoint(cCore); tendonJointStack[stackSize] = child; stackSize++; } curTendonJoint++; } } return true; } bool NpScene::addArticulationSensorInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim) { const PxU32 nbSensors = npaRC->getNbSensors(); for (PxU32 i = 0; i < nbSensors; ++i) { NpArticulationSensor* sensor = npaRC->getSensor(i); scAddArticulationSensor(*sensor); //add tendon sim to articulation sim Sc::ArticulationSensorSim* sensorSim = sensor->getSensorCore().getSim(); scArtSim->addSensor(sensorSim, sensor->getLink()->getLinkIndex()); } return true; } bool NpScene::addArticulationInternal(PxArticulationReducedCoordinate& npa) { // Add root link first const PxU32 nbLinks = npa.getNbLinks(); PX_ASSERT(nbLinks > 0); NpArticulationReducedCoordinate& npaRC = static_cast<NpArticulationReducedCoordinate&>(npa); NpArticulationLink* rootLink = static_cast<NpArticulationLink*>(npaRC.getRoot()); checkArticulationLink(this, rootLink); bool linkTriggersWakeUp = !rootLink->scCheckSleepReadinessBesidesWakeCounter(); addArticulationLinkBody(*rootLink); // Add articulation scAddArticulation(npaRC); if (npaRC.mTopologyChanged) { //increase cache version npaRC.mCacheVersion++; npaRC.mTopologyChanged = false; } Sc::ArticulationCore& scArtCore = npaRC.getCore(); Sc::ArticulationSim* scArtSim = scArtCore.getSim(); PxU32 handle = scArtSim->findBodyIndex(*rootLink->getCore().getSim()); rootLink->setLLIndex(handle); rootLink->setInboundJointDof(0); addArticulationLinkConstraint(*rootLink); // Add links & joints PX_ALLOCA(linkStack, NpArticulationLink*, nbLinks); linkStack[0] = rootLink; PxU32 curLink = 0; PxU32 stackSize = 1; while(curLink < (nbLinks-1)) { PX_ASSERT(curLink < stackSize); NpArticulationLink* l = linkStack[curLink]; NpArticulationLink*const* children = l->getChildren(); for(PxU32 i=0; i < l->getNbChildren(); i++) { NpArticulationLink* child = children[i]; NpArticulationJointReducedCoordinate* joint = static_cast<NpArticulationJointReducedCoordinate*>(child->getInboundJoint()); Sc::ArticulationJointCore& jCore = joint->getCore(); jCore.getCore().jointDirtyFlag = Dy::ArticulationJointCoreDirtyFlag::eALL; checkArticulationLink(this, child); linkTriggersWakeUp = linkTriggersWakeUp || (!child->scCheckSleepReadinessBesidesWakeCounter()); addArticulationLink(*child); // Adds joint too //child->setInboundJointDof(scArtSim->getDof(child->getLinkIndex())); linkStack[stackSize] = child; stackSize++; } curLink++; } //create low-level tendons addSpatialTendonInternal(&npaRC, scArtSim); addFixedTendonInternal(&npaRC, scArtSim); addArticulationSensorInternal(&npaRC, scArtSim); scArtSim->createLLStructure(); if ((scArtCore.getWakeCounter() == 0.0f) && linkTriggersWakeUp) { //The articulation needs to wake up, if one of the links triggers activation. npaRC.wakeUpInternal(true, false); } mArticulations.insert(&npa); //add loop joints if(scArtCore.getArticulationFlags() & PxArticulationFlag::eFIX_BASE) rootLink->setFixedBaseLink(true); //This method will prepare link data for the gpu mScene.addArticulationSimControl(scArtCore); const PxU32 maxLinks = mScene.getMaxArticulationLinks(); if (maxLinks < nbLinks) mScene.setMaxArticulationLinks(nbLinks); for (PxU32 i = 0; i < npaRC.mLoopJoints.size(); ++i) { Sc::ConstraintSim* cSim = npaRC.mLoopJoints[i]->getCore().getSim(); scArtSim->addLoopConstraint(cSim); } scArtSim->initializeConfiguration(); npaRC.updateKinematic(PxArticulationKinematicFlag::ePOSITION | PxArticulationKinematicFlag::eVELOCITY); if (scArtSim) { //scArtSim->checkResize(); linkStack[0] = rootLink; curLink = 0; stackSize = 1; while (curLink < (nbLinks - 1)) { PX_ASSERT(curLink < stackSize); NpArticulationLink* l = linkStack[curLink]; NpArticulationLink*const* children = l->getChildren(); for (PxU32 i = 0; i < l->getNbChildren(); i++) { NpArticulationLink* child = children[i]; child->setInboundJointDof(scArtSim->getDof(child->getLinkIndex())); NpArticulationJointReducedCoordinate* joint = static_cast<NpArticulationJointReducedCoordinate*>(child->getInboundJoint()); PxArticulationJointType::Enum jointType = joint->getJointType(); if (jointType == PxArticulationJointType::eUNDEFINED) { #if PX_CHECKED outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxScene::addArticulation(): The application need to set joint type. defaulting joint type to eFix"); #endif joint->scSetJointType(PxArticulationJointType::eFIX); child->setInboundJointDof(0); } if (jointType != PxArticulationJointType::eFIX) { PxArticulationMotion::Enum motionX = joint->getMotion(PxArticulationAxis::eX); PxArticulationMotion::Enum motionY = joint->getMotion(PxArticulationAxis::eY); PxArticulationMotion::Enum motionZ = joint->getMotion(PxArticulationAxis::eZ); PxArticulationMotion::Enum motionSwing1 = joint->getMotion(PxArticulationAxis::eSWING1); PxArticulationMotion::Enum motionSwing2 = joint->getMotion(PxArticulationAxis::eSWING2); PxArticulationMotion::Enum motionTwist = joint->getMotion(PxArticulationAxis::eTWIST); //PxArticulationMotion::eLOCKED is 0 if (!(motionX | motionY | motionZ | motionSwing1 | motionSwing2 | motionTwist)) { //if all axis are locked, which means the user doesn't set the motion. In this case, we should change the joint type to be //fix to avoid crash in the solver #if PX_CHECKED outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxScene::addArticulation(): Encountered a joint with all motions fixed. Switching joint type to eFix"); #endif joint->scSetJointType(PxArticulationJointType::eFIX); child->setInboundJointDof(0); } } linkStack[stackSize] = child; stackSize++; } curLink++; } } OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_ADD_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, articulations, static_cast<PxScene &>(*this), static_cast<PxArticulationReducedCoordinate&>(npa)); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, dofs, static_cast<PxArticulationReducedCoordinate&>(npa), npa.getDofs()); OMNI_PVD_WRITE_SCOPE_END return true; } void NpScene::removeArticulation(PxArticulationReducedCoordinate& articulation, bool wakeOnLostTouch) { PX_PROFILE_ZONE("API.removeArticulation", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::removeArticulation() not allowed while simulation is running. Call will be ignored.") if(removeFromSceneCheck(this, articulation.getScene(), "PxScene::removeArticulation(): Articulation")) removeArticulationInternal(articulation, wakeOnLostTouch, true); } void NpScene::removeArticulationInternal(PxArticulationReducedCoordinate& pxa, bool wakeOnLostTouch, bool removeFromAggregate) { NpArticulationReducedCoordinate& npArticulation = static_cast<NpArticulationReducedCoordinate&>(pxa); PxU32 nbLinks = npArticulation.getNbLinks(); PX_ASSERT(nbLinks > 0); if(removeFromAggregate && npArticulation.getAggregate()) { static_cast<NpAggregate*>(npArticulation.getAggregate())->removeArticulationAndReinsert(npArticulation, false); PX_ASSERT(!npArticulation.getAggregate()); } //!!!AL // Inefficient. We might want to introduce a LL method to kill the whole LL articulation together with all joints in one go, then // the order of removing the links/joints does not matter anymore. // Remove links & joints PX_ALLOCA(linkStack, NpArticulationLink*, nbLinks); linkStack[0] = npArticulation.getLinks()[0]; PxU32 curLink = 0, stackSize = 1; while(curLink < (nbLinks-1)) { PX_ASSERT(curLink < stackSize); NpArticulationLink* l = linkStack[curLink]; NpArticulationLink*const* children = l->getChildren(); for(PxU32 i=0; i < l->getNbChildren(); i++) { linkStack[stackSize] = children[i]; stackSize++; } curLink++; } PxRigidBodyFlags flag; for(PxI32 j=PxI32(nbLinks); j-- > 0; ) { flag |= linkStack[j]->getCore().getCore().mFlags; removeArticulationLink(*linkStack[j], wakeOnLostTouch); } // Remove tendons (RC checked in method) removeArticulationTendons(npArticulation); //Remove sensors removeArticulationSensors(npArticulation); if (flag & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) { PxNodeIndex index = npArticulation.getCore().getIslandNodeIndex(); if (index.isValid()) mScene.resetSpeculativeCCDArticulationLink(index.index()); } // Remove articulation scRemoveArticulation(npArticulation); removeFromArticulationList(npArticulation); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_REMOVE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, articulations, static_cast<PxScene &>(*this), pxa) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, dofs, pxa, pxa.getDofs()); OMNI_PVD_WRITE_SCOPE_END } /////////////////////////////////////////////////////////////////////////////// bool NpScene::addSoftBody(PxSoftBody& softBody) { if (!(this->getFlags() & PxSceneFlag::eENABLE_GPU_DYNAMICS)) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActor(): Soft bodies can only be simulated by GPU-accelerated scenes!"); #if PX_SUPPORT_GPU_PHYSX if (!softBody.getSimulationMesh()) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::addActor(): Soft body does not have simulation mesh, will not be added to scene!"); // Add soft body NpSoftBody& npSB = static_cast<NpSoftBody&>(softBody); scAddSoftBody(npSB); NpShape* npShape = static_cast<NpShape*>(npSB.getShape()); Sc::ShapeCore* shapeCore = &npShape->getCore(); npSB.getCore().attachShapeCore(shapeCore); npSB.getCore().attachSimulationMesh(softBody.getSimulationMesh(), softBody.getSoftBodyAuxData()); mSoftBodies.insert(&softBody); //for gpu soft body mScene.addSoftBodySimControl(npSB.getCore()); return true; #else PX_UNUSED(softBody); return false; #endif } void NpScene::removeSoftBody(PxSoftBody& softBody, bool /*wakeOnLostTouch*/) { #if PX_SUPPORT_GPU_PHYSX // Remove soft body NpSoftBody& npSB = reinterpret_cast<NpSoftBody&>(softBody); scRemoveSoftBody(npSB); removeFromSoftBodyList(softBody); #else PX_UNUSED(softBody); #endif } PxU32 NpScene::getNbSoftBodies() const { #if PX_SUPPORT_GPU_PHYSX NP_READ_CHECK(this); return mSoftBodies.size(); #else return 0; #endif } PxU32 NpScene::getSoftBodies(PxSoftBody** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { #if PX_SUPPORT_GPU_PHYSX NP_READ_CHECK(this); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mSoftBodies.getEntries(), mSoftBodies.size()); #else PX_UNUSED(userBuffer); PX_UNUSED(bufferSize); PX_UNUSED(startIndex); return 0; #endif } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION bool NpScene::addFEMCloth(PxFEMCloth& femCloth) { if (!(this->getFlags() & PxSceneFlag::eENABLE_GPU_DYNAMICS)) return PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxScene::addFEMCloth(): FEM-cloth can only be simulated by GPU-accelerated scenes!"); #if PX_SUPPORT_GPU_PHYSX // Add FEM-cloth NpFEMCloth& npCloth = static_cast<NpFEMCloth&>(femCloth); scAddFEMCloth(this, npCloth); NpShape* npShape = static_cast<NpShape*>(npCloth.getShape()); Sc::ShapeCore* shapeCore = &npShape->getCore(); npCloth.getCore().attachShapeCore(shapeCore); mFEMCloths.insert(&femCloth); //for gpu FEM-cloth mScene.addFEMClothSimControl(npCloth.getCore()); return true; #else PX_UNUSED(femCloth); return false; #endif } void NpScene::removeFEMCloth(PxFEMCloth& femCloth, bool /*wakeOnLostTouch*/) { #if PX_SUPPORT_GPU_PHYSX // Remove FEM-cloth NpFEMCloth& npCloth = reinterpret_cast<NpFEMCloth&>(femCloth); scRemoveFEMCloth(npCloth); removeFromFEMClothList(femCloth); #else PX_UNUSED(femCloth); #endif } #endif PxU32 NpScene::getNbFEMCloths() const { #if PX_SUPPORT_GPU_PHYSX && PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NP_READ_CHECK(this); return mFEMCloths.size(); #else return 0; #endif } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxU32 NpScene::getFEMCloths(PxFEMCloth** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { #if PX_SUPPORT_GPU_PHYSX NP_READ_CHECK(this); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mFEMCloths.getEntries(), mFEMCloths.size()); #else PX_UNUSED(userBuffer); PX_UNUSED(bufferSize); PX_UNUSED(startIndex); return 0; #endif } #else PxU32 NpScene::getFEMCloths(PxFEMCloth**, PxU32, PxU32) const { return 0; } #endif /////////////////////////////////////////////////////////////////////////////// bool NpScene::addParticleSystem(PxParticleSystem& particleSystem) { if (!mScene.isUsingGpuDynamicsAndBp()) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addActor(): Particle systems only currently supported with GPU-accelerated scenes!"); #if PX_SUPPORT_GPU_PHYSX switch(particleSystem.getConcreteType()) { case PxConcreteType::ePBD_PARTICLESYSTEM: { NpPBDParticleSystem& npPS = static_cast<NpPBDParticleSystem&>(particleSystem); scAddParticleSystem(npPS); PxPBDParticleSystem& pxPs = static_cast<PxPBDParticleSystem&>(particleSystem); mPBDParticleSystems.insert(&pxPs); mScene.addParticleSystemSimControl(npPS.getCore()); return true; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION case PxConcreteType::eFLIP_PARTICLESYSTEM: { NpFLIPParticleSystem& npPS = static_cast<NpFLIPParticleSystem&>(particleSystem); scAddParticleSystem(npPS); PxFLIPParticleSystem& pxPS = static_cast<PxFLIPParticleSystem&>(particleSystem); mFLIPParticleSystems.insert(&pxPS); mScene.addParticleSystemSimControl(npPS.getCore()); return true; } case PxConcreteType::eMPM_PARTICLESYSTEM: { NpMPMParticleSystem& npPS = static_cast<NpMPMParticleSystem&>(particleSystem); scAddParticleSystem(npPS); PxMPMParticleSystem& pxPS = static_cast<PxMPMParticleSystem&>(particleSystem); mMPMParticleSystems.insert(&pxPS); //for gpu particle system mScene.addParticleSystemSimControl(npPS.getCore()); return true; } #endif default: { PX_ASSERT(false); return false; } } #else PX_UNUSED(particleSystem); return false; #endif } void NpScene::removeParticleSystem(PxParticleSystem& particleSystem, bool /*wakeOnLostTouch*/) { #if PX_SUPPORT_GPU_PHYSX switch(particleSystem.getConcreteType()) { case PxConcreteType::ePBD_PARTICLESYSTEM: { // Remove particle system NpPBDParticleSystem& npPS = reinterpret_cast<NpPBDParticleSystem&>(particleSystem); scRemoveParticleSystem(npPS); PxPBDParticleSystem& pxPS = static_cast<PxPBDParticleSystem&>(particleSystem); removeFromParticleSystemList(pxPS); return; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION case PxConcreteType::eFLIP_PARTICLESYSTEM: { // Remove particle system NpFLIPParticleSystem& npPS = reinterpret_cast<NpFLIPParticleSystem&>(particleSystem); scRemoveParticleSystem(npPS); PxFLIPParticleSystem& pxPS = static_cast<PxFLIPParticleSystem&>(particleSystem); removeFromParticleSystemList(pxPS); return; } case PxConcreteType::eMPM_PARTICLESYSTEM: { // Remove particle system NpMPMParticleSystem& npPS = reinterpret_cast<NpMPMParticleSystem&>(particleSystem); scRemoveParticleSystem(npPS); PxMPMParticleSystem& pxPS = static_cast<PxMPMParticleSystem&>(particleSystem); removeFromParticleSystemList(pxPS); return; } #endif default: PX_ASSERT(false); } #else PX_UNUSED(particleSystem); #endif } PxU32 NpScene::getNbParticleSystems(PxParticleSolverType::Enum type) const { NP_READ_CHECK(this); #if PX_SUPPORT_GPU_PHYSX switch (type) { case PxParticleSolverType::ePBD: { return mPBDParticleSystems.size(); } case PxParticleSolverType::eFLIP: { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION return mFLIPParticleSystems.size(); #else return 0; #endif } case PxParticleSolverType::eMPM: { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION return mMPMParticleSystems.size(); #else return 0; #endif } default: { PX_ASSERT(false); return 0; } } #else PX_UNUSED(type); return 0; #endif } PxU32 NpScene::getParticleSystems(PxParticleSolverType::Enum type, PxParticleSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(this); #if PX_SUPPORT_GPU_PHYSX switch (type) { case PxParticleSolverType::ePBD: { return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mPBDParticleSystems.getEntries(), mPBDParticleSystems.size()); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION case PxParticleSolverType::eFLIP: { return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mFLIPParticleSystems.getEntries(), mFLIPParticleSystems.size()); } case PxParticleSolverType::eMPM: { return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mMPMParticleSystems.getEntries(), mMPMParticleSystems.size()); } #endif default: { PX_ASSERT(false); return 0; } } #else PX_UNUSED(type); PX_UNUSED(userBuffer); PX_UNUSED(bufferSize); PX_UNUSED(startIndex); return 0; #endif } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION bool NpScene::addHairSystem(PxHairSystem& hairSystem) { if (!mScene.isUsingGpuDynamicsAndBp()) { return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addHairSystem(): Hair systems only currently supported with GPU-accelerated scenes!"); } #if PX_SUPPORT_GPU_PHYSX NpHairSystem& npHairSystem = static_cast<NpHairSystem&>(hairSystem); scAddHairSystem(npHairSystem); mHairSystems.insert(&npHairSystem); mScene.addHairSystemSimControl(npHairSystem.getCore()); return true; #else PX_UNUSED(hairSystem); return false; #endif } void NpScene::removeHairSystem(PxHairSystem& hairSystem, bool /*wakeOnLostTouch*/) { #if PX_SUPPORT_GPU_PHYSX NpHairSystem& npHairSystem = static_cast<NpHairSystem&>(hairSystem); scRemoveHairSystem(npHairSystem); removeFromHairSystemList(hairSystem); #else PX_UNUSED(hairSystem); #endif } #endif PxU32 NpScene::getNbHairSystems() const { #if PX_SUPPORT_GPU_PHYSX && PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NP_READ_CHECK(this); return mHairSystems.size(); #else return 0; #endif } PxU32 NpScene::getHairSystems(PxHairSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { #if PX_SUPPORT_GPU_PHYSX && PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NP_READ_CHECK(this); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mHairSystems.getEntries(), mHairSystems.size()); #else PX_UNUSED(userBuffer); PX_UNUSED(bufferSize); PX_UNUSED(startIndex); return 0; #endif } /////////////////////////////////////////////////////////////////////////////// void NpScene::addArticulationLinkBody(NpArticulationLink& link) { scAddActor(link, false, NULL, NULL); link.setRigidActorSceneIndex(mRigidActorIndexPool.getNewID()); link.getShapeManager().setupAllSceneQuery(getSQAPI(), link, NULL); } void NpScene::addArticulationLinkConstraint(NpArticulationLink& link) { NpArticulationJointReducedCoordinate* j = static_cast<NpArticulationJointReducedCoordinate*>(link.getInboundJoint()); if (j) { scAddArticulationJoint(*j); } link.addConstraintsToScene(); } void NpScene::addArticulationLink(NpArticulationLink& link) { Sc::ArticulationCore& scArtCore = static_cast<NpArticulationReducedCoordinate&>(link.getArticulation()).getCore(); Sc::ArticulationSim* scArtSim = scArtCore.getSim(); Sc::ArticulationSimDirtyFlags dirtyFlags = scArtSim->getDirtyFlag(); addArticulationLinkBody(link); addArticulationLinkConstraint(link); if (scArtSim) { PxU32 cHandle = scArtSim->findBodyIndex(*link.getCore().getSim()); link.setLLIndex(cHandle); NpArticulationJointReducedCoordinate* j = static_cast<NpArticulationJointReducedCoordinate*>(link.getInboundJoint()); j->getCore().setLLIndex(cHandle); const bool isDirty = (dirtyFlags & Sc::ArticulationSimDirtyFlag::eUPDATE); if (j && (!isDirty)) { getScScene().addDirtyArticulationSim(scArtSim); } } } void NpScene::removeArticulationLink(NpArticulationLink& link, bool wakeOnLostTouch) { NpArticulationJointReducedCoordinate* j = static_cast<NpArticulationJointReducedCoordinate*>(link.getInboundJoint()); link.removeConstraintsFromScene(); link.getShapeManager().teardownAllSceneQuery(getSQAPI(), link); Sc::ArticulationCore& scArtCore = static_cast<NpArticulationReducedCoordinate&>(link.getArticulation()).getCore(); Sc::ArticulationSim* scArtSim = scArtCore.getSim(); Sc::ArticulationSimDirtyFlags dirtyFlags = scArtSim->getDirtyFlag(); if (j) { const bool isDirty = (dirtyFlags & Sc::ArticulationSimDirtyFlag::eUPDATE); if (!isDirty) { getScScene().addDirtyArticulationSim(scArtSim); } const PxU32 linkIndex = link.getLinkIndex(); scArtSim->copyJointStatus(linkIndex); scRemoveArticulationJoint(*j); } scRemoveActor(link, wakeOnLostTouch, false); mRigidActorIndexPool.freeID(link.getRigidActorSceneIndex()); link.setRigidActorSceneIndex(NP_UNUSED_BASE_INDEX); } //////////////////////////////////////////////////////////////////////////////// void NpScene::addArticulationAttachment(NpArticulationAttachment& attachment) { Sc::ArticulationSpatialTendonCore& tendonCore = attachment.getTendon().getTendonCore(); Sc::ArticulationSpatialTendonSim* sim = tendonCore.getSim(); if (sim) { Sc::ArticulationAttachmentCore& attachmentCore = attachment.getCore(); attachmentCore.mLLLinkIndex = attachment.mLink->getLinkIndex(); sim->addAttachment(attachmentCore); } } void NpScene::removeArticulationAttachment(NpArticulationAttachment& attachment) { Sc::ArticulationSpatialTendonCore& tendonCore = attachment.getTendon().getTendonCore(); Sc::ArticulationSpatialTendonSim* sim = tendonCore.getSim(); if (sim) { Sc::ArticulationAttachmentCore& attachmentCore = attachment.getCore(); sim->removeAttachment(attachmentCore); } } //////////////////////////////////////////////////////////////////////////////////// void NpScene::addArticulationTendonJoint(NpArticulationTendonJoint& tendonJoint) { Sc::ArticulationFixedTendonCore& tendonCore = tendonJoint.getTendon().getTendonCore(); Sc::ArticulationFixedTendonSim* sim = tendonCore.getSim(); if (sim) { Sc::ArticulationTendonJointCore& jointCore = tendonJoint.getCore(); jointCore.mLLLinkIndex = tendonJoint.mLink->getLinkIndex(); sim->addTendonJoint(jointCore); } } void NpScene::removeArticulationTendonJoint(NpArticulationTendonJoint& joint) { Sc::ArticulationFixedTendonCore& tendonCore = joint.getTendon().getTendonCore(); Sc::ArticulationFixedTendonSim* sim = tendonCore.getSim(); if (sim) { Sc::ArticulationTendonJointCore& jointCore = joint.getCore(); sim->removeTendonJoint(jointCore); } } void NpScene::removeArticulationTendons(PxArticulationReducedCoordinate& articulation) { NpArticulationReducedCoordinate* npaRC = static_cast<NpArticulationReducedCoordinate*>(&articulation); // Remove spatial tendons const PxU32 nbSpatialTendons = npaRC->getNbSpatialTendons(); for(PxU32 i = 0; i < nbSpatialTendons; i++) { NpArticulationSpatialTendon* tendon = npaRC->getSpatialTendon(i); npaRC->removeSpatialTendonInternal(tendon); } //Remove fixed tendons const PxU32 nbFixedTendons = npaRC->getNbFixedTendons(); for(PxU32 i = 0; i < nbFixedTendons; i++) { NpArticulationFixedTendon* tendon = npaRC->getFixedTendon(i); npaRC->removeFixedTendonInternal(tendon); } } void NpScene::removeArticulationSensors(PxArticulationReducedCoordinate& articulation) { NpArticulationReducedCoordinate* npaRC = static_cast<NpArticulationReducedCoordinate*>(&articulation); //Remove sensors const PxU32 nbSensors = npaRC->getNbSensors(); for (PxU32 i = 0; i < nbSensors; i++) { NpArticulationSensor* sensor = npaRC->getSensor(i); npaRC->removeSensorInternal(sensor); } } /////////////////////////////////////////////////////////////////////////////// void NpScene::scAddAggregate(NpAggregate& agg) { PX_ASSERT(!isAPIWriteForbidden()); agg.setNpScene(this); const PxU32 aggregateID = mScene.createAggregate(&agg, agg.getMaxNbShapesFast(), agg.getFilterHint()); agg.setAggregateID(aggregateID); #if PX_SUPPORT_PVD //Sending pvd events after all aggregates's actors are inserted into scene mScenePvdClient.createPvdInstance(&agg); #endif } void NpScene::scRemoveAggregate(NpAggregate& agg) { PX_ASSERT(!isAPIWriteForbidden()); mScene.deleteAggregate(agg.getAggregateID()); agg.setNpScene(NULL); #if PX_SUPPORT_PVD mScenePvdClient.releasePvdInstance(&agg); #endif } bool NpScene::addAggregate(PxAggregate& aggregate) { PX_PROFILE_ZONE("API.addAggregate", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::addAggregate() not allowed while simulation is running. Call will be ignored.", false) PX_SIMD_GUARD; NpAggregate& np = static_cast<NpAggregate&>(aggregate); #if PX_CHECKED { const PxU32 nb = np.getCurrentSizeFast(); for(PxU32 i=0;i<nb;i++) { PxRigidStatic* a = np.getActorFast(i)->is<PxRigidStatic>(); if(a && !static_cast<NpRigidStatic*>(a)->checkConstraintValidity()) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addAggregate(): Aggregate contains an actor with an invalid constraint!"); } } #endif if(mScene.isUsingGpuDynamicsOrBp() && np.getMaxNbShapesFast() == PX_MAX_U32) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addAggregate(): Aggregates cannot be added to GPU scene unless you provide a maxNbShapes!"); if(np.getNpScene()) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::addAggregate(): Aggregate already assigned to a scene. Call will be ignored!"); scAddAggregate(np); np.addToScene(*this); mAggregates.insert(&aggregate); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_ADD_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, aggregates, static_cast<PxScene&>(*this), aggregate); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, scene, aggregate, static_cast<PxScene const*>(this)); OMNI_PVD_WRITE_SCOPE_END return true; } void NpScene::removeAggregate(PxAggregate& aggregate, bool wakeOnLostTouch) { PX_PROFILE_ZONE("API.removeAggregate", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::removeAggregate() not allowed while simulation is running. Call will be ignored.") if(!removeFromSceneCheck(this, aggregate.getScene(), "PxScene::removeAggregate(): Aggregate")) return; NpAggregate& np = static_cast<NpAggregate&>(aggregate); if(np.getScene()!=this) return; const PxU32 nb = np.getCurrentSizeFast(); for(PxU32 j=0;j<nb;j++) { PxActor* a = np.getActorFast(j); PX_ASSERT(a); if (a->getType() != PxActorType::eARTICULATION_LINK) { NpActor& sc = NpActor::getFromPxActor(*a); np.scRemoveActor(sc, false); // This is only here to make sure the aggregateID gets set to invalid removeActorInternal(*a, wakeOnLostTouch, false); } else if (a->getScene()) { NpArticulationLink& al = static_cast<NpArticulationLink&>(*a); NpArticulationReducedCoordinate& npArt = static_cast<NpArticulationReducedCoordinate&>(al.getRoot()); NpArticulationLink* const* links = npArt.getLinks(); for(PxU32 i=0; i < npArt.getNbLinks(); i++) { np.scRemoveActor(*links[i], false); // This is only here to make sure the aggregateID gets set to invalid } removeArticulationInternal(npArt, wakeOnLostTouch, false); } } scRemoveAggregate(np); removeFromAggregateList(aggregate); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_REMOVE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, aggregates, static_cast<PxScene&>(*this), aggregate); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, scene, aggregate, static_cast<PxScene const*>(NULL)); OMNI_PVD_WRITE_SCOPE_END } PxU32 NpScene::getNbAggregates() const { NP_READ_CHECK(this); return mAggregates.size(); } PxU32 NpScene::getAggregates(PxAggregate** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(this); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mAggregates.getEntries(), mAggregates.size()); } /////////////////////////////////////////////////////////////////////////////// void NpScene::scSwitchRigidToNoSim(NpActor& r) { PX_ASSERT(!isAPIWriteForbidden()); if(r.getNpScene()) { PxInlineArray<const Sc::ShapeCore*, 64> scShapes; const NpType::Enum npType = r.getNpType(); if(npType==NpType::eRIGID_STATIC) getScScene().removeStatic(static_cast<NpRigidStatic&>(r).getCore(), scShapes, true); else if(npType==NpType::eBODY) getScScene().removeBody(static_cast<NpRigidDynamic&>(r).getCore(), scShapes, true); else if(npType==NpType::eBODY_FROM_ARTICULATION_LINK) getScScene().removeBody(static_cast<NpArticulationLink&>(r).getCore(), scShapes, true); else PX_ASSERT(0); } } void NpScene::scSwitchRigidFromNoSim(NpActor& r) { PX_ASSERT(!isAPIWriteForbidden()); if(r.getNpScene()) { NpShape* const* shapes; const size_t shapePtrOffset = NpShape::getCoreOffset(); PxU32 nbShapes; { bool isCompound; const NpType::Enum npType = r.getNpType(); if(npType==NpType::eRIGID_STATIC) { NpRigidStatic& np = static_cast<NpRigidStatic&>(r); nbShapes = NpRigidStaticGetShapes(np, shapes); getScScene().addStatic(np.getCore(), shapes, nbShapes, shapePtrOffset, NULL); } else if(npType==NpType::eBODY) { NpRigidDynamic& np = static_cast<NpRigidDynamic&>(r); nbShapes = NpRigidDynamicGetShapes(np, shapes, &isCompound); getScScene().addBody(np.getCore(), shapes, nbShapes, shapePtrOffset, NULL, isCompound); } else if(npType==NpType::eBODY_FROM_ARTICULATION_LINK) { NpArticulationLink& np = static_cast<NpArticulationLink&>(r); nbShapes = NpArticulationGetShapes(np, shapes, &isCompound); getScScene().addBody(np.getCore(), shapes, nbShapes, shapePtrOffset, NULL, isCompound); } else { nbShapes = 0; shapes = NULL; isCompound = false; PX_ASSERT(0); } } } } /////////////////////////////////////////////////////////////////////////////// bool NpScene::addCollection(const PxCollection& collection) { PX_PROFILE_ZONE("API.addCollection", getContextId()); const Cm::Collection& col = static_cast<const Cm::Collection&>(collection); PxU32 nb = col.internalGetNbObjects(); #if PX_CHECKED for(PxU32 i=0;i<nb;i++) { PxRigidStatic* a = col.internalGetObject(i)->is<PxRigidStatic>(); if(a && !static_cast<NpRigidStatic*>(a)->checkConstraintValidity()) return outputError<PxErrorCode::eINVALID_OPERATION>( __LINE__, "PxScene::addCollection(): collection contains an actor with an invalid constraint!"); } #endif PxArray<PxActor*> actorsToInsert; actorsToInsert.reserve(nb); struct Local { static void addActorIfNeeded(PxActor* actor, PxArray<PxActor*>& actorArray) { if(actor->getAggregate()) return; // The actor will be added when the aggregate is added actorArray.pushBack(actor); } }; for(PxU32 i=0;i<nb;i++) { PxBase* s = col.internalGetObject(i); const PxType serialType = s->getConcreteType(); //NpArticulationLink, NpArticulationJoint are added with the NpArticulation //Actors and Articulations that are members of an Aggregate are added with the NpAggregate if(serialType==PxConcreteType::eRIGID_DYNAMIC) { NpRigidDynamic* np = static_cast<NpRigidDynamic*>(s); // if pruner structure exists for the actor, actor will be added with the pruner structure if(!np->getShapeManager().getPruningStructure()) Local::addActorIfNeeded(np, actorsToInsert); } else if(serialType==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* np = static_cast<NpRigidStatic*>(s); // if pruner structure exists for the actor, actor will be added with the pruner structure if(!np->getShapeManager().getPruningStructure()) Local::addActorIfNeeded(np, actorsToInsert); } else if(serialType==PxConcreteType::eSHAPE) { } else if (serialType == PxConcreteType::eARTICULATION_REDUCED_COORDINATE) { NpArticulationReducedCoordinate* np = static_cast<NpArticulationReducedCoordinate*>(s); if (!np->getAggregate()) // The actor will be added when the aggregate is added { addArticulation(static_cast<PxArticulationReducedCoordinate&>(*np)); } } else if(serialType==PxConcreteType::eAGGREGATE) { NpAggregate* np = static_cast<NpAggregate*>(s); addAggregate(*np); } else if(serialType == PxConcreteType::ePRUNING_STRUCTURE) { PxPruningStructure* ps = static_cast<PxPruningStructure*>(s); addActors(*ps); } } if(!actorsToInsert.empty()) addActorsInternal(&actorsToInsert[0], actorsToInsert.size(), NULL); return true; } /////////////////////////////////////////////////////////////////////////////// PxU32 NpScene::getNbActors(PxActorTypeFlags types) const { NP_READ_CHECK(this); PxU32 nbActors = 0; if(types & PxActorTypeFlag::eRIGID_STATIC) nbActors += mRigidStatics.size(); if(types & PxActorTypeFlag::eRIGID_DYNAMIC) nbActors += mRigidDynamics.size(); return nbActors; } static PxU32 getArrayOfPointers_RigidActors(PxActor** PX_RESTRICT userBuffer, PxU32 bufferSize, PxU32 startIndex, NpRigidStatic*const* PX_RESTRICT src0, PxU32 size0, NpRigidDynamic*const* PX_RESTRICT src1, PxU32 size1) { // PT: we run the same code as getArrayOfPointers but with a virtual array containing both static & dynamic actors. const PxU32 size = size0 + size1; const PxU32 remainder = PxU32(PxMax<PxI32>(PxI32(size - startIndex), 0)); const PxU32 writeCount = PxMin(remainder, bufferSize); for(PxU32 i=0;i<writeCount;i++) { const PxU32 index = startIndex+i; PX_ASSERT(index<size); if(index<size0) userBuffer[i] = src0[index]; else userBuffer[i] = src1[index-size0]; } return writeCount; } PxU32 NpScene::getActors(PxActorTypeFlags types, PxActor** buffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(this); const bool wantsStatic = types & PxActorTypeFlag::eRIGID_STATIC; const bool wantsDynamic = types & PxActorTypeFlag::eRIGID_DYNAMIC; if(wantsStatic && !wantsDynamic) return Cm::getArrayOfPointers(buffer, bufferSize, startIndex, mRigidStatics.begin(), mRigidStatics.size()); if(!wantsStatic && wantsDynamic) return Cm::getArrayOfPointers(buffer, bufferSize, startIndex, mRigidDynamics.begin(), mRigidDynamics.size()); if(wantsStatic && wantsDynamic) { return getArrayOfPointers_RigidActors(buffer, bufferSize, startIndex, mRigidStatics.begin(), mRigidStatics.size(), mRigidDynamics.begin(), mRigidDynamics.size()); } return 0; } /////////////////////////////////////////////////////////////////////////////// PxActor** NpScene::getActiveActors(PxU32& nbActorsOut) { NP_READ_CHECK(this); if(!isAPIWriteForbidden()) return mScene.getActiveActors(nbActorsOut); else { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::getActiveActors() not allowed while simulation is running. Call will be ignored."); nbActorsOut = 0; return NULL; } } PxActor** NpScene::getFrozenActors(PxU32& nbActorsOut) { NP_READ_CHECK(this); if(!isAPIWriteForbidden()) return mScene.getFrozenActors(nbActorsOut); else { outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxScene::getFrozenActors() not allowed while simulation is running. Call will be ignored."); nbActorsOut = 0; return NULL; } } void NpScene::setFrozenActorFlag(const bool buildFrozenActors) { #if PX_CHECKED PxSceneFlags combinedFlag(PxSceneFlag::eENABLE_ACTIVE_ACTORS | PxSceneFlag::eENABLE_STABILIZATION); PX_CHECK_AND_RETURN((getFlags() & combinedFlag)== combinedFlag, "NpScene::setFrozenActorFlag: Cannot raise BuildFrozenActors if PxSceneFlag::eENABLE_STABILIZATION and PxSceneFlag::eENABLE_ACTIVE_ACTORS is not raised!"); #endif mBuildFrozenActors = buildFrozenActors; } /////////////////////////////////////////////////////////////////////////////// PxU32 NpScene::getNbArticulations() const { NP_READ_CHECK(this); return mArticulations.size(); } PxU32 NpScene::getArticulations(PxArticulationReducedCoordinate** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(this); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mArticulations.getEntries(), mArticulations.size()); } /////////////////////////////////////////////////////////////////////////////// PxU32 NpScene::getNbConstraints() const { NP_READ_CHECK(this); return mScene.getNbConstraints(); } static PX_FORCE_INLINE PxU32 getArrayOfPointers(PxConstraint** PX_RESTRICT userBuffer, PxU32 bufferSize, PxU32 startIndex, Sc::ConstraintCore*const* PX_RESTRICT src, PxU32 size) { const PxU32 remainder = PxU32(PxMax<PxI32>(PxI32(size - startIndex), 0)); const PxU32 writeCount = PxMin(remainder, bufferSize); src += startIndex; for(PxU32 i=0;i<writeCount;i++) { PxConstraint* pxc = src[i]->getPxConstraint(); userBuffer[i] = static_cast<PxConstraint*>(pxc); } return writeCount; } PxU32 NpScene::getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(this); return ::getArrayOfPointers(userBuffer, bufferSize, startIndex, mScene.getConstraints(), mScene.getNbConstraints()); } /////////////////////////////////////////////////////////////////////////////// const PxRenderBuffer& NpScene::getRenderBuffer() { if (getSimulationStage() != Sc::SimulationStage::eCOMPLETE) { // will be reading the Sc::Scene renderable which is getting written // during the sim, hence, avoid call while simulation is running. outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::getRenderBuffer() not allowed while simulation is running. Call will be ignored."); } return mRenderBuffer; } /////////////////////////////////////////////////////////////////////////////// void NpScene::getSimulationStatistics(PxSimulationStatistics& s) const { NP_READ_CHECK(this); if (getSimulationStage() == Sc::SimulationStage::eCOMPLETE) { #if PX_ENABLE_SIM_STATS mScene.getStats(s); #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS PX_UNUSED(s); #endif } else { //will be reading data that is getting written during the sim, hence, avoid call while simulation is running. outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::getSimulationStatistics() not allowed while simulation is running. Call will be ignored."); } } /////////////////////////////////////////////////////////////////////////////// PxClientID NpScene::createClient() { NP_WRITE_CHECK(this); // PT: mNbClients starts at 1, 0 reserved for PX_DEFAULT_CLIENT const PxClientID clientID = PxClientID(mNbClients); mNbClients++; return clientID; } /////////////////////////////////////////////////////////////////////////////// PxSolverType::Enum NpScene::getSolverType() const { NP_READ_CHECK(this); return mScene.getSolverType(); } //FrictionModel PxFrictionType::Enum NpScene::getFrictionType() const { NP_READ_CHECK(this); return mScene.getFrictionType(); } /////////////////////////////////////////////////////////////////////////////// // Callbacks void NpScene::setSimulationEventCallback(PxSimulationEventCallback* callback) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setSimulationEventCallback() not allowed while simulation is running. Call will be ignored.") mScene.setSimulationEventCallback(callback); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, hasSimulationEventCallback, static_cast<PxScene&>(*this), callback ? true : false) } PxSimulationEventCallback* NpScene::getSimulationEventCallback() const { NP_READ_CHECK(this); return mScene.getSimulationEventCallback(); } void NpScene::setContactModifyCallback(PxContactModifyCallback* callback) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setContactModifyCallback() not allowed while simulation is running. Call will be ignored.") mScene.setContactModifyCallback(callback); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, hasContactModifyCallback, static_cast<PxScene&>(*this), callback ? true : false) } PxContactModifyCallback* NpScene::getContactModifyCallback() const { NP_READ_CHECK(this); return mScene.getContactModifyCallback(); } void NpScene::setCCDContactModifyCallback(PxCCDContactModifyCallback* callback) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setCCDContactModifyCallback() not allowed while simulation is running. Call will be ignored.") mScene.setCCDContactModifyCallback(callback); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, hasCCDContactModifyCallback, static_cast<PxScene&>(*this), callback ? true : false) } PxCCDContactModifyCallback* NpScene::getCCDContactModifyCallback() const { NP_READ_CHECK(this); return mScene.getCCDContactModifyCallback(); } void NpScene::setBroadPhaseCallback(PxBroadPhaseCallback* callback) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setBroadPhaseCallback() not allowed while simulation is running. Call will be ignored.") mScene.getBroadphaseManager().setBroadPhaseCallback(callback); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, hasBroadPhaseCallback, static_cast<PxScene&>(*this), callback ? true : false) } PxBroadPhaseCallback* NpScene::getBroadPhaseCallback() const { NP_READ_CHECK(this); return mScene.getBroadphaseManager().getBroadPhaseCallback(); } void NpScene::setCCDMaxPasses(PxU32 ccdMaxPasses) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((ccdMaxPasses!=0), "PxScene::setCCDMaxPasses(): ccd max passes cannot be zero!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setCCDMaxPasses() not allowed while simulation is running. Call will be ignored.") mScene.setCCDMaxPasses(ccdMaxPasses); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, ccdMaxPasses, static_cast<PxScene&>(*this), ccdMaxPasses) } PxU32 NpScene::getCCDMaxPasses() const { NP_READ_CHECK(this); return mScene.getCCDMaxPasses(); } void NpScene::setCCDMaxSeparation(const PxReal separation) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((separation>=0.0f), "PxScene::setCCDMaxSeparation(): separation value has to be in [0, PX_MAX_F32)!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setCCDMaxSeparation() not allowed while simulation is running. Call will be ignored.") mScene.setCCDMaxSeparation(separation); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, ccdMaxSeparation, static_cast<PxScene&>(*this), separation) } PxReal NpScene::getCCDMaxSeparation() const { NP_READ_CHECK(this); return mScene.getCCDMaxSeparation(); } void NpScene::setCCDThreshold(const PxReal t) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((t>0.0f), "PxScene::setCCDThreshold(): threshold value has to be in [eps, PX_MAX_F32)!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setCCDThreshold() not allowed while simulation is running. Call will be ignored.") mScene.setCCDThreshold(t); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, ccdThreshold, static_cast<PxScene&>(*this), t) } PxReal NpScene::getCCDThreshold() const { NP_READ_CHECK(this); return mScene.getCCDThreshold(); } PxBroadPhaseType::Enum NpScene::getBroadPhaseType() const { NP_READ_CHECK(this); const Bp::BroadPhase* bp = mScene.getAABBManager()->getBroadPhase(); return bp->getType(); } bool NpScene::getBroadPhaseCaps(PxBroadPhaseCaps& caps) const { NP_READ_CHECK(this); const Bp::BroadPhase* bp = mScene.getAABBManager()->getBroadPhase(); bp->getCaps(caps); return true; } PxU32 NpScene::getNbBroadPhaseRegions() const { NP_READ_CHECK(this); const Bp::BroadPhase* bp = mScene.getAABBManager()->getBroadPhase(); return bp->getNbRegions(); } PxU32 NpScene::getBroadPhaseRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(this); const Bp::BroadPhase* bp = mScene.getAABBManager()->getBroadPhase(); return bp->getRegions(userBuffer, bufferSize, startIndex); } PxU32 NpScene::addBroadPhaseRegion(const PxBroadPhaseRegion& region, bool populateRegion) { PX_PROFILE_ZONE("BroadPhase.addBroadPhaseRegion", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_MSG(region.mBounds.isValid(), "PxScene::addBroadPhaseRegion(): invalid bounds provided!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::addBroadPhaseRegion() not allowed while simulation is running. Call will be ignored.", 0xffffffff) if(region.mBounds.isEmpty()) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::addBroadPhaseRegion(): region bounds are empty. Call will be ignored."); return 0xffffffff; } Bp::AABBManagerBase* aabbManager = mScene.getAABBManager(); Bp::BroadPhase* bp = aabbManager->getBroadPhase(); return bp->addRegion(region, populateRegion, aabbManager->getBoundsArray().begin(), aabbManager->getContactDistances()); } bool NpScene::removeBroadPhaseRegion(PxU32 handle) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::removeBroadPhaseRegion() not allowed while simulation is running. Call will be ignored.", false) Bp::BroadPhase* bp = mScene.getAABBManager()->getBroadPhase(); return bp->removeRegion(handle); } /////////////////////////////////////////////////////////////////////////////// // Filtering void NpScene::setFilterShaderData(const void* data, PxU32 dataSize) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN(( ((dataSize == 0) && (data == NULL)) || ((dataSize > 0) && (data != NULL)) ), "PxScene::setFilterShaderData(): data pointer must not be NULL unless the specified data size is 0 too and vice versa."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setFilterShaderData() not allowed while simulation is running. Call will be ignored.") mScene.setFilterShaderData(data, dataSize); updatePvdProperties(); } const void* NpScene::getFilterShaderData() const { NP_READ_CHECK(this); return mScene.getFilterShaderDataFast(); } PxU32 NpScene::getFilterShaderDataSize() const { NP_READ_CHECK(this); return mScene.getFilterShaderDataSizeFast(); } PxSimulationFilterShader NpScene::getFilterShader() const { NP_READ_CHECK(this); return mScene.getFilterShaderFast(); } PxSimulationFilterCallback* NpScene::getFilterCallback() const { NP_READ_CHECK(this); return mScene.getFilterCallbackFast(); } bool NpScene::resetFiltering(PxActor& actor) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN_VAL(NpActor::getNpSceneFromActor(actor) && (NpActor::getNpSceneFromActor(actor) == this), "PxScene::resetFiltering(): Actor must be in a scene.", false); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::resetFiltering() not allowed while simulation is running. Call will be ignored.", false) bool status; switch(actor.getConcreteType()) { case PxConcreteType::eRIGID_STATIC: { NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor); status = npStatic.NpRigidStaticT::resetFiltering_(npStatic, npStatic.getCore(), NULL, 0); } break; case PxConcreteType::eRIGID_DYNAMIC: { NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor); status = npDynamic.resetFiltering_(npDynamic, npDynamic.getCore(), NULL, 0); if(status) npDynamic.wakeUpInternal(); } break; case PxConcreteType::eARTICULATION_LINK: { NpArticulationLink& npLink = static_cast<NpArticulationLink&>(actor); status = npLink.resetFiltering_(npLink, npLink.getCore(), NULL, 0); if(status) { NpArticulationReducedCoordinate& npArticulation = static_cast<NpArticulationReducedCoordinate&>(npLink.getRoot()); npArticulation.wakeUpInternal(false, true); } } break; default: status = outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::resetFiltering(): only PxRigidActor supports this operation!"); } return status; } bool NpScene::resetFiltering(PxRigidActor& actor, PxShape*const* shapes, PxU32 shapeCount) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN_VAL(NpActor::getNpSceneFromActor(actor) && (NpActor::getNpSceneFromActor(actor) == this), "PxScene::resetFiltering(): Actor must be in a scene.", false); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::resetFiltering() not allowed while simulation is running. Call will be ignored.", false) PX_SIMD_GUARD; bool status = false; switch(actor.getConcreteType()) { case PxConcreteType::eRIGID_STATIC: { NpRigidStatic& npStatic = static_cast<NpRigidStatic&>(actor); status = npStatic.NpRigidStaticT::resetFiltering_(npStatic, npStatic.getCore(), shapes, shapeCount); } break; case PxConcreteType::eRIGID_DYNAMIC: { NpRigidDynamic& npDynamic = static_cast<NpRigidDynamic&>(actor); status = npDynamic.resetFiltering_(npDynamic, npDynamic.getCore(), shapes, shapeCount); if(status) npDynamic.wakeUpInternal(); } break; case PxConcreteType::eARTICULATION_LINK: { NpArticulationLink& npLink = static_cast<NpArticulationLink&>(actor); status = npLink.resetFiltering_(npLink, npLink.getCore(), shapes, shapeCount); if(status) { NpArticulationReducedCoordinate& impl = static_cast<NpArticulationReducedCoordinate&>(npLink.getRoot()); impl.wakeUpInternal(false, true); } } break; } return status; } PxPairFilteringMode::Enum NpScene::getKinematicKinematicFilteringMode() const { NP_READ_CHECK(this); return mScene.getKineKineFilteringMode(); } PxPairFilteringMode::Enum NpScene::getStaticKinematicFilteringMode() const { NP_READ_CHECK(this); return mScene.getStaticKineFilteringMode(); } /////////////////////////////////////////////////////////////////////////////// PxPhysics& NpScene::getPhysics() { return mPhysics; } void NpScene::updateConstants(const PxArray<NpConstraint*>& constraints) { PxsSimulationController* simController = mScene.getSimulationController(); PX_ASSERT(simController); PxU32 nbConstraints = constraints.size(); NpConstraint*const* currentConstraint = constraints.begin(); while(nbConstraints--) { (*currentConstraint)->updateConstants(*simController); currentConstraint++; } } void NpScene::updateDirtyShaders() { PX_PROFILE_ZONE("Sim.updateDirtyShaders", getContextId()); // this should continue to be done in the Np layer even after SC has taken over // all vital simulation functions, because it needs to complete before simulate() // returns to the application #ifdef NEW_DIRTY_SHADERS_CODE if(1) { updateConstants(mAlwaysUpdatedConstraints); updateConstants(mDirtyConstraints); mDirtyConstraints.clear(); } else #endif { // However, the implementation needs fixing so that it does work proportional to // the number of dirty shaders PxsSimulationController* simController = mScene.getSimulationController(); PX_ASSERT(simController); const PxU32 nbConstraints = mScene.getNbConstraints(); Sc::ConstraintCore*const* constraints = mScene.getConstraints(); for(PxU32 i=0;i<nbConstraints;i++) { PxConstraint* pxc = constraints[i]->getPxConstraint(); static_cast<NpConstraint*>(pxc)->updateConstants(*simController); } } } // PT: TODO // - do we really need a different mutex per material type? // - classes like PxsMaterialManager are already typedef of templated types so maybe we don't need them here template<class NpMaterialT, class MaterialManagerT, class MaterialCoreT> static void updateLowLevelMaterials(NpPhysics& physics, PxMutex& sceneMaterialBufferLock, MaterialManagerT& pxsMaterialManager, PxArray<NpScene::MaterialEvent>& materialBuffer, PxvNphaseImplementationContext* context) { PxMutex::ScopedLock lock(sceneMaterialBufferLock); NpMaterialT** masterMaterial = NpMaterialAccessor<NpMaterialT>::getMaterialManager(physics).getMaterials(); //sync all the material events const PxU32 size = materialBuffer.size(); for(PxU32 i=0; i<size; i++) { const NpScene::MaterialEvent& event = materialBuffer[i]; const NpMaterialT* masMat = masterMaterial[event.mHandle]; switch(event.mType) { case NpScene::MATERIAL_ADD: if(masMat) { MaterialCoreT* materialCore = &masterMaterial[event.mHandle]->mMaterial; pxsMaterialManager.setMaterial(materialCore); context->registerMaterial(*materialCore); } break; case NpScene::MATERIAL_UPDATE: if(masMat) { MaterialCoreT* materialCore = &masterMaterial[event.mHandle]->mMaterial; pxsMaterialManager.updateMaterial(materialCore); context->updateMaterial(*materialCore); } break; case NpScene::MATERIAL_REMOVE: if (event.mHandle < pxsMaterialManager.getMaxSize()) // materials might get added and then removed again immediately. However, the add does not get processed (see case MATERIAL_ADD above), { // so the remove might end up reading out of bounds memory unless checked. MaterialCoreT* materialCore = pxsMaterialManager.getMaterial(event.mHandle); if (materialCore->mMaterialIndex == event.mHandle) { context->unregisterMaterial(*materialCore); pxsMaterialManager.removeMaterial(materialCore); } } break; }; } materialBuffer.resize(0); } void NpScene::syncMaterialEvents() { //sync all the material events PxvNphaseImplementationContext* context = mScene.getLowLevelContext()->getNphaseImplementationContext(); updateLowLevelMaterials<NpMaterial, PxsMaterialManager, PxsMaterialCore>(mPhysics, mSceneMaterialBufferLock, mScene.getMaterialManager(), mSceneMaterialBuffer, context); #if PX_SUPPORT_GPU_PHYSX updateLowLevelMaterials<NpFEMSoftBodyMaterial, PxsFEMMaterialManager, PxsFEMSoftBodyMaterialCore> (mPhysics, mSceneFEMSoftBodyMaterialBufferLock, mScene.getFEMMaterialManager(), mSceneFEMSoftBodyMaterialBuffer, context); updateLowLevelMaterials<NpPBDMaterial, PxsPBDMaterialManager, PxsPBDMaterialCore> (mPhysics, mScenePBDMaterialBufferLock, mScene.getPBDMaterialManager(), mScenePBDMaterialBuffer, context); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION updateLowLevelMaterials<NpFEMClothMaterial, PxsFEMClothMaterialManager, PxsFEMClothMaterialCore> (mPhysics, mSceneFEMClothMaterialBufferLock, mScene.getFEMClothMaterialManager(), mSceneFEMClothMaterialBuffer, context); updateLowLevelMaterials<NpFLIPMaterial, PxsFLIPMaterialManager, PxsFLIPMaterialCore> (mPhysics, mSceneFLIPMaterialBufferLock, mScene.getFLIPMaterialManager(), mSceneFLIPMaterialBuffer, context); updateLowLevelMaterials<NpMPMMaterial, PxsMPMMaterialManager, PxsMPMMaterialCore> (mPhysics, mSceneMPMMaterialBufferLock, mScene.getMPMMaterialManager(), mSceneMPMMaterialBuffer, context); #endif #endif } /////////////////////////////////////////////////////////////////////////////// bool NpScene::simulateOrCollide(PxReal elapsedTime, PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation, const char* invalidCallMsg, Sc::SimulationStage::Enum simStage) { PX_SIMD_GUARD; { // write guard must end before simulation kicks off worker threads // otherwise the simulation callbacks could overlap with this function // and perform API reads,triggering an error NP_WRITE_CHECK(this); PX_PROFILE_START_CROSSTHREAD("Basic.simulate", getContextId()); if(getSimulationStage() != Sc::SimulationStage::eCOMPLETE) { //fetchResult doesn't get called return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, invalidCallMsg); } #if PX_SUPPORT_GPU_PHYSX if (mCudaContextManager) { if (mScene.isUsingGpuDynamicsOrBp()) { PxCUresult lastError = mCudaContextManager->getCudaContext()->getLastError(); if (lastError) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PhysX Internal CUDA error. Simulation can not continue! Error code %i!\n", PxI32(lastError)); //return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "PhysX Internal CUDA error. Simulation can not continue!"); } } } #endif PX_CHECK_AND_RETURN_VAL(elapsedTime > 0, "PxScene::collide/simulate: The elapsed time must be positive!", false); PX_CHECK_AND_RETURN_VAL((size_t(scratchBlock)&15) == 0, "PxScene::simulate: scratch block must be 16-byte aligned!", false); PX_CHECK_AND_RETURN_VAL((scratchBlockSize&16383) == 0, "PxScene::simulate: scratch block size must be a multiple of 16K", false); #if PX_SUPPORT_PVD //signal the frame is starting. mScenePvdClient.frameStart(elapsedTime); #endif #if PX_ENABLE_DEBUG_VISUALIZATION visualize(); #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif updateDirtyShaders(); #if PX_SUPPORT_PVD mScenePvdClient.updateJoints(); #endif mScene.setScratchBlock(scratchBlock, scratchBlockSize); mElapsedTime = elapsedTime; if (simStage == Sc::SimulationStage::eCOLLIDE) mScene.setElapsedTime(elapsedTime); mControllingSimulation = controlSimulation; syncMaterialEvents(); setSimulationStage(simStage); setAPIWriteToForbidden(); setAPIReadToForbidden(); mScene.setCollisionPhaseToActive(); } { PX_PROFILE_ZONE("Sim.taskFrameworkSetup", getContextId()); if (controlSimulation) { { PX_PROFILE_ZONE("Sim.resetDependencies", getContextId()); // Only reset dependencies, etc if we own the TaskManager. Will be false // when an NpScene is controlled by an APEX scene. mTaskManager->resetDependencies(); } mTaskManager->startSimulation(); } if (simStage == Sc::SimulationStage::eCOLLIDE) { mCollisionCompletion.setContinuation(*mTaskManager, completionTask); mSceneCollide.setContinuation(&mCollisionCompletion); //Initialize scene completion task mSceneCompletion.setContinuation(*mTaskManager, NULL); mCollisionCompletion.removeReference(); mSceneCollide.removeReference(); } else { mSceneCompletion.setContinuation(*mTaskManager, completionTask); mSceneExecution.setContinuation(*mTaskManager, &mSceneCompletion); mSceneCompletion.removeReference(); mSceneExecution.removeReference(); } } return true; } bool NpScene::simulate(PxReal elapsedTime, PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation) { return simulateOrCollide( elapsedTime, completionTask, scratchBlock, scratchBlockSize, controlSimulation, "PxScene::simulate: Simulation is still processing last simulate call, you should call fetchResults()!", Sc::SimulationStage::eADVANCE); } bool NpScene::advance(PxBaseTask* completionTask) { NP_WRITE_CHECK(this); //issue error if advance() doesn't get called between fetchCollision() and fetchResult() if(getSimulationStage() != Sc::SimulationStage::eFETCHCOLLIDE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::advance: advance() called illegally! advance() needed to be called after fetchCollision() and before fetchResult()!!"); //if mSimulateStage == eFETCHCOLLIDE, which means collide() has been kicked off and finished running, we can run advance() safely { //change the mSimulateStaget to eADVANCE to indicate the next stage to run is fetchResult() setSimulationStage(Sc::SimulationStage::eADVANCE); setAPIReadToForbidden(); { PX_PROFILE_ZONE("Sim.taskFrameworkSetup", getContextId()); mSceneCompletion.setDependent(completionTask); mSceneAdvance.setContinuation(*mTaskManager, &mSceneCompletion); mSceneCompletion.removeReference(); mSceneAdvance.removeReference(); } } return true; } bool NpScene::collide(PxReal elapsedTime, PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation) { return simulateOrCollide( elapsedTime, completionTask, scratchBlock, scratchBlockSize, controlSimulation, "PxScene::collide: collide() called illegally! If it isn't the first frame, collide() needed to be called between fetchResults() and fetchCollision(). Otherwise, collide() needed to be called before fetchCollision()", Sc::SimulationStage::eCOLLIDE); } bool NpScene::checkCollisionInternal(bool block) { PX_PROFILE_ZONE("Basic.checkCollision", getContextId()); return mCollisionDone.wait(block ? PxSync::waitForever : 0); } bool NpScene::checkCollision(bool block) { return checkCollisionInternal(block); } bool NpScene::fetchCollision(bool block) { if(getSimulationStage() != Sc::SimulationStage::eCOLLIDE) { return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchCollision: fetchCollision() should be called after collide() and before advance()!"); } //if collision isn't finish running (and block is false), then return false if(!checkCollisionInternal(block)) return false; // take write check *after* collision() finished, otherwise // we will block fetchCollision() from using the API NP_WRITE_CHECK_NOREENTRY(this); setSimulationStage(Sc::SimulationStage::eFETCHCOLLIDE); setAPIReadToAllowed(); return true; } void NpScene::flushSimulation(bool sendPendingReports) { PX_PROFILE_ZONE("API.flushSimulation", getContextId()); NP_WRITE_CHECK_NOREENTRY(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::flushSimulation(): This call is not allowed while the simulation is running. Call will be ignored") PX_SIMD_GUARD; mScene.flush(sendPendingReports); getSQAPI().flushMemory(); //!!! TODO: Shrink all NpObject lists? } /* Replaces finishRun() with the addition of appropriate thread sync(pulled out of PhysicsThread()) Note: this function can be called from the application thread or the physics thread, depending on the scene flags. */ void NpScene::executeScene(PxBaseTask* continuation) { mScene.simulate(mElapsedTime, continuation); } void NpScene::executeCollide(PxBaseTask* continuation) { mScene.collide(mElapsedTime, continuation); } void NpScene::executeAdvance(PxBaseTask* continuation) { mScene.advance(mElapsedTime, continuation); } /////////////////////////////////////////////////////////////////////////////// #define IMPLEMENT_MATERIAL(MaterialType, CoreType, LockName, BufferName) \ void NpScene::addMaterial(const MaterialType& mat) \ { \ const CoreType& material = mat.mMaterial; \ PxMutex::ScopedLock lock(LockName); \ BufferName.pushBack(MaterialEvent(material.mMaterialIndex, MATERIAL_ADD)); \ CREATE_PVD_INSTANCE(&material) \ } \ \ void NpScene::updateMaterial(const MaterialType& mat) \ { \ const CoreType& material = mat.mMaterial; \ PxMutex::ScopedLock lock(LockName); \ BufferName.pushBack(MaterialEvent(material.mMaterialIndex, MATERIAL_UPDATE)); \ UPDATE_PVD_PROPERTIES(&material) \ } \ \ void NpScene::removeMaterial(const MaterialType& mat) \ { \ const CoreType& material = mat.mMaterial; \ if(material.mMaterialIndex == MATERIAL_INVALID_HANDLE) \ return; \ PxMutex::ScopedLock lock(LockName); \ BufferName.pushBack(MaterialEvent(material.mMaterialIndex, MATERIAL_REMOVE)); \ RELEASE_PVD_INSTANCE(&material); \ } IMPLEMENT_MATERIAL(NpMaterial, PxsMaterialCore, mSceneMaterialBufferLock, mSceneMaterialBuffer) #if PX_SUPPORT_GPU_PHYSX IMPLEMENT_MATERIAL(NpFEMSoftBodyMaterial, PxsFEMSoftBodyMaterialCore, mSceneFEMSoftBodyMaterialBufferLock, mSceneFEMSoftBodyMaterialBuffer) #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION IMPLEMENT_MATERIAL(NpFEMClothMaterial, PxsFEMClothMaterialCore, mSceneFEMClothMaterialBufferLock, mSceneFEMClothMaterialBuffer) #endif IMPLEMENT_MATERIAL(NpPBDMaterial, PxsPBDMaterialCore, mScenePBDMaterialBufferLock, mScenePBDMaterialBuffer) #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION IMPLEMENT_MATERIAL(NpFLIPMaterial, PxsFLIPMaterialCore, mSceneFLIPMaterialBufferLock, mSceneFLIPMaterialBuffer) IMPLEMENT_MATERIAL(NpMPMMaterial, PxsMPMMaterialCore, mSceneMPMMaterialBufferLock, mSceneMPMMaterialBuffer) #endif #endif /////////////////////////////////////////////////////////////////////////////// void NpScene::setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((group1 < PX_MAX_DOMINANCE_GROUP && group2 < PX_MAX_DOMINANCE_GROUP), "PxScene::setDominanceGroupPair: invalid params! Groups must be <= 31!"); //can't change matrix diagonal PX_CHECK_AND_RETURN(group1 != group2, "PxScene::setDominanceGroupPair: invalid params! Groups must be unequal! Can't change matrix diagonal!"); PX_CHECK_AND_RETURN( ((dominance.dominance0) == 1.0f && (dominance.dominance1 == 1.0f)) || ((dominance.dominance0) == 1.0f && (dominance.dominance1 == 0.0f)) || ((dominance.dominance0) == 0.0f && (dominance.dominance1 == 1.0f)) , "PxScene::setDominanceGroupPair: invalid params! dominance must be one of (1,1), (1,0), or (0,1)!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setDominanceGroupPair() not allowed while simulation is running. Call will be ignored.") mScene.setDominanceGroupPair(group1, group2, dominance); updatePvdProperties(); } PxDominanceGroupPair NpScene::getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const { NP_READ_CHECK(this); PX_CHECK_AND_RETURN_VAL((group1 < PX_MAX_DOMINANCE_GROUP && group2 < PX_MAX_DOMINANCE_GROUP), "PxScene::getDominanceGroupPair: invalid params! Groups must be <= 31!", PxDominanceGroupPair(PxU8(1u), PxU8(1u))); return mScene.getDominanceGroupPair(group1, group2); } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX void NpScene::updatePhysXIndicator() { PxIntBool isGpu = mScene.isUsingGpuDynamicsOrBp(); mPhysXIndicator.setIsGpu(isGpu != 0); } #endif //PX_SUPPORT_GPU_PHYSX /////////////////////////////////////////////////////////////////////////////// void NpScene::setSolverBatchSize(PxU32 solverBatchSize) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setSolverBatchSize() not allowed while simulation is running. Call will be ignored.") mScene.setSolverBatchSize(solverBatchSize); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, solverBatchSize, static_cast<PxScene&>(*this), solverBatchSize) } PxU32 NpScene::getSolverBatchSize(void) const { NP_READ_CHECK(this); // get from our local copy return mScene.getSolverBatchSize(); } void NpScene::setSolverArticulationBatchSize(PxU32 solverBatchSize) { NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setSolverArticulationBatchSize() not allowed while simulation is running. Call will be ignored.") mScene.setSolverArticBatchSize(solverBatchSize); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, solverArticulationBatchSize, static_cast<PxScene&>(*this), solverBatchSize) } PxU32 NpScene::getSolverArticulationBatchSize(void) const { NP_READ_CHECK(this); // get from our local copy return mScene.getSolverArticBatchSize(); } /////////////////////////////////////////////////////////////////////////////// bool NpScene::setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN_VAL(PxIsFinite(value), "PxScene::setVisualizationParameter: value is not valid.", false); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(this, "PxScene::setVisualizationParameter() not allowed while simulation is running. Call will be ignored.", false) if (param >= PxVisualizationParameter::eNUM_VALUES) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "setVisualizationParameter: parameter out of range."); else if (value < 0.0f) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "setVisualizationParameter: value must be larger or equal to 0."); else { mScene.setVisualizationParameter(param, value); return true; } } PxReal NpScene::getVisualizationParameter(PxVisualizationParameter::Enum param) const { if (param < PxVisualizationParameter::eNUM_VALUES) return mScene.getVisualizationParameter(param); else outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "getVisualizationParameter: param is not an enum."); return 0.0f; } void NpScene::setVisualizationCullingBox(const PxBounds3& box) { NP_WRITE_CHECK(this); PX_CHECK_MSG(box.isValid(), "PxScene::setVisualizationCullingBox(): invalid bounds provided!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setVisualizationCullingBox() not allowed while simulation is running. Call will be ignored.") mScene.setVisualizationCullingBox(box); } PxBounds3 NpScene::getVisualizationCullingBox() const { NP_READ_CHECK(this); const PxBounds3& bounds = mScene.getVisualizationCullingBox(); PX_ASSERT(bounds.isValid()); return bounds; } void NpScene::setNbContactDataBlocks(PxU32 numBlocks) { PX_CHECK_AND_RETURN((getSimulationStage() == Sc::SimulationStage::eCOMPLETE), "PxScene::setNbContactDataBlock: This call is not allowed while the simulation is running. Call will be ignored!"); mScene.setNbContactDataBlocks(numBlocks); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, nbContactDataBlocks, static_cast<PxScene&>(*this), numBlocks) } PxU32 NpScene::getNbContactDataBlocksUsed() const { PX_CHECK_AND_RETURN_VAL((getSimulationStage() == Sc::SimulationStage::eCOMPLETE), "PxScene::getNbContactDataBlocksUsed: This call is not allowed while the simulation is running. Returning 0.", 0); return mScene.getNbContactDataBlocksUsed(); } PxU32 NpScene::getMaxNbContactDataBlocksUsed() const { PX_CHECK_AND_RETURN_VAL((getSimulationStage() == Sc::SimulationStage::eCOMPLETE), "PxScene::getMaxNbContactDataBlocksUsed: This call is not allowed while the simulation is running. Returning 0.", 0); return mScene.getMaxNbContactDataBlocksUsed(); } PxU32 NpScene::getTimestamp() const { return mScene.getTimeStamp(); } PxCpuDispatcher* NpScene::getCpuDispatcher() const { return mTaskManager->getCpuDispatcher(); } PxCudaContextManager* NpScene::getCudaContextManager() const { return mCudaContextManager; } void NpScene::setMaxBiasCoefficient(const PxReal coeff) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((coeff>=0.0f), "PxScene::setMaxBiasCoefficient(): coefficient has to be in [0, PX_MAX_F32]!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setMaxBiasCoefficient() not allowed while simulation is running. Call will be ignored.") mScene.setMaxBiasCoefficient(coeff); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, maxBiasCoefficient, static_cast<PxScene&>(*this), coeff) } PxReal NpScene::getMaxBiasCoefficient() const { NP_READ_CHECK(this); return mScene.getMaxBiasCoefficient(); } void NpScene::setFrictionOffsetThreshold(const PxReal t) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((t>=0.0f), "PxScene::setFrictionOffsetThreshold(): threshold value has to be in [0, PX_MAX_F32)!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setFrictionOffsetThreshold() not allowed while simulation is running. Call will be ignored.") mScene.setFrictionOffsetThreshold(t); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, frictionOffsetThreshold, static_cast<PxScene&>(*this), t) } PxReal NpScene::getFrictionOffsetThreshold() const { NP_READ_CHECK(this); return mScene.getFrictionOffsetThreshold(); } void NpScene::setFrictionCorrelationDistance(const PxReal t) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((t >= 0.0f), "PxScene::setFrictionCorrelationDistance(): threshold value has to be in [0, PX_MAX_F32)!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::setFrictionCorrelationDistance() not allowed while simulation is running. Call will be ignored.") mScene.setFrictionCorrelationDistance(t); updatePvdProperties(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxScene, frictionCorrelationDistance, static_cast<PxScene&>(*this), t) } PxReal NpScene::getFrictionCorrelationDistance() const { NP_READ_CHECK(this); return mScene.getFrictionCorrelationDistance(); } PxU32 NpScene::getContactReportStreamBufferSize() const { NP_READ_CHECK(this); return mScene.getDefaultContactReportStreamBufferSize(); } #if PX_CHECKED void NpScene::checkPositionSanity(const PxRigidActor& a, const PxTransform& pose, const char* fnName) const { if(!mSanityBounds.contains(pose.p)) PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "%s: actor pose for %lp is outside sanity bounds\n", fnName, &a); } #endif namespace { struct ThreadReadWriteCount { ThreadReadWriteCount(const size_t data) : readDepth(data & 0xFF), writeDepth((data >> 8) & 0xFF), readLockDepth((data >> 16) & 0xFF), writeLockDepth((data >> 24) & 0xFF) { } size_t getData() const { return size_t(writeLockDepth) << 24 | size_t(readLockDepth) << 16 | size_t(writeDepth) << 8 | size_t(readDepth); } PxU8 readDepth; // depth of re-entrant reads PxU8 writeDepth; // depth of re-entrant writes PxU8 readLockDepth; // depth of read-locks PxU8 writeLockDepth; // depth of write-locks }; } #if NP_ENABLE_THREAD_CHECKS NpScene::StartWriteResult::Enum NpScene::startWrite(bool allowReentry) { PX_COMPILE_TIME_ASSERT(sizeof(ThreadReadWriteCount) == 4); if (mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK) { ThreadReadWriteCount localCounts(PxTlsGetValue(mThreadReadWriteDepth)); if (mBetweenFetchResults) return StartWriteResult::eIN_FETCHRESULTS; // ensure we already have the write lock return localCounts.writeLockDepth > 0 ? StartWriteResult::eOK : StartWriteResult::eNO_LOCK; } { ThreadReadWriteCount localCounts(PxTlsGetValue(mThreadReadWriteDepth)); StartWriteResult::Enum result; if (mBetweenFetchResults) result = StartWriteResult::eIN_FETCHRESULTS; // check we are the only thread reading (allows read->write order on a single thread) and no other threads are writing else if (mConcurrentReadCount != localCounts.readDepth || mConcurrentWriteCount != localCounts.writeDepth) result = StartWriteResult::eRACE_DETECTED; else result = StartWriteResult::eOK; // increment shared write counter PxAtomicIncrement(&mConcurrentWriteCount); // in the normal case (re-entry is allowed) then we simply increment // the writeDepth by 1, otherwise (re-entry is not allowed) increment // by 2 to force subsequent writes to fail by creating a mismatch between // the concurrent write counter and the local counter, any value > 1 will do localCounts.writeDepth += allowReentry ? 1 : 2; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); if (result != StartWriteResult::eOK) PxAtomicIncrement(&mConcurrentErrorCount); return result; } } void NpScene::stopWrite(bool allowReentry) { if (!(mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)) { PxAtomicDecrement(&mConcurrentWriteCount); // decrement depth of writes for this thread ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); // see comment in startWrite() if (allowReentry) localCounts.writeDepth--; else localCounts.writeDepth-=2; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); } } bool NpScene::startRead() const { if (mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK) { ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); // ensure we already have the write or read lock return localCounts.writeLockDepth > 0 || localCounts.readLockDepth > 0; } else { PxAtomicIncrement(&mConcurrentReadCount); // update current threads read depth ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); localCounts.readDepth++; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); // success if the current thread is already performing a write (API re-entry) or no writes are in progress const bool success = (localCounts.writeDepth > 0 || mConcurrentWriteCount == 0); if (!success) PxAtomicIncrement(&mConcurrentErrorCount); return success; } } void NpScene::stopRead() const { if (!(mScene.getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)) { PxAtomicDecrement(&mConcurrentReadCount); // update local threads read depth ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); localCounts.readDepth--; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); } } #else NpScene::StartWriteResult::Enum NpScene::startWrite(bool) { PX_ASSERT(0); return NpScene::StartWriteResult::eOK; } void NpScene::stopWrite(bool) {} bool NpScene::startRead() const { PX_ASSERT(0); return false; } void NpScene::stopRead() const {} #endif // NP_ENABLE_THREAD_CHECKS void NpScene::lockRead(const char* /*file*/, PxU32 /*line*/) { // increment this threads read depth ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); localCounts.readLockDepth++; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); // if we are the current writer then increment the reader count but don't actually lock (allow reading from threads with write ownership) if(localCounts.readLockDepth == 1) mRWLock.lockReader(mCurrentWriter != PxThread::getId()); } void NpScene::unlockRead() { // increment this threads read depth ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); if(localCounts.readLockDepth < 1) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::unlockRead() called without matching call to PxScene::lockRead(), behaviour will be undefined."); return; } localCounts.readLockDepth--; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); // only unlock on last read if(localCounts.readLockDepth == 0) mRWLock.unlockReader(); } void NpScene::lockWrite(const char* file, PxU32 line) { // increment this threads write depth ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); if (localCounts.writeLockDepth == 0 && localCounts.readLockDepth > 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, file?file:__FILE__, file?int(line):__LINE__, "PxScene::lockWrite() detected after a PxScene::lockRead(), lock upgrading is not supported, behaviour will be undefined."); return; } localCounts.writeLockDepth++; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); // only lock on first call if (localCounts.writeLockDepth == 1) mRWLock.lockWriter(); PX_ASSERT(mCurrentWriter == 0 || mCurrentWriter == PxThread::getId()); // set ourselves as the current writer mCurrentWriter = PxThread::getId(); } void NpScene::unlockWrite() { // increment this thread's write depth ThreadReadWriteCount localCounts (PxTlsGetValue(mThreadReadWriteDepth)); if (localCounts.writeLockDepth < 1) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::unlockWrite() called without matching call to PxScene::lockWrite(), behaviour will be undefined."); return; } localCounts.writeLockDepth--; PxTlsSetValue(mThreadReadWriteDepth, localCounts.getData()); PX_ASSERT(mCurrentWriter == PxThread::getId()); if (localCounts.writeLockDepth == 0) { mCurrentWriter = 0; mRWLock.unlockWriter(); } } PxReal NpScene::getWakeCounterResetValue() const { NP_READ_CHECK(this); return getWakeCounterResetValueInternal(); } static PX_FORCE_INLINE void shiftRigidActor(PxRigidActor* a, const PxVec3& shift) { PxActorType::Enum t = a->getType(); if (t == PxActorType::eRIGID_DYNAMIC) { NpRigidDynamic* rd = static_cast<NpRigidDynamic*>(a); rd->getCore().onOriginShift(shift); } else if (t == PxActorType::eRIGID_STATIC) { NpRigidStatic* rs = static_cast<NpRigidStatic*>(a); rs->getCore().onOriginShift(shift); } else { PX_ASSERT(t == PxActorType::eARTICULATION_LINK); NpArticulationLink* al = static_cast<NpArticulationLink*>(a); al->getCore().onOriginShift(shift); } } template<typename T> static void shiftRigidActors(PxArray<T*>& rigidActorList, const PxVec3& shift) { const PxU32 prefetchLookAhead = 4; PxU32 rigidCount = rigidActorList.size(); T*const* rigidActors = rigidActorList.begin(); PxU32 batchIterCount = rigidCount / prefetchLookAhead; PxU32 idx = 0; for(PxU32 i=0; i < batchIterCount; i++) { // prefetch elements for next batch if (i < (batchIterCount-1)) { PxPrefetchLine(rigidActors[idx + prefetchLookAhead]); PxPrefetchLine(reinterpret_cast<PxU8*>(rigidActors[idx + prefetchLookAhead]) + 128); PxPrefetchLine(rigidActors[idx + prefetchLookAhead + 1]); PxPrefetchLine(reinterpret_cast<PxU8*>(rigidActors[idx + prefetchLookAhead + 1]) + 128); PxPrefetchLine(rigidActors[idx + prefetchLookAhead + 2]); PxPrefetchLine(reinterpret_cast<PxU8*>(rigidActors[idx + prefetchLookAhead + 2]) + 128); PxPrefetchLine(rigidActors[idx + prefetchLookAhead + 3]); PxPrefetchLine(reinterpret_cast<PxU8*>(rigidActors[idx + prefetchLookAhead + 3]) + 128); } else { for(PxU32 k=(idx + prefetchLookAhead); k < rigidCount; k++) { PxPrefetchLine(rigidActors[k]); PxPrefetchLine(reinterpret_cast<PxU8*>(rigidActors[k]) + 128); } } for(PxU32 j=idx; j < (idx + prefetchLookAhead); j++) { shiftRigidActor(rigidActors[j], shift); } idx += prefetchLookAhead; } // process remaining objects for(PxU32 i=idx; i < rigidCount; i++) { shiftRigidActor(rigidActors[i], shift); } } void NpScene::shiftOrigin(const PxVec3& shift) { PX_PROFILE_ZONE("API.shiftOrigin", getContextId()); NP_WRITE_CHECK(this); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::shiftOrigin() not allowed while simulation is running. Call will be ignored.") PX_SIMD_GUARD; shiftRigidActors(mRigidDynamics, shift); shiftRigidActors(mRigidStatics, shift); PxArticulationReducedCoordinate*const* articulations = mArticulations.getEntries(); for(PxU32 i=0; i < mArticulations.size(); i++) { PxArticulationReducedCoordinate* np = (articulations[i]); NpArticulationLink*const* links = static_cast<NpArticulationReducedCoordinate*>(np)->getLinks(); for(PxU32 j=0; j < np->getNbLinks(); j++) { shiftRigidActor(links[j], shift); } } mScene.shiftOrigin(shift); PVD_ORIGIN_SHIFT(shift); // shift scene query related data structures getSQAPI().shiftOrigin(shift); #if PX_ENABLE_DEBUG_VISUALIZATION // debug visualization mRenderBuffer.shift(-shift); #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif } PxPvdSceneClient* NpScene::getScenePvdClient() { #if PX_SUPPORT_PVD return &mScenePvdClient; #else return NULL; #endif } void NpScene::copyArticulationData(void* jointData, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbCopyArticulations, CUevent copyEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::copyArticulationData() not allowed while simulation is running. Call will be ignored."); if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::copyArticulationData(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } if (dataType == PxArticulationGpuDataType::eLINK_FORCE || dataType == PxArticulationGpuDataType::eLINK_TORQUE || dataType == PxArticulationGpuDataType::eFIXED_TENDON || dataType == PxArticulationGpuDataType::eFIXED_TENDON_JOINT || dataType == PxArticulationGpuDataType::eSPATIAL_TENDON || dataType == PxArticulationGpuDataType::eSPATIAL_TENDON_ATTACHMENT) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::copyArticulationData, specified data is write only."); return; } mScene.getSimulationController()->copyArticulationData(jointData, index, dataType, nbCopyArticulations, copyEvent); } void NpScene::applyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbUpdatedArticulations, CUevent waitEvent, CUevent signalEvent) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::applyArticulationData() not allowed while simulation is running. Call will be ignored."); if (!data || !index) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyArticulationData, data and/or index has to be valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyArticulationData(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } if (dataType == PxArticulationGpuDataType::eJOINT_ACCELERATION || dataType == PxArticulationGpuDataType::eJOINT_SOLVER_FORCE || dataType == PxArticulationGpuDataType::eSENSOR_FORCE || dataType == PxArticulationGpuDataType::eLINK_TRANSFORM || dataType == PxArticulationGpuDataType::eLINK_VELOCITY || dataType == PxArticulationGpuDataType::eLINK_ACCELERATION || dataType == PxArticulationGpuDataType::eLINK_INCOMING_JOINT_FORCE ) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyArticulationData, specified data is read only."); return; } mScene.getSimulationController()->applyArticulationData(data,index, dataType, nbUpdatedArticulations, waitEvent, signalEvent); } void NpScene::updateArticulationsKinematic(CUevent signalEvent) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::updateArticulationsKinematic() not allowed while simulation is running. Call will be ignored."); if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::updateArticulationsKinematic(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->updateArticulationsKinematic(signalEvent); } void NpScene::copySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbCopySoftBodies, const PxU32 maxSize, CUevent copyEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::copySoftBodyData() not allowed while simulation is running. Call will be ignored."); //if ((mScene.getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && mScene.isUsingGpuRigidBodies()) mScene.getSimulationController()->copySoftBodyData(data, dataSizes, softBodyIndices, flag, nbCopySoftBodies, maxSize, copyEvent); } void NpScene::applySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbUpdatedSoftBodies, const PxU32 maxSize, CUevent applyEvent, CUevent signalEvent) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::applySoftBodyData() not allowed while simulation is running. Call will be ignored."); //if ((mScene.getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && mScene.isUsingGpuRigidBodies()) mScene.getSimulationController()->applySoftBodyData(data, dataSizes, softBodyIndices, flag, nbUpdatedSoftBodies, maxSize, applyEvent, signalEvent); } void NpScene::copyContactData(void* data, const PxU32 maxContactPairs, void* numContactPairs, CUevent copyEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::copyContactData() not allowed while simulation is running. Call will be ignored."); if (!data || !numContactPairs) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::copyContactData, data and/or count has to be valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::copyContactData(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->copyContactData(mScene.getDynamicsContext(), data, maxContactPairs, numContactPairs, copyEvent); } void NpScene::copyBodyData(PxGpuBodyData* data, PxGpuActorPair* index, const PxU32 nbCopyActors, CUevent copyEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::copyBodyData() not allowed while simulation is running. Call will be ignored."); if (!data) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::copyBodyData, data has to be valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::copyBodyData(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->copyBodyData(data, index, nbCopyActors, copyEvent); } void NpScene::applyActorData(void* data, PxGpuActorPair* index, PxActorCacheFlag::Enum flag, const PxU32 nbUpdatedActors, CUevent waitEvent, CUevent signalEvent) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::applyActorData() not allowed while simulation is running. Call will be ignored."); if (!data || !index) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyActorData, data and/or index has to be valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyActorData(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->applyActorData(data, index, flag, nbUpdatedActors, waitEvent, signalEvent); } void NpScene::evaluateSDFDistances(const PxU32* sdfShapeIds, const PxU32 nbShapes, const PxVec4* samplePointsConcatenated, const PxU32* samplePointCountPerShape, const PxU32 maxPointCount, PxVec4* localGradientAndSDFConcatenated, CUevent event) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::evaluateSDFDistances() not allowed while simulation is running. Call will be ignored."); if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::evaluateSDFDistances(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->evaluateSDFDistances(sdfShapeIds, nbShapes, samplePointsConcatenated, samplePointCountPerShape, maxPointCount, localGradientAndSDFConcatenated, event); } void NpScene::computeDenseJacobians(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::computeDenseJacobians() not allowed while simulation is running. Call will be ignored."); if (!indices) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeDenseJacobians, indices have to be a valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeDenseJacobians(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->computeDenseJacobians(indices, nbIndices, computeEvent); } void NpScene::computeGeneralizedMassMatrices(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::computeGeneralizedMassMatrices() not allowed while simulation is running. Call will be ignored."); if (!indices) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeGeneralizedMassMatrices, indices have to be a valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeGeneralizedMassMatrices(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->computeGeneralizedMassMatrices(indices, nbIndices, computeEvent); } void NpScene::computeGeneralizedGravityForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::computeGeneralizedGravityForces() not allowed while simulation is running. Call will be ignored."); if (!indices) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeGeneralizedGravityForces, indices have to be a valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeGeneralizedGravityForces(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->computeGeneralizedGravityForces(indices, nbIndices, getGravity(), computeEvent); } void NpScene::computeCoriolisAndCentrifugalForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent) { PX_CHECK_SCENE_API_READ_FORBIDDEN(this, "PxScene::computeCoriolisAndCentrifugalForces() not allowed while simulation is running. Call will be ignored."); if (!indices) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeCoriolisAndCentrifugalForces, indices have to be a valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::computeCoriolisAndCentrifugalForces(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->computeCoriolisAndCentrifugalForces(indices, nbIndices, computeEvent); } void NpScene::applyParticleBufferData(const PxU32* indices, const PxGpuParticleBufferIndexPair* indexPairs, const PxParticleBufferFlags* flags, PxU32 nbUpdatedBuffers, CUevent waitEvent, CUevent signalEvent) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(this, "PxScene::applyParticleBufferData() not allowed while simulation is running. Call will be ignored."); if (!indices || !flags) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyParticleBufferData, indices and/or flags has to be valid pointer."); return; } if (!isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::applyParticleBufferData(): it is illegal to call this function if the scene is not configured for direct-GPU access or the direct-GPU API has not been initialized yet."); return; } mScene.getSimulationController()->applyParticleBufferData(indices, indexPairs, flags, nbUpdatedBuffers, waitEvent, signalEvent); } PxsSimulationController* NpScene::getSimulationController() { return mScene.getSimulationController(); } void NpScene::setActiveActors(PxActor** actors, PxU32 nbActors) { NP_WRITE_CHECK(this); mScene.setActiveActors(actors, nbActors); } void NpScene::frameEnd() { #if PX_SUPPORT_PVD mScenePvdClient.frameEnd(); #endif } /////////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE PxU32 getShapes(NpRigidStatic& rigid, NpShape* const *& shapes) { return NpRigidStaticGetShapes(rigid, shapes); } PX_FORCE_INLINE PxU32 getShapes(NpRigidDynamic& rigid, NpShape* const *& shapes) { return NpRigidDynamicGetShapes(rigid, shapes); } PX_FORCE_INLINE PxU32 getShapes(NpArticulationLink& rigid, NpShape* const *& shapes) { return NpArticulationGetShapes(rigid, shapes); } PX_FORCE_INLINE NpShape* getShape(NpShape* const* shapeArray, const PxU32 i) { return shapeArray[i]; } PX_FORCE_INLINE NpShape* getShape(Sc::ShapeCore* const* shapeArray, const PxU32 i) { return static_cast<NpShape*>(shapeArray[i]->getPxShape()); } template<class T> PX_FORCE_INLINE static void addActorShapes(T* const* shapeArray, const PxU32 nbShapes, PxActor* pxActor, NpScene* scScene) { PX_ASSERT(pxActor); PX_ASSERT(scScene); PX_ASSERT((0==nbShapes) || shapeArray); for (PxU32 i = 0; i < nbShapes; i++) { NpShape* npShape = getShape(shapeArray, i); PX_ASSERT(npShape); npShape->setSceneIfExclusive(scScene); #if PX_SUPPORT_PVD scScene->getScenePvdClientInternal().createPvdInstance(npShape, *pxActor); #else PX_UNUSED(pxActor); #endif } } template<class T> PX_FORCE_INLINE static void removeActorShapes(T* const* shapeArray, const PxU32 nbShapes, PxActor* pxActor, NpScene* scScene) { PX_ASSERT(pxActor); PX_ASSERT(scScene); PX_ASSERT((0 == nbShapes) || shapeArray); for (PxU32 i = 0; i < nbShapes; i++) { NpShape* npShape = getShape(shapeArray, i); PX_ASSERT(npShape); #if PX_SUPPORT_PVD scScene->getScenePvdClientInternal().releasePvdInstance(npShape, *pxActor); #else PX_UNUSED(pxActor); PX_UNUSED(scScene); #endif npShape->setSceneIfExclusive(NULL); } } void addSimActorToScScene(Sc::Scene& s, NpRigidStatic& staticObject, NpShape* const* npShapes, PxU32 nbShapes, PxBounds3* uninflatedBounds, const BVH* bvh) { PX_UNUSED(bvh); const size_t shapePtrOffset = NpShape::getCoreOffset(); s.addStatic(staticObject.getCore(), npShapes, nbShapes, shapePtrOffset, uninflatedBounds); } template <class T> void addSimActorToScSceneT(Sc::Scene& s, NpRigidBodyTemplate<T>& dynamicObject, NpShape* const* npShapes, PxU32 nbShapes, PxBounds3* uninflatedBounds, const BVH* bvh) { const bool isCompound = bvh ? true : false; const size_t shapePtrOffset = NpShape::getCoreOffset(); s.addBody(dynamicObject.getCore(), npShapes, nbShapes, shapePtrOffset, uninflatedBounds, isCompound); } void addSimActorToScScene(Sc::Scene& s, NpRigidDynamic& dynamicObject, NpShape* const* npShapes, PxU32 nbShapes, PxBounds3* uninflatedBounds, const BVH* bvh) { addSimActorToScSceneT<PxRigidDynamic>(s, dynamicObject, npShapes, nbShapes, uninflatedBounds, bvh); } void addSimActorToScScene(Sc::Scene& s, NpArticulationLink& dynamicObject, NpShape* const* npShapes, PxU32 nbShapes, PxBounds3* uninflatedBounds, const BVH* bvh) { addSimActorToScSceneT<PxArticulationLink>(s, dynamicObject, npShapes, nbShapes, uninflatedBounds, bvh); } PX_FORCE_INLINE static void removeSimActorFromScScene(Sc::Scene& s, NpRigidStatic& staticObject, PxInlineArray<const Sc::ShapeCore*, 64>& scBatchRemovedShapes, bool wakeOnLostTouch) { s.removeStatic(staticObject.getCore(), scBatchRemovedShapes, wakeOnLostTouch); } template <class T> PX_FORCE_INLINE static void removeSimActorFromScSceneT(Sc::Scene& s, NpRigidBodyTemplate<T>& dynamicObject, PxInlineArray<const Sc::ShapeCore*, 64>& scBatchRemovedShapes, bool wakeOnLostTouch) { s.removeBody(dynamicObject.getCore(), scBatchRemovedShapes, wakeOnLostTouch); } PX_FORCE_INLINE static void removeSimActorFromScScene(Sc::Scene& s, NpRigidDynamic& dynamicObject, PxInlineArray<const Sc::ShapeCore*, 64>& scBatchRemovedShapes, bool wakeOnLostTouch) { removeSimActorFromScSceneT<PxRigidDynamic>(s, dynamicObject, scBatchRemovedShapes, wakeOnLostTouch); } PX_FORCE_INLINE static void removeSimActorFromScScene(Sc::Scene& s, NpArticulationLink& dynamicObject, PxInlineArray<const Sc::ShapeCore*, 64>& scBatchRemovedShapes, bool wakeOnLostTouch) { removeSimActorFromScSceneT<PxArticulationLink>(s, dynamicObject, scBatchRemovedShapes, wakeOnLostTouch); } template <class T> PX_FORCE_INLINE static void addSimActor(Sc::Scene& s, T& object, PxBounds3* uninflatedBounds, const BVH* bvh) { NpShape* const* npShapes = NULL; const PxU32 nbShapes = getShapes(object, npShapes); PX_ASSERT((0 == nbShapes) || npShapes); addSimActorToScScene(s, object, npShapes, nbShapes, uninflatedBounds, bvh); NpScene* scScene = object.getNpScene(); addActorShapes(npShapes, nbShapes, &object, scScene); } template <class T> PX_FORCE_INLINE static void removeSimActor(Sc::Scene& s, T& object, bool wakeOnLostTouch) { NpScene* scScene = object.getNpScene(); PxInlineArray<const Sc::ShapeCore*, 64> localShapes; PxInlineArray<const Sc::ShapeCore*, 64>& scBatchRemovedShapes = s.getBatchRemove() ? s.getBatchRemove()->removedShapes : localShapes; removeSimActorFromScScene(s, object, scBatchRemovedShapes, wakeOnLostTouch); Sc::ShapeCore* const* scShapes = const_cast<Sc::ShapeCore*const*>(scBatchRemovedShapes.begin()); const PxU32 nbShapes = scBatchRemovedShapes.size(); PX_ASSERT((0 == nbShapes) || scShapes); removeActorShapes(scShapes, nbShapes, &object, scScene); } // PT: TODO: consider unifying addNonSimActor / removeNonSimActor template <class T> PX_FORCE_INLINE static void addNonSimActor(T& rigid) { NpShape* const* npShapes = NULL; const PxU32 nbShapes = getShapes(rigid, npShapes); PX_ASSERT((0 == nbShapes) || npShapes); NpScene* scScene = rigid.getNpScene(); PX_ASSERT(scScene); addActorShapes(npShapes, nbShapes, &rigid, scScene); } template <class T> PX_FORCE_INLINE static void removeNonSimActor(T& rigid) { NpShape* const* npShapes = NULL; const PxU32 nbShapes = getShapes(rigid, npShapes); PX_ASSERT((0 == nbShapes) || npShapes); NpScene* scScene = rigid.getNpScene(); PX_ASSERT(scScene); removeActorShapes(npShapes, nbShapes, &rigid, scScene); } template <typename T>struct ScSceneFns {}; #if PX_SUPPORT_GPU_PHYSX template<> struct ScSceneFns<NpSoftBody> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpSoftBody& v, PxBounds3*, const BVH*, bool) { s.addSoftBody(v.getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpSoftBody& v, bool /*wakeOnLostTouch*/) { s.removeSoftBody(v.getCore()); } }; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION template<> struct ScSceneFns<NpFEMCloth> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpFEMCloth& v, PxBounds3*, const Gu::BVH*, bool) { s.addFEMCloth(v.getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpFEMCloth& v, bool /*wakeOnLostTouch*/) { s.removeFEMCloth(v.getCore()); } }; #endif template<> struct ScSceneFns<NpPBDParticleSystem> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpPBDParticleSystem& v, PxBounds3*, const BVH*, bool) { s.addParticleSystem(v.getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpPBDParticleSystem& v, bool /*wakeOnLostTouch*/) { s.removeParticleSystem(v.getCore()); } }; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION template<> struct ScSceneFns<NpFLIPParticleSystem> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpFLIPParticleSystem& v, PxBounds3*, const BVH*, bool) { s.addParticleSystem(v.getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpFLIPParticleSystem& v, bool /*wakeOnLostTouch*/) { s.removeParticleSystem(v.getCore()); } }; template<> struct ScSceneFns<NpMPMParticleSystem> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpMPMParticleSystem& v, PxBounds3*, const BVH*, bool) { s.addParticleSystem(v.getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpMPMParticleSystem& v, bool /*wakeOnLostTouch*/) { s.removeParticleSystem(v.getCore()); } }; template<> struct ScSceneFns<NpHairSystem> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpHairSystem& v, PxBounds3*, const BVH*, bool) { s.addHairSystem(v.getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpHairSystem& v, bool /*wakeOnLostTouch*/) { s.removeHairSystem(v.getCore()); } }; #endif #endif template<> struct ScSceneFns<NpArticulationReducedCoordinate> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpArticulationReducedCoordinate& v, PxBounds3*, const BVH*, bool) { s.addArticulation(v.getCore(), v.getRoot()->getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpArticulationReducedCoordinate& v, bool /*wakeOnLostTouch*/) { s.removeArticulation(v.getCore()); } }; template<> struct ScSceneFns<NpArticulationJointReducedCoordinate> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpArticulationJointReducedCoordinate& v, PxBounds3*, const BVH*, bool) { s.addArticulationJoint(v.getCore(), v.getParent().getCore(), v.getChild().getCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpArticulationJointReducedCoordinate& v, bool /*wakeOnLostTouch*/) { s.removeArticulationJoint(v.getCore()); } }; template<> struct ScSceneFns<NpArticulationSpatialTendon> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpArticulationSpatialTendon& v, PxBounds3*, const BVH*, bool) { s.addArticulationTendon(v.getTendonCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpArticulationSpatialTendon& v, bool /*wakeOnLostTouch*/) { s.removeArticulationTendon(v.getTendonCore()); } }; template<> struct ScSceneFns<NpArticulationFixedTendon> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpArticulationFixedTendon& v, PxBounds3*, const BVH*, bool) { s.addArticulationTendon(v.getTendonCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpArticulationFixedTendon& v, bool /*wakeOnLostTouch*/) { s.removeArticulationTendon(v.getTendonCore()); } }; template<> struct ScSceneFns<NpArticulationSensor> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpArticulationSensor& v, PxBounds3*, const BVH*, bool) { s.addArticulationSensor(v.getSensorCore()); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpArticulationSensor& v, bool /*wakeOnLostTouch*/) { s.removeArticulationSensor(v.getSensorCore()); } }; // PT: TODO: refactor with version in NpConstraint.cpp & with NpActor::getFromPxActor static NpActor* getNpActor(PxRigidActor* a) { if(!a) return NULL; const PxType type = a->getConcreteType(); if(type == PxConcreteType::eRIGID_DYNAMIC) return static_cast<NpRigidDynamic*>(a); else if(type == PxConcreteType::eARTICULATION_LINK) return static_cast<NpArticulationLink*>(a); else { PX_ASSERT(type == PxConcreteType::eRIGID_STATIC); return static_cast<NpRigidStatic*>(a); } } template<> struct ScSceneFns<NpConstraint> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpConstraint& v, PxBounds3*, const BVH*, bool) { PxRigidActor* a0, * a1; v.getActors(a0, a1); NpActor* sc0 = getNpActor(a0); NpActor* sc1 = getNpActor(a1); PX_ASSERT((!sc0) || (!(sc0->getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)))); PX_ASSERT((!sc1) || (!(sc1->getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)))); s.addConstraint(v.getCore(), sc0 ? &sc0->getScRigidCore() : NULL, sc1 ? &sc1->getScRigidCore() : NULL); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpConstraint& v, bool /*wakeOnLostTouch*/) { s.removeConstraint(v.getCore()); } }; template<> struct ScSceneFns<NpRigidStatic> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpRigidStatic& v, PxBounds3* uninflatedBounds, const BVH* bvh, bool noSim) { PX_ASSERT(v.getCore().getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)==noSim); if(!noSim) addSimActor(s, v, uninflatedBounds, bvh); else addNonSimActor(v); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpRigidStatic& v, bool wakeOnLostTouch) { if(!v.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)) removeSimActor(s, v, wakeOnLostTouch); else removeNonSimActor(v); } }; template<> struct ScSceneFns<NpRigidDynamic> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpRigidDynamic& v, PxBounds3* uninflatedBounds, const BVH* bvh, bool noSim) { PX_ASSERT(v.getCore().getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)==noSim); if(!noSim) addSimActor(s, v, uninflatedBounds, bvh); else addNonSimActor(v); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpRigidDynamic& v, bool wakeOnLostTouch) { if(!v.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)) removeSimActor(s, v, wakeOnLostTouch); else removeNonSimActor(v); } }; template<> struct ScSceneFns<NpArticulationLink> { static PX_FORCE_INLINE void insert(Sc::Scene& s, NpArticulationLink& v, PxBounds3* uninflatedBounds, const BVH* bvh, bool noSim) { PX_UNUSED(noSim); PX_ASSERT(!noSim); // PT: the flag isn't supported on NpArticulationLink PX_ASSERT(!v.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)); //if(!noSim) addSimActor(s, v, uninflatedBounds, bvh); //else // addNonSimActor(v); } static PX_FORCE_INLINE void remove(Sc::Scene& s, NpArticulationLink& v, bool wakeOnLostTouch) { PX_ASSERT(!v.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)); //if(!v.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)) removeSimActor(s, v, wakeOnLostTouch); //else // removeNonSimActor(v); } }; /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_PVD template<typename T> struct PvdFns { // PT: in the following functions, checkPvdDebugFlag() is done by the callers to save time when functions are called from a loop. static void createInstance(NpScene& scene, Vd::PvdSceneClient& d, T* v) { PX_PROFILE_ZONE("PVD.createPVDInstance", scene.getScScene().getContextId()); PX_UNUSED(scene); d.createPvdInstance(v); } static void updateInstance(NpScene& scene, Vd::PvdSceneClient& d, T* v) { PX_UNUSED(scene); { PX_PROFILE_ZONE("PVD.updatePVDProperties", scene.getScScene().getContextId()); d.updatePvdProperties(v); } } static void releaseInstance(NpScene& scene, Vd::PvdSceneClient& d, T* v) { PX_UNUSED(scene); PX_PROFILE_ZONE("PVD.releasePVDInstance", scene.getScScene().getContextId()); d.releasePvdInstance(v); } }; #endif /////////////////////////////////////////////////////////////////////////////// template<typename T> static void add(NpScene* npScene, T& v, PxBounds3* uninflatedBounds=NULL, const BVH* bvh=NULL, bool noSim=false) { PX_ASSERT(!npScene->isAPIWriteForbidden()); v.setNpScene(npScene); ScSceneFns<T>::insert(npScene->getScScene(), v, uninflatedBounds, bvh, noSim); #if PX_SUPPORT_PVD Vd::PvdSceneClient& pvdClient = npScene->getScenePvdClientInternal(); if(pvdClient.checkPvdDebugFlag()) PvdFns<T>::createInstance(*npScene, pvdClient, &v); #endif } template<typename T> static void remove(NpScene* npScene, T& v, bool wakeOnLostTouch=false) { PX_ASSERT(!npScene->isAPIWriteForbidden()); ScSceneFns<T>::remove(npScene->getScScene(), v, wakeOnLostTouch); #if PX_SUPPORT_PVD Vd::PvdSceneClient& pvdClient = npScene->getScenePvdClientInternal(); if(pvdClient.checkPvdDebugFlag()) PvdFns<T>::releaseInstance(*npScene, pvdClient, &v); #endif v.setNpScene(NULL); } template<class T> static void removeRigidNoSimT(NpScene* npScene, T& v) { PX_ASSERT(!npScene->isAPIWriteForbidden()); PX_ASSERT(v.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)); removeNonSimActor(v); #if PX_SUPPORT_PVD Vd::PvdSceneClient& pvdClient = npScene->getScenePvdClientInternal(); if(pvdClient.checkPvdDebugFlag()) PvdFns<T>::releaseInstance(*npScene, pvdClient, &v); #else PX_UNUSED(npScene); #endif v.setNpScene(NULL); } template<class T> static PX_FORCE_INLINE void addActorT(NpScene* npScene, T& actor, bool noSim, PxBounds3* uninflatedBounds, const BVH* bvh) { PX_ASSERT(!npScene->isAPIWriteForbidden()); PX_PROFILE_ZONE("API.addActorToSim", npScene->getScScene().getContextId()); if(!noSim) { // PT: TODO: this codepath re-tests the sim flag and actually supports both cases!!! add<T>(npScene, actor, uninflatedBounds, bvh, noSim); } else { PX_ASSERT(actor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)); actor.setNpScene(npScene); #if PX_SUPPORT_PVD Vd::PvdSceneClient& pvdClient = npScene->getScenePvdClientInternal(); if(pvdClient.checkPvdDebugFlag()) PvdFns<T>::createInstance(*npScene, pvdClient, &actor); #endif OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxScene, actors, static_cast<PxScene &>(*npScene), static_cast<PxActor &>(actor)) addNonSimActor(actor); } } /////////////////////////////////////////////////////////////////////////////// void NpScene::scAddActor(NpRigidStatic& rigidStatic, bool noSim, PxBounds3* uninflatedBounds, const BVH* bvh) { addActorT(this, rigidStatic, noSim, uninflatedBounds, bvh); } void NpScene::scAddActor(NpRigidDynamic& body, bool noSim, PxBounds3* uninflatedBounds, const BVH* bvh) { addActorT(this, body, noSim, uninflatedBounds, bvh); } void NpScene::scAddActor(NpArticulationLink& body, bool noSim, PxBounds3* uninflatedBounds, const BVH* bvh) { addActorT(this, body, noSim, uninflatedBounds, bvh); } /////////////////////////////////////////////////////////////////////////////// // PT: TODO: refactor scRemoveActor for NpRigidStatic & NpRigidDynamic void NpScene::scRemoveActor(NpRigidStatic& rigidStatic, bool wakeOnLostTouch, bool noSim) { PX_ASSERT(!isAPIWriteForbidden()); PX_PROFILE_ZONE("API.removeActorFromSim", getScScene().getContextId()); if(!noSim) remove<NpRigidStatic>(this, rigidStatic, wakeOnLostTouch); else removeRigidNoSimT(this, rigidStatic); } void NpScene::scRemoveActor(NpRigidDynamic& body, bool wakeOnLostTouch, bool noSim) { PX_ASSERT(!isAPIWriteForbidden()); PX_PROFILE_ZONE("API.removeActorFromSim", getScScene().getContextId()); if(!noSim) remove<NpRigidDynamic>(this, body, wakeOnLostTouch); else removeRigidNoSimT(this, body); } void NpScene::scRemoveActor(NpArticulationLink& body, bool wakeOnLostTouch, bool noSim) { PX_ASSERT(!noSim); PX_UNUSED(noSim); PX_ASSERT(!isAPIWriteForbidden()); PX_PROFILE_ZONE("API.removeActorFromSim", getScScene().getContextId()); remove<NpArticulationLink>(this, body, wakeOnLostTouch); } /////////////////////////////////////////////////////////////////////////////// #ifdef NEW_DIRTY_SHADERS_CODE void NpScene::addDirtyConstraint(NpConstraint* constraint) { PX_ASSERT(!constraint->isDirty()); // PT: lock needed because PxConstraint::markDirty() can be called from multiple threads. // PT: TODO: consider optimizing this PxMutex::ScopedLock lock(mDirtyConstraintsLock); mDirtyConstraints.pushBack(constraint); } #endif void NpScene::addToConstraintList(PxConstraint& constraint) { NpConstraint& npConstraint = static_cast<NpConstraint&>(constraint); add<NpConstraint>(this, npConstraint); #ifdef NEW_DIRTY_SHADERS_CODE if(npConstraint.getCore().getFlags() & PxConstraintFlag::eALWAYS_UPDATE) mAlwaysUpdatedConstraints.pushBack(&npConstraint); else { // PT: mark all new constraints dirty to make sure their data is copied at least once mDirtyConstraints.pushBack(&npConstraint); npConstraint.getCore().setDirty(); } #endif } void NpScene::removeFromConstraintList(PxConstraint& constraint) { PX_ASSERT(!isAPIWriteForbidden()); NpConstraint& npConstraint = static_cast<NpConstraint&>(constraint); #ifdef NEW_DIRTY_SHADERS_CODE // PT: TODO: consider optimizing this { if(npConstraint.getCore().isDirty()) mDirtyConstraints.findAndReplaceWithLast(&npConstraint); if(npConstraint.getCore().getFlags() & PxConstraintFlag::eALWAYS_UPDATE) mAlwaysUpdatedConstraints.findAndReplaceWithLast(&npConstraint); } #endif mScene.removeConstraint(npConstraint.getCore()); // Release pvd constraint immediately since delayed removal with already released ext::joints does not work, can't call callback. RELEASE_PVD_INSTANCE(&npConstraint) npConstraint.setNpScene(NULL); } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX void NpScene::scAddSoftBody(NpSoftBody& softBody) { add<NpSoftBody>(this, softBody); } void NpScene::scRemoveSoftBody(NpSoftBody& softBody) { mScene.removeSoftBodySimControl(softBody.getCore()); remove<NpSoftBody>(this, softBody); } //////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpScene::scAddFEMCloth(NpScene* npScene, NpFEMCloth& femCloth) { add<NpFEMCloth>(npScene, femCloth, NULL, NULL); } void NpScene::scRemoveFEMCloth(NpFEMCloth& femCloth) { mScene.removeFEMClothSimControl(femCloth.getCore()); remove<NpFEMCloth>(this, femCloth, false); } #endif //////////////////////////////////////////////////////////////////////////////// void NpScene::scAddParticleSystem(NpPBDParticleSystem& particleSystem) { add<NpPBDParticleSystem>(this, particleSystem); } void NpScene::scRemoveParticleSystem(NpPBDParticleSystem& particleSystem) { mScene.removeParticleSystemSimControl(particleSystem.getCore()); remove<NpPBDParticleSystem>(this, particleSystem); } //////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpScene::scAddParticleSystem(NpFLIPParticleSystem& particleSystem) { add<NpFLIPParticleSystem>(this, particleSystem); } void NpScene::scRemoveParticleSystem(NpFLIPParticleSystem& particleSystem) { mScene.removeParticleSystemSimControl(particleSystem.getCore()); remove<NpFLIPParticleSystem>(this, particleSystem); } //////////////////////////////////////////////////////////////////////////////// void NpScene::scAddParticleSystem(NpMPMParticleSystem& particleSystem) { add<NpMPMParticleSystem>(this, particleSystem); } void NpScene::scRemoveParticleSystem(NpMPMParticleSystem& particleSystem) { mScene.removeParticleSystemSimControl(particleSystem.getCore()); remove<NpMPMParticleSystem>(this, particleSystem); } //////////////////////////////////////////////////////////////////////////////// void NpScene::scAddHairSystem(NpHairSystem& hairSystem) { add<NpHairSystem>(this, hairSystem); } void NpScene::scRemoveHairSystem(NpHairSystem& hairSystem) { mScene.removeHairSystemSimControl(hairSystem.getCore()); remove<NpHairSystem>(this, hairSystem); } #endif #endif /////////////////////////////////////////////////////////////////////////////// void NpScene::scAddArticulation(NpArticulationReducedCoordinate& articulation) { add<NpArticulationReducedCoordinate>(this, articulation); } void NpScene::scRemoveArticulation(NpArticulationReducedCoordinate& articulation) { mScene.removeArticulationSimControl(articulation.getCore()); remove<NpArticulationReducedCoordinate>(this, articulation); } /////////////////////////////////////////////////////////////////////////////// void NpScene::scAddArticulationJoint(NpArticulationJointReducedCoordinate& joint) { add<NpArticulationJointReducedCoordinate>(this, joint); } void NpScene::scRemoveArticulationJoint(NpArticulationJointReducedCoordinate& joint) { remove<NpArticulationJointReducedCoordinate>(this, joint); } /////////////////////////////////////////////////////////////////////////////// void NpScene::scAddArticulationSpatialTendon(NpArticulationSpatialTendon& tendon) { add<NpArticulationSpatialTendon>(this, tendon); } void NpScene::scRemoveArticulationSpatialTendon(NpArticulationSpatialTendon& tendon) { remove<NpArticulationSpatialTendon>(this, tendon); } /////////////////////////////////////////////////////////////////////////////// void NpScene::scAddArticulationFixedTendon(NpArticulationFixedTendon& tendon) { add<NpArticulationFixedTendon>(this, tendon); } void NpScene::scRemoveArticulationFixedTendon(NpArticulationFixedTendon& tendon) { remove<NpArticulationFixedTendon>(this, tendon); } void NpScene::scAddArticulationSensor(NpArticulationSensor& sensor) { add<NpArticulationSensor>(this, sensor); } void NpScene::scRemoveArticulationSensor(NpArticulationSensor& sensor) { remove<NpArticulationSensor>(this, sensor); } /////////////////////////////////////////////////////////////////////////////// void NpScene::createInOmniPVD(const PxSceneDesc& desc) { PX_UNUSED(desc); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, static_cast<PxScene &>(*this)) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, gravity, static_cast<PxScene &>(*this), getGravity()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, flags, static_cast<PxScene&>(*this), getFlags()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, frictionType, static_cast<PxScene&>(*this), getFrictionType()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, broadPhaseType, static_cast<PxScene&>(*this), getBroadPhaseType()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, kineKineFilteringMode, static_cast<PxScene&>(*this), getKinematicKinematicFilteringMode()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, staticKineFilteringMode, static_cast<PxScene&>(*this), getStaticKinematicFilteringMode()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, solverType, static_cast<PxScene&>(*this), getSolverType()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, bounceThresholdVelocity, static_cast<PxScene&>(*this), getBounceThresholdVelocity()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, frictionOffsetThreshold, static_cast<PxScene&>(*this), getFrictionOffsetThreshold()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, frictionCorrelationDistance, static_cast<PxScene&>(*this), getFrictionCorrelationDistance()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, solverBatchSize, static_cast<PxScene&>(*this), getSolverBatchSize()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, solverArticulationBatchSize, static_cast<PxScene&>(*this), getSolverArticulationBatchSize()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, nbContactDataBlocks, static_cast<PxScene&>(*this), getNbContactDataBlocksUsed()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, maxNbContactDataBlocks, static_cast<PxScene&>(*this), getMaxNbContactDataBlocksUsed())//naming problem of functions OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, maxBiasCoefficient, static_cast<PxScene&>(*this), getMaxBiasCoefficient()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, contactReportStreamBufferSize, static_cast<PxScene&>(*this), getContactReportStreamBufferSize()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, ccdMaxPasses, static_cast<PxScene&>(*this), getCCDMaxPasses()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, ccdThreshold, static_cast<PxScene&>(*this), getCCDThreshold()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, ccdMaxSeparation, static_cast<PxScene&>(*this), getCCDMaxSeparation()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, wakeCounterResetValue, static_cast<PxScene&>(*this), getWakeCounterResetValue()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbActors, static_cast<PxScene&>(*this), desc.limits.maxNbActors) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbBodies, static_cast<PxScene&>(*this), desc.limits.maxNbBodies) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbStaticShapes, static_cast<PxScene&>(*this), desc.limits.maxNbStaticShapes) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbDynamicShapes, static_cast<PxScene&>(*this), desc.limits.maxNbDynamicShapes) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbAggregates, static_cast<PxScene&>(*this), desc.limits.maxNbAggregates) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbConstraints, static_cast<PxScene&>(*this), desc.limits.maxNbConstraints) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbRegions, static_cast<PxScene&>(*this), desc.limits.maxNbRegions) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, limitsMaxNbBroadPhaseOverlaps, static_cast<PxScene&>(*this), desc.limits.maxNbBroadPhaseOverlaps) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasCPUDispatcher, static_cast<PxScene&>(*this), getCpuDispatcher() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasCUDAContextManager, static_cast<PxScene&>(*this), getCudaContextManager() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasSimulationEventCallback, static_cast<PxScene&>(*this), getSimulationEventCallback() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasContactModifyCallback, static_cast<PxScene&>(*this), getContactModifyCallback() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasCCDContactModifyCallback, static_cast<PxScene&>(*this), getCCDContactModifyCallback() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasBroadPhaseCallback, static_cast<PxScene&>(*this), getBroadPhaseCallback() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, hasFilterCallback, static_cast<PxScene&>(*this), getFilterCallback() ? true : false) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, sanityBounds, static_cast<PxScene&>(*this), desc.sanityBounds) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, gpuDynamicsConfig, static_cast<PxScene&>(*this), desc.gpuDynamicsConfig) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, gpuMaxNumPartitions, static_cast<PxScene&>(*this), desc.gpuMaxNumPartitions) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, gpuMaxNumStaticPartitions, static_cast<PxScene&>(*this), desc.gpuMaxNumStaticPartitions) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, gpuComputeVersion, static_cast<PxScene&>(*this), desc.gpuComputeVersion) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, contactPairSlabSize, static_cast<PxScene&>(*this), desc.contactPairSlabSize) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, tolerancesScale, static_cast<PxScene&>(*this), desc.getTolerancesScale()) OMNI_PVD_WRITE_SCOPE_END }
168,633
C++
33.464337
249
0.735787
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSerializerAdapter.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/PxBase.h" #include "common/PxSerialFramework.h" #include "common/PxSerializer.h" #include "PxPhysicsSerialization.h" #include "GuHeightField.h" #include "GuConvexMesh.h" #include "GuTriangleMesh.h" #include "GuTriangleMeshBV4.h" #include "GuTriangleMeshRTree.h" #include "GuHeightFieldData.h" #include "NpPruningStructure.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationLink.h" #include "NpArticulationSensor.h" #include "NpMaterial.h" #include "NpAggregate.h" namespace physx { using namespace physx::Gu; template<> void PxSerializerDefaultAdapter<NpMaterial>::registerReferences(PxBase& obj, PxSerializationContext& context) const { NpMaterial& t = static_cast<NpMaterial&>(obj); context.registerReference(obj, PX_SERIAL_REF_KIND_PXBASE, size_t(&obj)); context.registerReference(obj, PX_SERIAL_REF_KIND_MATERIAL_IDX, size_t(t.mMaterial.mMaterialIndex)); } template<> void PxSerializerDefaultAdapter<NpRigidDynamic>::registerReferences(PxBase& obj, PxSerializationContext& context) const { NpRigidDynamic& dynamic = static_cast<NpRigidDynamic&>(obj); context.registerReference(obj, PX_SERIAL_REF_KIND_PXBASE, size_t(&obj)); struct RequiresCallback : public PxProcessPxBaseCallback { RequiresCallback(physx::PxSerializationContext& c) : context(c) {} RequiresCallback& operator=(const RequiresCallback&) { PX_ASSERT(0); return *this; } //PX_NOCOPY doesn't work for local classes void process(PxBase& base) { context.registerReference(base, PX_SERIAL_REF_KIND_PXBASE, size_t(&base)); } PxSerializationContext& context; }; RequiresCallback callback(context); dynamic.requiresObjects(callback); } template<> bool PxSerializerDefaultAdapter<NpArticulationLink>::isSubordinate() const { return true; } template<> void PxSerializerDefaultAdapter<NpShape>::registerReferences(PxBase& obj, PxSerializationContext& context) const { NpShape& shape = static_cast<NpShape&>(obj); context.registerReference(obj, PX_SERIAL_REF_KIND_PXBASE, size_t(&obj)); struct RequiresCallback : public PxProcessPxBaseCallback { RequiresCallback(physx::PxSerializationContext& c) : context(c) {} RequiresCallback &operator=(const RequiresCallback&) { PX_ASSERT(0); return *this; } //PX_NOCOPY doesn't work for local classes void process(PxBase& base) { PxMaterial* pxMaterial = base.is<PxMaterial>(); if (!pxMaterial) { context.registerReference(base, PX_SERIAL_REF_KIND_PXBASE, size_t(&base)); } else { //ideally we would move this part to ScShapeCore but we don't yet have a MaterialManager available there. const PxU16 index = static_cast<NpMaterial*>(pxMaterial)->mMaterial.mMaterialIndex; context.registerReference(base, PX_SERIAL_REF_KIND_MATERIAL_IDX, size_t(index)); } } PxSerializationContext& context; }; RequiresCallback callback(context); shape.requiresObjects(callback); } template<> bool PxSerializerDefaultAdapter<NpConstraint>::isSubordinate() const { return true; } template<> bool PxSerializerDefaultAdapter<NpArticulationJointReducedCoordinate>::isSubordinate() const { return true; } } using namespace physx; void PxRegisterPhysicsSerializers(PxSerializationRegistry& sr) { sr.registerSerializer(PxConcreteType::eCONVEX_MESH, PX_NEW_SERIALIZER_ADAPTER(ConvexMesh)); sr.registerSerializer(PxConcreteType::eTRIANGLE_MESH_BVH33, PX_NEW_SERIALIZER_ADAPTER(RTreeTriangleMesh)); sr.registerSerializer(PxConcreteType::eTRIANGLE_MESH_BVH34, PX_NEW_SERIALIZER_ADAPTER(BV4TriangleMesh)); sr.registerSerializer(PxConcreteType::eHEIGHTFIELD, PX_NEW_SERIALIZER_ADAPTER(HeightField)); sr.registerSerializer(PxConcreteType::eRIGID_DYNAMIC, PX_NEW_SERIALIZER_ADAPTER(NpRigidDynamic)); sr.registerSerializer(PxConcreteType::eRIGID_STATIC, PX_NEW_SERIALIZER_ADAPTER(NpRigidStatic)); sr.registerSerializer(PxConcreteType::eSHAPE, PX_NEW_SERIALIZER_ADAPTER(NpShape)); sr.registerSerializer(PxConcreteType::eMATERIAL, PX_NEW_SERIALIZER_ADAPTER(NpMaterial)); sr.registerSerializer(PxConcreteType::eCONSTRAINT, PX_NEW_SERIALIZER_ADAPTER(NpConstraint)); sr.registerSerializer(PxConcreteType::eAGGREGATE, PX_NEW_SERIALIZER_ADAPTER(NpAggregate)); sr.registerSerializer(PxConcreteType::eARTICULATION_REDUCED_COORDINATE, PX_NEW_SERIALIZER_ADAPTER(NpArticulationReducedCoordinate)); sr.registerSerializer(PxConcreteType::eARTICULATION_LINK, PX_NEW_SERIALIZER_ADAPTER(NpArticulationLink)); sr.registerSerializer(PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE, PX_NEW_SERIALIZER_ADAPTER(NpArticulationJointReducedCoordinate)); sr.registerSerializer(PxConcreteType::eARTICULATION_SENSOR, PX_NEW_SERIALIZER_ADAPTER(NpArticulationSensor)); sr.registerSerializer(PxConcreteType::eARTICULATION_SPATIAL_TENDON, PX_NEW_SERIALIZER_ADAPTER(NpArticulationSpatialTendon)); sr.registerSerializer(PxConcreteType::eARTICULATION_ATTACHMENT, PX_NEW_SERIALIZER_ADAPTER(NpArticulationAttachment)); sr.registerSerializer(PxConcreteType::eARTICULATION_FIXED_TENDON, PX_NEW_SERIALIZER_ADAPTER(NpArticulationFixedTendon)); sr.registerSerializer(PxConcreteType::eARTICULATION_TENDON_JOINT, PX_NEW_SERIALIZER_ADAPTER(NpArticulationTendonJoint)); sr.registerSerializer(PxConcreteType::ePRUNING_STRUCTURE, PX_NEW_SERIALIZER_ADAPTER(Sq::PruningStructure)); } void PxUnregisterPhysicsSerializers(PxSerializationRegistry& sr) { PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eCONVEX_MESH)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eTRIANGLE_MESH_BVH33)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eTRIANGLE_MESH_BVH34)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eHEIGHTFIELD)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eRIGID_DYNAMIC)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eRIGID_STATIC)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eSHAPE)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eMATERIAL)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eCONSTRAINT)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eAGGREGATE)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_REDUCED_COORDINATE)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_LINK)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_SENSOR)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_SPATIAL_TENDON)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_ATTACHMENT)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_FIXED_TENDON)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::eARTICULATION_TENDON_JOINT)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxConcreteType::ePRUNING_STRUCTURE)); }
9,015
C++
48.267759
144
0.78924
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationLink.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 "NpArticulationReducedCoordinate.h" #include "NpRigidActorTemplateInternal.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; using namespace Cm; // PX_SERIALIZATION void NpArticulationLink::requiresObjects(PxProcessPxBaseCallback& c) { NpArticulationLinkT::requiresObjects(c); if(mInboundJoint) c.process(*mInboundJoint); } void NpArticulationLink::exportExtraData(PxSerializationContext& stream) { NpArticulationLinkT::exportExtraData(stream); exportInlineArray(mChildLinks, stream); } void NpArticulationLink::importExtraData(PxDeserializationContext& context) { NpArticulationLinkT::importExtraData(context); importInlineArray(mChildLinks, context); } void NpArticulationLink::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mRoot); context.translatePxBase(mInboundJoint); context.translatePxBase(mParent); NpArticulationLinkT::resolveReferences(context); const PxU32 nbLinks = mChildLinks.size(); for(PxU32 i=0;i<nbLinks;i++) context.translatePxBase(mChildLinks[i]); } NpArticulationLink* NpArticulationLink::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationLink* obj = PX_PLACEMENT_NEW(address, NpArticulationLink(PxBaseFlags(0))); address += sizeof(NpArticulationLink); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationLink::NpArticulationLink(const PxTransform& bodyPose, PxArticulationReducedCoordinate& root, NpArticulationLink* parent) : NpArticulationLinkT (PxConcreteType::eARTICULATION_LINK, PxBaseFlag::eOWNS_MEMORY, PxActorType::eARTICULATION_LINK, NpType::eBODY_FROM_ARTICULATION_LINK, bodyPose), mRoot (&root), mInboundJoint (NULL), mParent (parent), mLLIndex (0xffffffff), mInboundJointDof (0xffffffff) { if (parent) parent->addToChildList(*this); } NpArticulationLink::~NpArticulationLink() { } void NpArticulationLink::releaseInternal() { NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, userData); NpArticulationReducedCoordinate* npArticulation = static_cast<NpArticulationReducedCoordinate*>(mRoot); npArticulation->removeLinkFromList(*this); if (mParent) mParent->removeFromChildList(*this); if (mInboundJoint) mInboundJoint->release(); //Remove constraints, aggregates, scene, shapes. removeRigidActorT<PxArticulationLink>(*this); PX_ASSERT(!isAPIWriteForbidden()); NpDestroyArticulationLink(this); } void NpArticulationLink::release() { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::release() not allowed while the articulation link is in a scene. Call will be ignored."); return; } //! this function doesn't get called when the articulation root is released // therefore, put deregistration code etc. into dtor, not here if (mChildLinks.empty()) { releaseInternal(); } else { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::release(): Only leaf articulation links can be released. Call will be ignored."); } } PxTransform NpArticulationLink::getGlobalPose() const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationLink::getGlobalPose() not allowed while simulation is running (except during PxScene::collide()).", PxTransform(PxIdentity)); // PT:: tag: scalar transform*transform return mCore.getBody2World() * mCore.getBody2Actor().getInverse(); } bool NpArticulationLink::attachShape(PxShape& shape) { static_cast<NpArticulationReducedCoordinate*>(mRoot)->incrementShapeCount(); return NpRigidActorTemplate::attachShape(shape); } void NpArticulationLink::detachShape(PxShape& shape, bool wakeOnLostTouch) { static_cast<NpArticulationReducedCoordinate*>(mRoot)->decrementShapeCount(); NpRigidActorTemplate::detachShape(shape, wakeOnLostTouch); } PxArticulationReducedCoordinate& NpArticulationLink::getArticulation() const { NP_READ_CHECK(getNpScene()); return *mRoot; } PxArticulationJointReducedCoordinate* NpArticulationLink::getInboundJoint() const { NP_READ_CHECK(getNpScene()); return mInboundJoint; } PxU32 NpArticulationLink::getInboundJointDof() const { NP_READ_CHECK(getNpScene()); return getNpScene() ? mInboundJointDof : 0xffffffffu; } PxU32 NpArticulationLink::getNbChildren() const { NP_READ_CHECK(getNpScene()); return mChildLinks.size(); } PxU32 NpArticulationLink::getChildren(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return getArrayOfPointers(userBuffer, bufferSize, startIndex, mChildLinks.begin(), mChildLinks.size()); } PxU32 NpArticulationLink::getLinkIndex() const { NP_READ_CHECK(getNpScene()); return getNpScene() ? mLLIndex : 0xffffffffu; } void NpArticulationLink::setCMassLocalPose(const PxTransform& pose) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxArticulationLink::setCMassLocalPose: invalid parameter"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationLink::setCMassLocalPose() not allowed while simulation is running. Call will be ignored.") const PxTransform p = pose.getNormalized(); const PxTransform oldpose = mCore.getBody2Actor(); const PxTransform comShift = p.transformInv(oldpose); NpArticulationLinkT::setCMassLocalPoseInternal(p); if(mInboundJoint) { NpArticulationJointReducedCoordinate* j =static_cast<NpArticulationJointReducedCoordinate*>(mInboundJoint); // PT:: tag: scalar transform*transform j->scSetChildPose(comShift.transform(j->getCore().getChildPose())); } for(PxU32 i=0; i<mChildLinks.size(); i++) { NpArticulationJointReducedCoordinate* j = static_cast<NpArticulationJointReducedCoordinate*>(mChildLinks[i]->getInboundJoint()); // PT:: tag: scalar transform*transform j->scSetParentPose(comShift.transform(j->getCore().getParentPose())); } } void NpArticulationLink::addForce(const PxVec3& force, PxForceMode::Enum mode, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(force.isFinite(), "PxArticulationLink::addForce: force is not valid."); PX_CHECK_AND_RETURN(npScene, "PxArticulationLink::addForce: Articulation link must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxArticulationLink::addForce() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::addForce(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } addSpatialForce(&force, NULL, mode); static_cast<NpArticulationReducedCoordinate*>(mRoot)->wakeUpInternal((!force.isZero()), autowake); } void NpArticulationLink::addTorque(const PxVec3& torque, PxForceMode::Enum mode, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(torque.isFinite(), "PxArticulationLink::addTorque: force is not valid."); PX_CHECK_AND_RETURN(npScene, "PxArticulationLink::addTorque: Articulation link must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxArticulationLink::addTorque() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::addTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } addSpatialForce(NULL, &torque, mode); static_cast<NpArticulationReducedCoordinate*>(mRoot)->wakeUpInternal((!torque.isZero()), autowake); } void NpArticulationLink::setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(torque.isFinite(), "PxArticulationLink::setForceAndTorque: torque is not valid."); PX_CHECK_AND_RETURN(force.isFinite(), "PxArticulationLink::setForceAndTorque: force is not valid."); PX_CHECK_AND_RETURN(npScene, "PxArticulationLink::addTorque: Articulation link must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxArticulationLink::setForceAndTorque() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().Call will be ignored."); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::setForceAndTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } setSpatialForce(&force, &torque, mode); static_cast<NpArticulationReducedCoordinate*>(mRoot)->wakeUpInternal((!torque.isZero()), true); } void NpArticulationLink::clearForce(PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxArticulationLink::clearForce: Articulation link must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxArticulationLink::clearForce() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().Call will be ignored."); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::clearForce(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } clearSpatialForce(mode, true, false); } void NpArticulationLink::clearTorque(PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxArticulationLink::clearTorque: Articulation link must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxArticulationLink::clearTorque() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().Call will be ignored."); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::clearTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } clearSpatialForce(mode, false, true); } void NpArticulationLink::setCfmScale(const PxReal cfmScale) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(cfmScale >= 0.f && cfmScale <= 1.f, "PxArticulationLink::setCfmScale: cfm is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationLink::setCfmScale() not allowed while simulation is running. Call will be ignored.") mCore.getCore().cfmScale = cfmScale; OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationLink, CFMScale, static_cast<PxArticulationLink&>(*this), cfmScale); // @@@ } PxReal NpArticulationLink::getCfmScale() const { NP_READ_CHECK(getNpScene()); return mCore.getCore().cfmScale; } void NpArticulationLink::setGlobalPoseInternal(const PxTransform& pose, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxArticulationLink::setGlobalPose: pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationLink::setGlobalPose() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationLink::setGlobalPose(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } #if PX_CHECKED if (npScene) npScene->checkPositionSanity(*this, pose, "PxArticulationLink::setGlobalPose"); #endif const PxTransform newPose = pose.getNormalized(); //AM: added to fix 1461 where users read and write orientations for no reason. // PT:: tag: scalar transform*transform const PxTransform body2World = newPose * mCore.getBody2Actor(); scSetBody2World(body2World); if (npScene && autowake) static_cast<NpArticulationReducedCoordinate*>(mRoot)->wakeUpInternal(false, true); if (npScene) static_cast<NpArticulationReducedCoordinate*>(mRoot)->setGlobalPose(); } void NpArticulationLink::setInboundJointDof(const PxU32 index) { mInboundJointDof = index; OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationLink, inboundJointDOF, static_cast<PxArticulationLink&>(*this), mInboundJointDof); } void NpArticulationLink::setFixedBaseLink(bool value) { NP_WRITE_CHECK(getNpScene()); mCore.setFixedBaseLink(value); } PxU32 physx::NpArticulationGetShapes(NpArticulationLink& actor, NpShape* const*& shapes, bool* isCompound) { NpShapeManager& sm = actor.getShapeManager(); shapes = sm.getShapes(); if (isCompound) *isCompound = sm.isSqCompound(); return sm.getNbShapes(); }
15,233
C++
38.466321
257
0.772139
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpConstraint.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 "PxConstraint.h" #include "NpConstraint.h" #include "NpPhysics.h" #include "NpRigidDynamic.h" #include "NpRigidStatic.h" #include "NpArticulationLink.h" #include "ScConstraintSim.h" #include "ScConstraintInteraction.h" #include "PxsSimulationController.h" using namespace physx; using namespace Sc; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE PxConstraintFlags scGetFlags(const ConstraintCore& core) { // return core.getFlags() & (~(PxConstraintFlag::eBROKEN | PxConstraintFlag::eGPU_COMPATIBLE)); return core.getFlags() & (~(PxConstraintFlag::eGPU_COMPATIBLE)); } static NpScene* getSceneFromActors(const PxRigidActor* actor0, const PxRigidActor* actor1) { NpScene* s0 = NULL; NpScene* s1 = NULL; if(actor0 && (!(actor0->getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)))) s0 = static_cast<NpScene*>(actor0->getScene()); if(actor1 && (!(actor1->getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)))) s1 = static_cast<NpScene*>(actor1->getScene()); #if PX_CHECKED if ((s0 && s1) && (s0 != s1)) outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Adding constraint to scene: Actors belong to different scenes, undefined behavior expected!"); #endif if ((!actor0 || s0) && (!actor1 || s1)) return s0 ? s0 : s1; else return NULL; } // PT: TODO: refactor with version in ScScene.cpp & with NpActor::getFromPxActor static NpActor* getNpActor(PxRigidActor* a) { if(!a) return NULL; const PxType type = a->getConcreteType(); if (type == PxConcreteType::eRIGID_DYNAMIC) return static_cast<NpRigidDynamic*>(a); else if (type == PxConcreteType::eARTICULATION_LINK) return static_cast<NpArticulationLink*>(a); else { PX_ASSERT(type == PxConcreteType::eRIGID_STATIC); return static_cast<NpRigidStatic*>(a); } } void NpConstraint::setConstraintFunctions(PxConstraintConnector& n, const PxConstraintShaderTable& shaders) { mCore.setConstraintFunctions(n, shaders); //update mConnectorArray, since mActor0 or mActor1 should be in external reference bool bNeedUpdate = false; if(mActor0) { NpActor& npActor = NpActor::getFromPxActor(*mActor0); if(npActor.findConnector(NpConnectorType::eConstraint, this) == 0xffffffff) { bNeedUpdate = true; npActor.addConnector(NpConnectorType::eConstraint, this, "PxConstraint: Add to rigid actor 0: Constraint already added"); } } if(mActor1) { NpActor& npActor = NpActor::getFromPxActor(*mActor1); if(npActor.findConnector(NpConnectorType::eConstraint, this) == 0xffffffff) { bNeedUpdate = true; npActor.addConnector(NpConnectorType::eConstraint, this, "PxConstraint: Add to rigid actor 1: Constraint already added"); } } if(bNeedUpdate) { NpScene* newScene = ::getSceneFromActors(mActor0, mActor1); NpScene* oldScene = getNpScene(); if (oldScene != newScene) { if(oldScene) oldScene->removeFromConstraintList(*this); if(newScene) newScene->addToConstraintList(*this); } } } void NpConstraint::addConnectors(PxRigidActor* actor0, PxRigidActor* actor1) { if(actor0) NpActor::getFromPxActor(*actor0).addConnector(NpConnectorType::eConstraint, this, "PxConstraint: Add to rigid actor 0: Constraint already added"); if(actor1) NpActor::getFromPxActor(*actor1).addConnector(NpConnectorType::eConstraint, this, "PxConstraint: Add to rigid actor 1: Constraint already added"); } void NpConstraint::removeConnectors(const char* errorMsg0, const char* errorMsg1) { if(mActor0) NpActor::getFromPxActor(*mActor0).removeConnector(*mActor0, NpConnectorType::eConstraint, this, errorMsg0); if(mActor1) NpActor::getFromPxActor(*mActor1).removeConnector(*mActor1, NpConnectorType::eConstraint, this, errorMsg1); } NpConstraint::NpConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) : PxConstraint(PxConcreteType::eCONSTRAINT, PxBaseFlag::eOWNS_MEMORY), NpBase (NpType::eCONSTRAINT), mActor0 (actor0), mActor1 (actor1), mCore (connector, shaders, dataSize) { scSetFlags(shaders.flag); addConnectors(actor0, actor1); NpScene* s = ::getSceneFromActors(actor0, actor1); if (s) { if(s->isAPIWriteForbidden()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxConstraint creation not allowed while simulation is running. Call will be ignored."); return; } s->addToConstraintList(*this); } } NpConstraint::~NpConstraint() { if(getBaseFlags()&PxBaseFlag::eOWNS_MEMORY) mCore.getPxConnector()->onConstraintRelease(); NpFactory::getInstance().onConstraintRelease(this); } static const char* gRemoveConnectorMsg = "PxConstraint::release(): internal error, mConnectorArray not created."; void NpConstraint::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxConstraint::release() not allowed while simulation is running. Call will be ignored.") NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, NULL); removeConnectors(gRemoveConnectorMsg, gRemoveConnectorMsg); if(npScene) npScene->removeFromConstraintList(*this); NpDestroyConstraint(this); } // PX_SERIALIZATION void NpConstraint::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mActor0); context.translatePxBase(mActor1); } NpConstraint* NpConstraint::createObject(PxU8*& address, PxDeserializationContext& context) { NpConstraint* obj = PX_PLACEMENT_NEW(address, NpConstraint(PxBaseFlags(0))); address += sizeof(NpConstraint); obj->importExtraData(context); obj->resolveReferences(context); return obj; } // ~PX_SERIALIZATION PxScene* NpConstraint::getScene() const { return getNpScene(); } void NpConstraint::getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const { NP_READ_CHECK(getNpScene()); actor0 = mActor0; actor1 = mActor1; } static PX_INLINE void scSetBodies(ConstraintCore& core, NpActor* r0, NpActor* r1) { Sc::RigidCore* scR0 = r0 ? &r0->getScRigidCore() : NULL; Sc::RigidCore* scR1 = r1 ? &r1->getScRigidCore() : NULL; core.setBodies(scR0, scR1); } void NpConstraint::setActors(PxRigidActor* actor0, PxRigidActor* actor1) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN((actor0 && actor0->getConcreteType()!=PxConcreteType::eRIGID_STATIC) || (actor1 && actor1->getConcreteType()!=PxConcreteType::eRIGID_STATIC), "PxConstraint: at least one actor must be non-static"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxConstraint::setActors() not allowed while simulation is running. Call will be ignored.") if(mActor0 == actor0 && mActor1 == actor1) return; removeConnectors( "PxConstraint: Add to rigid actor 0: Constraint already added", "PxConstraint: Add to rigid actor 1: Constraint already added"); addConnectors(actor0, actor1); mActor0 = actor0; mActor1 = actor1; NpScene* newScene = ::getSceneFromActors(actor0, actor1); NpScene* oldScene = getNpScene(); // PT: bypassing the calls to removeFromConstraintList / addToConstraintList creates issues like PX-2363, where // various internal structures are not properly updated. Always going through the slower codepath fixes them. // if(oldScene != newScene) { if(oldScene) oldScene->removeFromConstraintList(*this); scSetBodies(mCore, getNpActor(actor0), getNpActor(actor1)); if(newScene) newScene->addToConstraintList(*this); } // else // scSetBodies(mCore, getNpActor(actor0), getNpActor(actor1)); UPDATE_PVD_PROPERTY } PxConstraintFlags NpConstraint::getFlags() const { NP_READ_CHECK(getNpScene()); return scGetFlags(mCore); } void NpConstraint::setFlags(PxConstraintFlags flags) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(!(flags & PxConstraintFlag::eBROKEN), "PxConstraintFlag::eBROKEN is a read only flag"); PX_CHECK_AND_RETURN(!(flags & PxConstraintFlag::eGPU_COMPATIBLE), "PxConstraintFlag::eGPU_COMPATIBLE is an internal flag and is illegal to set via the API"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxConstraint::setFlags() not allowed while simulation is running. Call will be ignored.") scSetFlags(flags); } void NpConstraint::setFlag(PxConstraintFlag::Enum flag, bool value) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(flag != PxConstraintFlag::eBROKEN, "PxConstraintFlag::eBROKEN is a read only flag"); PX_CHECK_AND_RETURN(flag != PxConstraintFlag::eGPU_COMPATIBLE, "PxConstraintFlag::eGPU_COMPATIBLE is an internal flag and is illegal to set via the API"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxConstraint::setFlag() not allowed while simulation is running. Call will be ignored.") const PxConstraintFlags f = scGetFlags(mCore); scSetFlags(value ? f|flag : f&~flag); } void NpConstraint::getForce(PxVec3& linear, PxVec3& angular) const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE(getNpScene(), "PxConstraint::getForce() not allowed while simulation is running (except during PxScene::collide())."); mCore.getForce(linear, angular); } void NpConstraint::markDirty() { #ifdef NEW_DIRTY_SHADERS_CODE if(mCore.getFlags() & PxConstraintFlag::eALWAYS_UPDATE) return; if(!mCore.isDirty()) { NpScene* npScene = getNpScene(); if(npScene) npScene->addDirtyConstraint(this); mCore.setDirty(); } #else mCore.setDirty(); #endif } void NpConstraint::updateConstants(PxsSimulationController& simController) { if(!mCore.isDirty() && !(mCore.getFlags() & PxConstraintFlag::eALWAYS_UPDATE)) return; PX_ASSERT(!isAPIWriteForbidden()); Sc::ConstraintSim* sim = mCore.getSim(); if(sim) { Dy::Constraint& LLC = sim->getLowLevelConstraint(); PxMemCopy(LLC.constantBlock, mCore.getPxConnector()->prepareData(), LLC.constantBlockSize); simController.updateJoint(sim->getInteraction()->getEdgeIndex(), &LLC); } mCore.clearDirty(); #if PX_SUPPORT_PVD NpScene* npScene = getNpScene(); //Changed to use the visual scenes update system which respects //the debugger's connection type flag. if(npScene) npScene->getScenePvdClientInternal().updatePvdProperties(this); #endif } void NpConstraint::setBreakForce(PxReal linear, PxReal angular) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxConstraint::setBreakForce() not allowed while simulation is running. Call will be ignored.") mCore.setBreakForce(linear, angular); markDirty(); UPDATE_PVD_PROPERTY } void NpConstraint::getBreakForce(PxReal& linear, PxReal& angular) const { NP_READ_CHECK(getNpScene()); mCore.getBreakForce(linear, angular); } void NpConstraint::setMinResponseThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold) && threshold>=0, "PxConstraint::setMinResponseThreshold: threshold must be non-negative"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxConstraint::setMinResponseThreshold() not allowed while simulation is running. Call will be ignored.") mCore.setMinResponseThreshold(threshold); UPDATE_PVD_PROPERTY } PxReal NpConstraint::getMinResponseThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getMinResponseThreshold(); } bool NpConstraint::isValid() const { NP_READ_CHECK(getNpScene()); const bool isValid0 = mActor0 && mActor0->getConcreteType()!=PxConcreteType::eRIGID_STATIC; const bool isValid1 = mActor1 && mActor1->getConcreteType()!=PxConcreteType::eRIGID_STATIC; return isValid0 || isValid1; } void* NpConstraint::getExternalReference(PxU32& typeID) { NP_READ_CHECK(getNpScene()); return mCore.getPxConnector()->getExternalReference(typeID); } void NpConstraint::comShift(PxRigidActor* actor) { PX_ASSERT(actor == mActor0 || actor == mActor1); PxConstraintConnector* connector = mCore.getPxConnector(); if(actor == mActor0) connector->onComShift(0); if(actor == mActor1) connector->onComShift(1); } void NpConstraint::actorDeleted(PxRigidActor* actor) { // the actor cannot be deleted without also removing it from the scene, // which means that the joint will also have been removed from the scene, // so we can just reset the actor here. PX_ASSERT(actor == mActor0 || actor == mActor1); if(actor == mActor0) mActor0 = NULL; else mActor1 = NULL; } NpScene* NpConstraint::getSceneFromActors() const { return ::getSceneFromActors(mActor0, mActor1); }
14,240
C++
31.292517
218
0.744031
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpShape.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_SHAPE_H #define NP_SHAPE_H #include "common/PxMetaData.h" #include "PxShape.h" #include "NpBase.h" #include "ScShapeCore.h" #include "NpPhysics.h" #include "CmPtrTable.h" namespace physx { class NpScene; class NpShape : public PxShape, public NpBase { public: // PX_SERIALIZATION NpShape(PxBaseFlags baseFlags); void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); void resolveReferences(PxDeserializationContext& context); static NpShape* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, const PxU16* materialIndices, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum flag = PxShapeCoreFlag::Enum(0)); virtual ~NpShape(); // PxRefCounted virtual PxU32 getReferenceCount() const PX_OVERRIDE; virtual void acquireReference() PX_OVERRIDE; //~PxRefCounted // PxShape virtual void release() PX_OVERRIDE; //!< call to release from actor virtual void setGeometry(const PxGeometry&) PX_OVERRIDE; virtual const PxGeometry& getGeometry() const PX_OVERRIDE; virtual PxRigidActor* getActor() const PX_OVERRIDE; virtual void setLocalPose(const PxTransform& pose) PX_OVERRIDE; virtual PxTransform getLocalPose() const PX_OVERRIDE; virtual void setSimulationFilterData(const PxFilterData& data) PX_OVERRIDE; virtual PxFilterData getSimulationFilterData() const PX_OVERRIDE; virtual void setQueryFilterData(const PxFilterData& data) PX_OVERRIDE; virtual PxFilterData getQueryFilterData() const PX_OVERRIDE; virtual void setMaterials(PxMaterial*const* materials, PxU16 materialCount) PX_OVERRIDE; virtual void setSoftBodyMaterials(PxFEMSoftBodyMaterial*const* materials, PxU16 materialCount) PX_OVERRIDE; virtual void setClothMaterials(PxFEMClothMaterial*const* materials, PxU16 materialCount) PX_OVERRIDE; virtual PxU16 getNbMaterials() const PX_OVERRIDE; virtual PxU32 getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxU32 getSoftBodyMaterials(PxFEMSoftBodyMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxU32 getClothMaterials(PxFEMClothMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxBaseMaterial* getMaterialFromInternalFaceIndex(PxU32 faceIndex) const PX_OVERRIDE; virtual void setContactOffset(PxReal) PX_OVERRIDE; virtual PxReal getContactOffset() const PX_OVERRIDE; virtual void setRestOffset(PxReal) PX_OVERRIDE; virtual PxReal getRestOffset() const PX_OVERRIDE; virtual void setDensityForFluid(PxReal) PX_OVERRIDE; virtual PxReal getDensityForFluid() const PX_OVERRIDE; virtual void setTorsionalPatchRadius(PxReal) PX_OVERRIDE; virtual PxReal getTorsionalPatchRadius() const PX_OVERRIDE; virtual void setMinTorsionalPatchRadius(PxReal) PX_OVERRIDE; virtual PxReal getMinTorsionalPatchRadius() const PX_OVERRIDE; virtual PxU32 getInternalShapeIndex() const PX_OVERRIDE; virtual void setFlag(PxShapeFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setFlags(PxShapeFlags inFlags) PX_OVERRIDE; virtual PxShapeFlags getFlags() const PX_OVERRIDE; virtual bool isExclusive() const PX_OVERRIDE; virtual void setName(const char* debugName) PX_OVERRIDE; virtual const char* getName() const PX_OVERRIDE; //~PxShape // Ref counting for shapes works like this: // * for exclusive shapes the actor has a counted reference // * for shared shapes, each actor has a counted reference, and the user has a counted reference // * for either kind, each instance of the shape in a scene (i.e. each shapeSim) causes the reference count to be incremented by 1. // Because these semantics aren't clear to users, this reference count should not be exposed in the API // PxBase virtual void onRefCountZero() PX_OVERRIDE; //~PxBase PX_FORCE_INLINE PxShapeFlags getFlagsFast() const { return mCore.getFlags(); } PX_FORCE_INLINE const PxTransform& getLocalPoseFast() const { return mCore.getShape2Actor(); } PX_FORCE_INLINE PxGeometryType::Enum getGeometryTypeFast() const { return mCore.getGeometryType(); } PX_FORCE_INLINE const PxFilterData& getQueryFilterDataFast() const { return mQueryFilterData; } PX_FORCE_INLINE PxU32 getActorCount() const { return mFreeSlot; } PX_FORCE_INLINE bool isExclusiveFast() const { return mCore.getCore().mShapeCoreFlags.isSet(PxShapeCoreFlag::eIS_EXCLUSIVE); } PX_FORCE_INLINE const Sc::ShapeCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::ShapeCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpShape, mCore); } // PT: TODO: this one only used internally and by NpFactory template <typename PxMaterialType, typename NpMaterialType> PX_INLINE PxMaterialType* getMaterial(PxU32 index) const { return scGetMaterial<NpMaterialType>(index); } PX_FORCE_INLINE void setSceneIfExclusive(NpScene* s) { if(isExclusiveFast()) setNpScene(s); } void releaseInternal(); // PT: it's "internal" but called by the NpFactory #if PX_CHECKED template <typename PxMaterialType> static bool checkMaterialSetup(const PxGeometry& geom, const char* errorMsgPrefix, PxMaterialType*const* materials, PxU16 materialCount); #endif void onActorAttach(PxActor& actor); void onActorDetach(); void incActorCount(); void decActorCount(); //Always returns 0xffffffff for shared shapes. PX_FORCE_INLINE PxU32 getShapeManagerArrayIndex(const Cm::PtrTable& shapes) const { if(isExclusiveFast()) { PX_ASSERT(isExclusiveFast() || NP_UNUSED_BASE_INDEX == getBaseIndex()); PX_ASSERT(!isExclusiveFast() || NP_UNUSED_BASE_INDEX != getBaseIndex()); const PxU32 index = getBaseIndex(); return index!=NP_UNUSED_BASE_INDEX ? index : 0xffffffff; } else return shapes.find(this); } PX_FORCE_INLINE bool checkShapeManagerArrayIndex(const Cm::PtrTable& shapes) const { return ((!isExclusiveFast() && NP_UNUSED_BASE_INDEX==getBaseIndex()) || ((getBaseIndex() < shapes.getCount()) && (shapes.getPtrs()[getBaseIndex()] == this))); } PX_FORCE_INLINE void setShapeManagerArrayIndex(const PxU32 id) { setBaseIndex(isExclusiveFast() ? id : NP_UNUSED_BASE_INDEX); } PX_FORCE_INLINE void clearShapeManagerArrayIndex() { setBaseIndex(NP_UNUSED_BASE_INDEX); } private: PxActor* mExclusiveShapeActor; Sc::ShapeCore mCore; PxFilterData mQueryFilterData; // Query filter data PT: TODO: consider moving this to SQ structures private: void notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlags notifyFlags); void notifyActorAndUpdatePVD(const PxShapeFlags oldShapeFlags); // PT: for shape flags change void incMeshRefCount(); void decMeshRefCount(); PxRefCounted* getMeshRefCountable(); bool isWritable(); void updateSQ(const char* errorMessage); template <typename PxMaterialType, typename NpMaterialType> bool setMaterialsHelper(PxMaterialType* const* materials, PxU16 materialCount); void setFlagsInternal(PxShapeFlags inFlags); Sc::RigidCore& getScRigidObjectExclusive() const; PX_FORCE_INLINE Sc::RigidCore* getScRigidObjectSLOW() { return NpShape::getActor() ? &getScRigidObjectExclusive() : NULL; } PX_INLINE PxU16 scGetNbMaterials() const { return mCore.getNbMaterialIndices(); } template <typename Material> PX_INLINE Material* scGetMaterial(PxU32 index) const { PX_ASSERT(index < scGetNbMaterials()); NpMaterialManager<Material>& matManager = NpMaterialAccessor<Material>::getMaterialManager(NpPhysics::getInstance()); // PT: TODO: revisit this indirection const PxU16 matTableIndex = mCore.getMaterialIndices()[index]; return matManager.getMaterial(matTableIndex); } // PT: TODO: this one only used internally template <typename PxMaterialType, typename NpMaterialType> PX_INLINE PxU32 scGetMaterials(PxMaterialType** buffer, PxU32 bufferSize, PxU32 startIndex=0) const { const PxU16* materialIndices; PxU32 matCount; NpMaterialManager<NpMaterialType>& matManager = NpMaterialAccessor<NpMaterialType>::getMaterialManager(NpPhysics::getInstance()); materialIndices = mCore.getMaterialIndices(); matCount = mCore.getNbMaterialIndices(); // PT: this is copied from Cm::getArrayOfPointers(). We cannot use the Cm function here // because of the extra indirection needed to access the materials. PxU32 size = matCount; const PxU32 remainder = PxU32(PxMax<PxI32>(PxI32(size - startIndex), 0)); const PxU32 writeCount = PxMin(remainder, bufferSize); materialIndices += startIndex; for(PxU32 i=0;i<writeCount;i++) buffer[i] = matManager.getMaterial(materialIndices[i]); return writeCount; } template<typename PxMaterialType, typename NpMaterialType> void setMaterialsInternal(PxMaterialType* const * materials, PxU16 materialCount); }; #if PX_CHECKED template <typename PxMaterialType> bool NpShape::checkMaterialSetup(const PxGeometry& geom, const char* errorMsgPrefix, PxMaterialType*const* materials, PxU16 materialCount) { for(PxU32 i=0; i<materialCount; ++i) { if(!materials[i]) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "material pointer %d is NULL!", i); return false; } } if(materialCount > 1) { const PxGeometryType::Enum type = geom.getType(); // verify we provide all materials required if(type == PxGeometryType::eTRIANGLEMESH) { const PxTriangleMeshGeometry& meshGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const PxTriangleMesh& mesh = *meshGeom.triangleMesh; // do not allow SDF multi-material tri-meshes: if(mesh.getSDF()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: multiple materials defined for an SDF triangle-mesh geometry!", errorMsgPrefix); return false; } const Gu::TriangleMesh& tmesh = static_cast<const Gu::TriangleMesh&>(mesh); if(tmesh.hasPerTriangleMaterials()) { const PxU32 nbTris = tmesh.getNbTrianglesFast(); for(PxU32 i=0; i<nbTris; i++) { const PxMaterialTableIndex meshMaterialIndex = mesh.getTriangleMaterialIndex(i); if(meshMaterialIndex >= materialCount) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: PxTriangleMesh material indices reference more materials than provided!", errorMsgPrefix); break; } } } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: multiple materials defined for a triangle-mesh that does not have per-triangle materials!", errorMsgPrefix); } } else if(type == PxGeometryType::eTETRAHEDRONMESH) { const PxTetrahedronMeshGeometry& meshGeom = static_cast<const PxTetrahedronMeshGeometry&>(geom); const PxTetrahedronMesh& mesh = *meshGeom.tetrahedronMesh; PX_UNUSED(mesh); //Need to fill in material /*if (mesh.getTriangleMaterialIndex(0) != 0xffff) { for (PxU32 i = 0; i < mesh.getNbTriangles(); i++) { const PxMaterialTableIndex meshMaterialIndex = mesh.getTriangleMaterialIndex(i); if (meshMaterialIndex >= materialCount) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: PxTriangleMesh material indices reference more materials than provided!", errorMsgPrefix); break; } } }*/ } else if(type == PxGeometryType::eHEIGHTFIELD) { const PxHeightFieldGeometry& meshGeom = static_cast<const PxHeightFieldGeometry&>(geom); const PxHeightField& mesh = *meshGeom.heightField; if (mesh.getTriangleMaterialIndex(0) != 0xffff) { const PxU32 nbTris = mesh.getNbColumns()*mesh.getNbRows() * 2; for (PxU32 i = 0; i < nbTris; i++) { const PxMaterialTableIndex meshMaterialIndex = mesh.getTriangleMaterialIndex(i); if (meshMaterialIndex != PxHeightFieldMaterial::eHOLE && meshMaterialIndex >= materialCount) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: PxHeightField material indices reference more materials than provided!", errorMsgPrefix); break; } } } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: multiple materials defined for a heightfield that does not have per-triangle materials!", errorMsgPrefix); } } else { // check that simple shapes don't get assigned multiple materials PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: multiple materials defined for single material geometry!", errorMsgPrefix); return false; } } return true; } #endif } #endif
15,708
C
43.126404
145
0.695187
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpDebugViz.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 "NpDebugViz.h" // PT: moving "all" debug viz code to the same file to improve cache locality when debug drawing things, // share more code, and make sure all actors do thing consistently. #include "NpScene.h" #include "NpCheck.h" #include "common/PxProfileZone.h" using namespace physx; #if PX_ENABLE_DEBUG_VISUALIZATION #include "NpShapeManager.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #include "NpHairSystem.h" #endif #include "foundation/PxVecMath.h" #include "geometry/PxMeshQuery.h" #include "GuHeightFieldUtil.h" #include "GuConvexEdgeFlags.h" #include "GuMidphaseInterface.h" #include "GuEdgeList.h" #include "GuBounds.h" #include "BpBroadPhase.h" #include "BpAABBManager.h" using namespace physx::aos; using namespace Gu; using namespace Cm; ///// static const PxU32 gCollisionShapeColor = PxU32(PxDebugColor::eARGB_MAGENTA); static PX_FORCE_INLINE Vec4V multiply3x3V(const Vec4V p, const PxMat34& mat) { Vec4V ResV = V4Scale(V4LoadU(&mat.m.column0.x), V4GetX(p)); ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.m.column1.x), V4GetY(p))); ResV = V4Add(ResV, V4Scale(V4LoadU(&mat.m.column2.x), V4GetZ(p))); return ResV; } // PT: beware, needs padding at the end of dst/src static PX_FORCE_INLINE void transformV(PxVec3* dst, const PxVec3* src, const Vec4V p, const PxMat34& mat) { const Vec4V vertexV = V4LoadU(&src->x); const Vec4V transformedV = V4Add(multiply3x3V(vertexV, mat), p); V4StoreU(transformedV, &dst->x); } static void visualizeSphere(const PxSphereGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose) { out << gCollisionShapeColor; // PT: no need to output this for each segment! out << absPose; renderOutputDebugCircle(out, 100, geometry.radius); PxMat44 rotPose(absPose); PxSwap(rotPose.column1, rotPose.column2); rotPose.column1 = -rotPose.column1; out << rotPose; renderOutputDebugCircle(out, 100, geometry.radius); PxSwap(rotPose.column0, rotPose.column2); rotPose.column0 = -rotPose.column0; out << rotPose; renderOutputDebugCircle(out, 100, geometry.radius); } static void visualizePlane(const PxPlaneGeometry& /*geometry*/, PxRenderOutput& out, const PxTransform& absPose) { PxMat44 rotPose(absPose); PxSwap(rotPose.column1, rotPose.column2); rotPose.column1 = -rotPose.column1; PxSwap(rotPose.column0, rotPose.column2); rotPose.column0 = -rotPose.column0; out << rotPose << gCollisionShapeColor; // PT: no need to output this for each segment! for(PxReal radius = 2.0f; radius < 20.0f ; radius += 2.0f) renderOutputDebugCircle(out, 100, radius*radius); } static void visualizeCapsule(const PxCapsuleGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose) { out << gCollisionShapeColor; out.outputCapsule(geometry.radius, geometry.halfHeight, absPose); } static void visualizeBox(const PxBoxGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose) { out << gCollisionShapeColor; out << absPose; renderOutputDebugBox(out, PxBounds3(-geometry.halfExtents, geometry.halfExtents)); } static void visualizeConvexMesh(const PxConvexMeshGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose) { const ConvexMesh* convexMesh = static_cast<const ConvexMesh*>(geometry.convexMesh); const ConvexHullData& hullData = convexMesh->getHull(); const PxVec3* vertices = hullData.getHullVertices(); const PxU8* indexBuffer = hullData.getVertexData8(); const PxU32 nbPolygons = convexMesh->getNbPolygonsFast(); const PxMat33Padded m33(absPose.q); const PxMat44 m44(m33 * toMat33(geometry.scale), absPose.p); out << m44 << gCollisionShapeColor; // PT: no need to output this for each segment! for(PxU32 i=0; i<nbPolygons; i++) { const PxU32 pnbVertices = hullData.mPolygons[i].mNbVerts; PxVec3 begin = m44.transform(vertices[indexBuffer[0]]); // PT: transform it only once before the loop starts for(PxU32 j=1; j<pnbVertices; j++) { const PxVec3 end = m44.transform(vertices[indexBuffer[j]]); out.outputSegment(begin, end); begin = end; } out.outputSegment(begin, m44.transform(vertices[indexBuffer[0]])); indexBuffer += pnbVertices; } } static void getTriangle(PxU32 i, PxVec3* wp, const PxVec3* vertices, const void* indices, bool has16BitIndices) { PxU32 ref0, ref1, ref2; getVertexRefs(i, ref0, ref1, ref2, indices, has16BitIndices); wp[0] = vertices[ref0]; wp[1] = vertices[ref1]; wp[2] = vertices[ref2]; } // PT: beware with wp, needs padding static void getWorldTriangle(PxU32 i, PxVec3* wp, const PxVec3* vertices, const void* indices, const PxMat34& absPose, bool has16BitIndices) { // PxVec3 localVerts[3]; // getTriangle(i, localVerts, vertices, indices, has16BitIndices); // wp[0] = absPose.transform(localVerts[0]); // wp[1] = absPose.transform(localVerts[1]); // wp[2] = absPose.transform(localVerts[2]); PxU32 ref0, ref1, ref2; getVertexRefs(i, ref0, ref1, ref2, indices, has16BitIndices); const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&absPose.p.x)); transformV(&wp[0], &vertices[ref0], posV, absPose); transformV(&wp[1], &vertices[ref1], posV, absPose); transformV(&wp[2], &vertices[ref2], posV, absPose); } static void visualizeActiveEdges(PxRenderOutput& out, const TriangleMesh& mesh, PxU32 nbTriangles, const PxU32* results, const PxMat34& absPose) { const PxU8* extraTrigData = mesh.getExtraTrigData(); const PxVec3* vertices = mesh.getVerticesFast(); const void* indices = mesh.getTrianglesFast(); out << PxU32(PxDebugColor::eARGB_YELLOW); // PT: no need to output this for each segment! const bool has16Bit = mesh.has16BitIndices(); for(PxU32 i=0; i<nbTriangles; i++) { const PxU32 index = results ? results[i] : i; PxVec3 wp[3+1]; getWorldTriangle(index, wp, vertices, indices, absPose, has16Bit); const PxU32 flags = getConvexEdgeFlags(extraTrigData, index); if(flags & ETD_CONVEX_EDGE_01) out.outputSegment(wp[0], wp[1]); if(flags & ETD_CONVEX_EDGE_12) out.outputSegment(wp[1], wp[2]); if(flags & ETD_CONVEX_EDGE_20) out.outputSegment(wp[0], wp[2]); } } static void visualizeFaceNormals( PxReal fscale, PxRenderOutput& out, PxU32 nbTriangles, const PxVec3* vertices, const void* indices, bool has16Bit, const PxU32* results, const PxMat34& absPose, const PxMat44& midt) { out << midt << PxU32(PxDebugColor::eARGB_DARKRED); // PT: no need to output this for each segment! const float coeff = 1.0f / 3.0f; PxDebugLine* segments = out.reserveSegments(nbTriangles); for(PxU32 i=0; i<nbTriangles; i++) { const PxU32 index = results ? results[i] : i; PxVec3 wp[3+1]; getWorldTriangle(index, wp, vertices, indices, absPose, has16Bit); const PxVec3 center = (wp[0] + wp[1] + wp[2]) * coeff; PxVec3 normal = (wp[0] - wp[1]).cross(wp[0] - wp[2]); PX_ASSERT(!normal.isZero()); normal = normal.getNormalized(); segments->pos0 = center; segments->pos1 = center + normal * fscale; segments->color0 = segments->color1 = PxU32(PxDebugColor::eARGB_DARKRED); segments++; } } static PxU32 MakeSolidColor(PxU32 alpha, PxU32 red, PxU32 green, PxU32 blue) { return (alpha<<24) | (red << 16) | (green << 8) | blue; } static void decodeTriple(PxU32 id, PxU32& x, PxU32& y, PxU32& z) { x = id & 0x000003FF; id = id >> 10; y = id & 0x000003FF; id = id >> 10; z = id & 0x000003FF; } PX_FORCE_INLINE PxU32 idx(PxU32 x, PxU32 y, PxU32 z, PxU32 width, PxU32 height) { return z * (width) * (height) + y * width + x; } PX_FORCE_INLINE PxReal decode(PxU8* data, PxU32 bytesPerSparsePixel, PxReal subgridsMinSdfValue, PxReal subgridsMaxSdfValue) { switch (bytesPerSparsePixel) { case 1: return PxReal(data[0]) * (1.0f / 255.0f) * (subgridsMaxSdfValue - subgridsMinSdfValue) + subgridsMinSdfValue; case 2: { PxU16* ptr = reinterpret_cast<PxU16*>(data); return PxReal(ptr[0]) * (1.0f / 65535.0f) * (subgridsMaxSdfValue - subgridsMinSdfValue) + subgridsMinSdfValue; } case 4: //If 4 bytes per subgrid pixel are available, then normal floats are used. No need to //de-normalize integer values since the floats already contain real distance values PxReal* ptr = reinterpret_cast<PxReal*>(data); return ptr[0]; } return 0; } PX_FORCE_INLINE PxU32 makeColor(PxReal v, PxReal invRange0, PxReal invRange1) { PxVec3 midColor(0.f, 0, 255.f); PxVec3 lowColor(255.f, 0, 0); PxVec3 outColor(0, 255.f, 0.f); PxU32 color; if (v > 0.f) { PxReal scale = PxPow(v * invRange0, 0.25f); PxVec3 blendColor = midColor + (outColor - midColor) * scale; color = MakeSolidColor( 0xff000000, PxU32(blendColor.x), PxU32(blendColor.y), PxU32(blendColor.z) ); } else { PxReal scale = PxPow(v * invRange1, 0.25f); PxVec3 blendColor = midColor + (lowColor - midColor) * scale; color = MakeSolidColor( 0xff000000, PxU32(blendColor.x), PxU32(blendColor.y), PxU32(blendColor.z) ); } return color; } //Returns true if the number of samples chosen to visualize was reduced (to speed up rendering) compared to the total number of sdf samples available static bool visualizeSDF(PxRenderOutput& out, const Gu::SDF& sdf, const PxMat34& absPose, bool limitNumberOfVisualizedSamples = false) { bool dataReductionActive = false; PxU32 upperByteLimit = 512u * 512u * 512u * sizeof(PxDebugPoint); //2GB - sizeof(PxDebugPoint)=16bytes bool repeat = true; PxReal low = 0.0f, high = 0.0f; PxU32 count = 0; PxU32 upperLimit = limitNumberOfVisualizedSamples ? 128 : 4096; PxReal sdfSpacing = 0.0f; PxU32 strideX = 0; PxU32 strideY = 0; PxU32 strideZ = 0; PxU32 nbX = 0, nbY = 0, nbZ = 0; PxU32 subgridSize = 0; PxU32 subgridStride = 1; while (repeat) { repeat = false; PxU32 nbTargetSamplesPerAxis = upperLimit; subgridStride = 1; if (sdf.mSubgridSize == 0) { subgridSize = 1; sdfSpacing = sdf.mSpacing; nbX = sdf.mDims.x; nbY = sdf.mDims.y; nbZ = sdf.mDims.z; } else { subgridSize = sdf.mSubgridSize; sdfSpacing = subgridSize * sdf.mSpacing; nbX = sdf.mDims.x / subgridSize + 1; nbY = sdf.mDims.y / subgridSize + 1; nbZ = sdf.mDims.z / subgridSize + 1; //Limit the max number of visualized sparse grid samples if (limitNumberOfVisualizedSamples && subgridSize > 4) { subgridStride = (subgridSize + 3) / 4; dataReductionActive = true; } } //KS - a bit arbitrary, but let's limit how many points we churn out strideX = (nbX + nbTargetSamplesPerAxis - 1) / nbTargetSamplesPerAxis; strideY = (nbY + nbTargetSamplesPerAxis - 1) / nbTargetSamplesPerAxis; strideZ = (nbZ + nbTargetSamplesPerAxis - 1) / nbTargetSamplesPerAxis; if (strideX != 1 || strideY != 1 || strideZ != 1) dataReductionActive = true; low = PX_MAX_F32; high = -PX_MAX_F32; count = 0; for (PxU32 k = 0; k < nbZ; k += strideZ) { for (PxU32 j = 0; j < nbY; j += strideY) { for (PxU32 i = 0; i < nbX; i += strideX) { PxReal v = sdf.mSdf[k*nbX*nbY + j * nbX + i]; count++; low = PxMin(low, v); high = PxMax(high, v); if (sdf.mSubgridSize > 0 && k < nbZ - 1 && j < nbY - 1 && i < nbX - 1) { PxU32 startId = sdf.mSubgridStartSlots[k*(nbX - 1)*(nbY - 1) + j * (nbX - 1) + i]; if (startId != 0xFFFFFFFFu) { PxU32 xBase, yBase, zBase; decodeTriple(startId, xBase, yBase, zBase); PX_ASSERT(xBase < sdf.mSdfSubgrids3DTexBlockDim.x); PX_ASSERT(yBase < sdf.mSdfSubgrids3DTexBlockDim.y); PX_ASSERT(zBase < sdf.mSdfSubgrids3DTexBlockDim.z); PxU32 localCount = subgridSize / subgridStride + 1; count += localCount * localCount * localCount; } } if (count * sizeof(PxDebugPoint) > upperByteLimit) break; } if (count * sizeof(PxDebugPoint) > upperByteLimit) break; } if (count * sizeof(PxDebugPoint) > upperByteLimit) break; } if (count * sizeof(PxDebugPoint) > upperByteLimit) { upperLimit /= 2; repeat = true; if (upperLimit == 1) return true; } } const PxReal range0 = high; const PxReal range1 = low; const PxReal invRange0 = 1.f / range0; const PxReal invRange1 = 1.f / range1; PxDebugPoint* points = out.reservePoints(count); PxVec3 localPos = sdf.mMeshLower; PxReal spacingX = sdfSpacing * strideX; PxReal spacingY = sdfSpacing * strideY; PxReal spacingZ = sdfSpacing * strideZ; for (PxU32 k = 0; k < nbZ; k += strideZ, localPos.z += spacingZ) { localPos.y = sdf.mMeshLower.y; for (PxU32 j = 0; j < nbY; j += strideY, localPos.y += spacingY) { localPos.x = sdf.mMeshLower.x; for (PxU32 i = 0; i < nbX; i += strideX, localPos.x += spacingX) { PxU32 color; if (sdf.mSubgridSize > 0 && k < nbZ - 1 && j < nbY - 1 && i < nbX - 1) { PxU32 startId = sdf.mSubgridStartSlots[k * (nbX - 1) * (nbY - 1) + j * (nbX - 1) + i]; if (startId != 0xFFFFFFFFu) { PxU32 xBase, yBase, zBase; decodeTriple(startId, xBase, yBase, zBase); xBase *= (subgridSize + 1); yBase *= (subgridSize + 1); zBase *= (subgridSize + 1); //Visualize the subgrid for (PxU32 z = 0; z <= subgridSize; z += subgridStride) { for (PxU32 y = 0; y <= subgridSize; y += subgridStride) { for (PxU32 x = 0; x <= subgridSize; x += subgridStride) { PxReal value = decode(&sdf.mSubgridSdf[sdf.mBytesPerSparsePixel * idx(xBase + x, yBase + y, zBase + z, sdf.mSdfSubgrids3DTexBlockDim.x * (subgridSize + 1), sdf.mSdfSubgrids3DTexBlockDim.y * (subgridSize + 1))], sdf.mBytesPerSparsePixel, sdf.mSubgridsMinSdfValue, sdf.mSubgridsMaxSdfValue); color = makeColor(value, invRange0, invRange1); PxVec3 subgridLocalPos = localPos + sdf.mSpacing * PxVec3(PxReal(x), PxReal(y), PxReal(z)); *points = PxDebugPoint(absPose.transform(subgridLocalPos), color); points++; } } } } } PxReal v = sdf.mSdf[k*nbX*nbY + j * nbX + i]; color = makeColor(v, invRange0, invRange1); *points = PxDebugPoint(absPose.transform(localPos), color); points++; } } } return dataReductionActive; } static PX_FORCE_INLINE void outputTriangle(PxDebugLine* segments, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxU32 color) { // PT: TODO: use SIMD segments[0] = PxDebugLine(v0, v1, color); segments[1] = PxDebugLine(v1, v2, color); segments[2] = PxDebugLine(v2, v0, color); } static void visualizeTriangleMesh(const PxTriangleMeshGeometry& geometry, PxRenderOutput& out, const PxTransform& pose, const PxBounds3& cullbox, PxReal fscale, bool visualizeShapes, bool visualizeEdges, bool useCullBox, bool visualizeSDFs) { const TriangleMesh* triangleMesh = static_cast<const TriangleMesh*>(geometry.triangleMesh); const PxMat44 midt(PxIdentity); // PT: TODO: why do we compute it that way sometimes? // const PxMat34 vertex2worldSkew = pose * geometry.scale; const PxMat33Padded m33(pose.q); const PxMat34 absPose(m33 * toMat33(geometry.scale), pose.p); PxU32 nbTriangles = triangleMesh->getNbTrianglesFast(); const PxU32 nbVertices = triangleMesh->getNbVerticesFast(); const PxVec3* vertices = triangleMesh->getVerticesFast(); const void* indices = triangleMesh->getTrianglesFast(); const bool has16Bit = triangleMesh->has16BitIndices(); bool drawSDF = visualizeSDFs && triangleMesh->getSDF(); PxU32* results = NULL; if (!drawSDF) { if (useCullBox) { const Box worldBox( (cullbox.maximum + cullbox.minimum)*0.5f, (cullbox.maximum - cullbox.minimum)*0.5f, PxMat33(PxIdentity)); // PT: TODO: use the callback version here to avoid allocating this huge array results = PX_ALLOCATE(PxU32, nbTriangles, "tmp triangle indices"); LimitedResults limitedResults(results, nbTriangles, 0); Midphase::intersectBoxVsMesh(worldBox, *triangleMesh, pose, geometry.scale, &limitedResults); nbTriangles = limitedResults.mNbResults; if (visualizeShapes) { const PxU32 scolor = gCollisionShapeColor; out << midt << scolor; // PT: no need to output this for each segment! // PT: TODO: don't render the same edge multiple times PxDebugLine* segments = out.reserveSegments(nbTriangles * 3); for (PxU32 i = 0; i < nbTriangles; i++) { PxVec3 wp[3 + 1]; getWorldTriangle(results[i], wp, vertices, indices, absPose, has16Bit); outputTriangle(segments, wp[0], wp[1], wp[2], scolor); segments += 3; } } } else { if (visualizeShapes) { const PxU32 scolor = gCollisionShapeColor; out << midt << scolor; // PT: no need to output this for each segment! const Vec4V posV = Vec4V_From_Vec3V(V3LoadU(&absPose.p.x)); PxVec3* transformed = PX_ALLOCATE(PxVec3, (nbVertices + 1), "PxVec3"); // for(PxU32 i=0;i<nbVertices;i++) // transformed[i] = absPose.transform(vertices[i]); for (PxU32 i = 0; i < nbVertices; i++) { //const Vec4V vertexV = V4LoadU(&vertices[i].x); //const Vec4V transformedV = V4Add(multiply3x3V(vertexV, absPose), posV); //V4StoreU(transformedV, &transformed[i].x); transformV(&transformed[i], &vertices[i], posV, absPose); } const Gu::EdgeList* edgeList = triangleMesh->requestEdgeList(); if (edgeList) { PxU32 nbEdges = edgeList->getNbEdges(); PxDebugLine* segments = out.reserveSegments(nbEdges); const Gu::EdgeData* edges = edgeList->getEdges(); while (nbEdges--) { segments->pos0 = transformed[edges->Ref0]; segments->pos1 = transformed[edges->Ref1]; segments->color0 = segments->color1 = scolor; segments++; edges++; } } else { PxDebugLine* segments = out.reserveSegments(nbTriangles * 3); for (PxU32 i = 0; i < nbTriangles; i++) { PxVec3 wp[3]; getTriangle(i, wp, transformed, indices, has16Bit); outputTriangle(segments, wp[0], wp[1], wp[2], scolor); segments += 3; } } PX_FREE(transformed); } } } if(fscale!=0.0f) { if(geometry.scale.hasNegativeDeterminant()) fscale = -fscale; visualizeFaceNormals(fscale, out, nbTriangles, vertices, indices, has16Bit, results, absPose, midt); } if(visualizeEdges) visualizeActiveEdges(out, *triangleMesh, nbTriangles, results, absPose); if (drawSDF) { const Gu::SDF& sdf = triangleMesh->getSdfDataFast(); //We have an SDF, we should debug render it... visualizeSDF(out, sdf, absPose); } PX_FREE(results); } static void visualizeHeightField(const PxHeightFieldGeometry& hfGeometry, PxRenderOutput& out, const PxTransform& absPose, const PxBounds3& cullbox, bool useCullBox) { const HeightField* heightfield = static_cast<const HeightField*>(hfGeometry.heightField); // PT: TODO: the debug viz for HFs is minimal at the moment... const PxU32 scolor = gCollisionShapeColor; const PxMat44 midt = PxMat44(PxIdentity); HeightFieldUtil hfUtil(hfGeometry); const PxU32 nbRows = heightfield->getNbRowsFast(); const PxU32 nbColumns = heightfield->getNbColumnsFast(); const PxU32 nbVerts = nbRows * nbColumns; const PxU32 nbTriangles = 2 * nbVerts; out << midt << scolor; // PT: no need to output the same matrix/color for each triangle if(useCullBox) { const PxTransform pose0((cullbox.maximum + cullbox.minimum)*0.5f); const PxBoxGeometry boxGeometry((cullbox.maximum - cullbox.minimum)*0.5f); PxU32* results = PX_ALLOCATE(PxU32, nbTriangles, "tmp triangle indices"); bool overflow = false; PxU32 nbTouchedTris = PxMeshQuery::findOverlapHeightField(boxGeometry, pose0, hfGeometry, absPose, results, nbTriangles, 0, overflow); PxDebugLine* segments = out.reserveSegments(nbTouchedTris*3); for(PxU32 i=0; i<nbTouchedTris; i++) { const PxU32 index = results[i]; PxTriangle currentTriangle; PxMeshQuery::getTriangle(hfGeometry, absPose, index, currentTriangle); //The check has been done in the findOverlapHeightField //if(heightfield->isValidTriangle(index) && heightfield->getTriangleMaterial(index) != PxHeightFieldMaterial::eHOLE) { outputTriangle(segments, currentTriangle.verts[0], currentTriangle.verts[1], currentTriangle.verts[2], scolor); segments+=3; } } PX_FREE(results); } else { // PT: transform vertices only once PxVec3* tmpVerts = PX_ALLOCATE(PxVec3, nbVerts, "PxVec3"); // PT: TODO: optimize the following line for(PxU32 i=0;i<nbVerts;i++) tmpVerts[i] = absPose.transform(hfUtil.hf2shapep(heightfield->getVertex(i))); for(PxU32 i=0; i<nbTriangles; i++) { if(heightfield->isValidTriangle(i) && heightfield->getTriangleMaterial(i) != PxHeightFieldMaterial::eHOLE) { PxU32 vi0, vi1, vi2; heightfield->getTriangleVertexIndices(i, vi0, vi1, vi2); PxDebugLine* segments = out.reserveSegments(3); outputTriangle(segments, tmpVerts[vi0], tmpVerts[vi1], tmpVerts[vi2], scolor); } } PX_FREE(tmpVerts); } } static void visualize(const PxGeometry& geometry, PxRenderOutput& out, const PxTransform& absPose, const PxBounds3& cullbox, const PxReal fscale, bool visualizeShapes, bool visualizeEdges, bool useCullBox, bool visualizeSDFs) { // triangle meshes can render active edges or face normals, but for other types we can just early out if there are no collision shapes if(!visualizeShapes && geometry.getType() != PxGeometryType::eTRIANGLEMESH) return; switch(geometry.getType()) { case PxGeometryType::eSPHERE: visualizeSphere(static_cast<const PxSphereGeometry&>(geometry), out, absPose); break; case PxGeometryType::eBOX: visualizeBox(static_cast<const PxBoxGeometry&>(geometry), out, absPose); break; case PxGeometryType::ePLANE: visualizePlane(static_cast<const PxPlaneGeometry&>(geometry), out, absPose); break; case PxGeometryType::eCAPSULE: visualizeCapsule(static_cast<const PxCapsuleGeometry&>(geometry), out, absPose); break; case PxGeometryType::eCONVEXMESH: visualizeConvexMesh(static_cast<const PxConvexMeshGeometry&>(geometry), out, absPose); break; case PxGeometryType::eTRIANGLEMESH: visualizeTriangleMesh(static_cast<const PxTriangleMeshGeometry&>(geometry), out, absPose, cullbox, fscale, visualizeShapes, visualizeEdges, useCullBox, visualizeSDFs); break; case PxGeometryType::eHEIGHTFIELD: visualizeHeightField(static_cast<const PxHeightFieldGeometry&>(geometry), out, absPose, cullbox, useCullBox); break; case PxGeometryType::eTETRAHEDRONMESH: case PxGeometryType::ePARTICLESYSTEM: // A.B. missing visualization code break; case PxGeometryType::eHAIRSYSTEM: break; case PxGeometryType::eCUSTOM: PX_ASSERT(static_cast<const PxCustomGeometry&>(geometry).isValid()); static_cast<const PxCustomGeometry&>(geometry).callbacks->visualize(geometry, out, absPose, cullbox); break; case PxGeometryType::eINVALID: break; case PxGeometryType::eGEOMETRY_COUNT: break; } } void NpShapeManager::visualize(PxRenderOutput& out, NpScene& scene, const PxRigidActor& actor, float scale) const { PX_ASSERT(scale!=0.0f); // Else we shouldn't have been called const Sc::Scene& scScene = scene.getScScene(); const PxU32 nbShapes = getNbShapes(); NpShape*const* PX_RESTRICT shapes = getShapes(); const bool visualizeCompounds = (nbShapes>1) && scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_COMPOUNDS)!=0.0f; // PT: moved all these out of the loop, no need to grab them once per shape const PxBounds3& cullbox = scScene.getVisualizationCullingBox(); const bool visualizeAABBs = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AABBS)!=0.0f; const bool visualizeShapes = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES)!=0.0f; const bool visualizeEdges = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_EDGES)!=0.0f; const bool visualizeSDFs = scScene.getVisualizationParameter(PxVisualizationParameter::eSDF)!=0.0f; const float fNormals = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_FNORMALS); const bool visualizeFNormals = fNormals!=0.0f; const bool visualizeCollision = visualizeShapes || visualizeFNormals || visualizeEdges || visualizeSDFs; const bool useCullBox = !cullbox.isEmpty(); const bool needsShapeBounds0 = visualizeCompounds || (visualizeCollision && useCullBox); const PxReal collisionAxes = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AXES); const PxReal fscale = scale * fNormals; const PxTransform32 actorPose(actor.getGlobalPose()); PxBounds3 compoundBounds(PxBounds3::empty()); for(PxU32 i=0;i<nbShapes;i++) { const NpShape& npShape = *shapes[i]; PxTransform32 absPose; aos::transformMultiply<true, true>(absPose, actorPose, npShape.getCore().getShape2Actor()); const PxGeometry& geom = npShape.getCore().getGeometry(); const bool shapeDebugVizEnabled = npShape.getCore().getFlags() & PxShapeFlag::eVISUALIZATION; const bool needsShapeBounds = needsShapeBounds0 || (visualizeAABBs && shapeDebugVizEnabled); const PxBounds3 currentShapeBounds = needsShapeBounds ? computeBounds(geom, absPose) : PxBounds3::empty(); if(shapeDebugVizEnabled) { if(visualizeAABBs) { out << PxU32(PxDebugColor::eARGB_YELLOW) << PxMat44(PxIdentity); renderOutputDebugBox(out, currentShapeBounds); } if(collisionAxes != 0.0f) { out << PxMat44(absPose); Cm::renderOutputDebugBasis(out, PxDebugBasis(PxVec3(collisionAxes), 0xcf0000, 0x00cf00, 0x0000cf)); } if(visualizeCollision) { if(!useCullBox || cullbox.intersects(currentShapeBounds)) ::visualize(geom, out, absPose, cullbox, fscale, visualizeShapes, visualizeEdges, useCullBox, visualizeSDFs); } } if(visualizeCompounds) compoundBounds.include(currentShapeBounds); } if(visualizeCompounds && !compoundBounds.isEmpty()) { out << gCollisionShapeColor << PxMat44(PxIdentity); renderOutputDebugBox(out, compoundBounds); } } ///// static PX_FORCE_INLINE void visualizeActor(PxRenderOutput& out, const Sc::Scene& scScene, const PxRigidActor& actor, float scale) { //visualize actor frames const PxReal actorAxes = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eACTOR_AXES); if(actorAxes != 0.0f) { out << actor.getGlobalPose(); Cm::renderOutputDebugBasis(out, PxDebugBasis(PxVec3(actorAxes))); } } void physx::visualizeRigidBody(PxRenderOutput& out, NpScene& scene, const PxRigidActor& actor, const Sc::BodyCore& core, float scale) { PX_ASSERT(scale!=0.0f); // Else we shouldn't have been called PX_ASSERT(core.getActorFlags() & PxActorFlag::eVISUALIZATION); // Else we shouldn't have been called const Sc::Scene& scScene = scene.getScScene(); visualizeActor(out, scScene, actor, scale); const PxTransform& body2World = core.getBody2World(); const PxReal bodyAxes = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eBODY_AXES); if(bodyAxes != 0.0f) { out << body2World; Cm::renderOutputDebugBasis(out, PxDebugBasis(PxVec3(bodyAxes))); } const PxReal linVelocity = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eBODY_LIN_VELOCITY); if(linVelocity != 0.0f) { out << 0xffffff << PxMat44(PxIdentity); Cm::renderOutputDebugArrow(out, PxDebugArrow(body2World.p, core.getLinearVelocity() * linVelocity, 0.2f * linVelocity)); } const PxReal angVelocity = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eBODY_ANG_VELOCITY); if(angVelocity != 0.0f) { out << 0x000000 << PxMat44(PxIdentity); Cm::renderOutputDebugArrow(out, PxDebugArrow(body2World.p, core.getAngularVelocity() * angVelocity, 0.2f * angVelocity)); } const PxReal massAxes = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eBODY_MASS_AXES); if(massAxes != 0.0f) { const PxReal sleepTime = core.getWakeCounter() / scene.getWakeCounterResetValueInternal(); PxU32 color = PxU32(0xff * (sleepTime>1.0f ? 1.0f : sleepTime)); color = core.isSleeping() ? 0xff0000 : (color<<16 | color<<8 | color); PxVec3 dims = invertDiagInertia(core.getInverseInertia()); dims = getDimsFromBodyInertia(dims, 1.0f / core.getInverseMass()); out << color << core.getBody2World(); const PxVec3 extents = dims * 0.5f; Cm::renderOutputDebugBox(out, PxBounds3(-extents, extents)); } } void NpRigidStatic::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { PX_ASSERT(scale!=0.0f); // Else we shouldn't have been called if(!(mCore.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; NpRigidStaticT::visualize(out, scene, scale); visualizeActor(out, scene.getScScene(), *this, scale); } void NpRigidDynamic::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { PX_ASSERT(scale!=0.0f); // Else we shouldn't have been called if(!(mCore.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; NpRigidDynamicT::visualize(out, scene, scale); } void NpArticulationLink::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { PX_ASSERT(scale!=0.0f); // Else we shouldn't have been called if(!(mCore.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; NpArticulationLinkT::visualize(out, scene, scale); const Sc::Scene& scScene = scene.getScScene(); const PxReal frameScale = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eJOINT_LOCAL_FRAMES); const PxReal limitScale = scale * scScene.getVisualizationParameter(PxVisualizationParameter::eJOINT_LIMITS); if(frameScale != 0.0f || limitScale != 0.0f) { ConstraintImmediateVisualizer viz(frameScale, limitScale, out); visualizeJoint(viz); } } void NpArticulationLink::visualizeJoint(PxConstraintVisualizer& jointViz) const { const NpArticulationLink* parent = getParent(); if(parent) { // PT:: tag: scalar transform*transform PxTransform cA2w = getGlobalPose().transform(mInboundJoint->getChildPose()); // PT:: tag: scalar transform*transform PxTransform cB2w = parent->getGlobalPose().transform(mInboundJoint->getParentPose()); jointViz.visualizeJointFrames(cA2w, cB2w); NpArticulationJointReducedCoordinate* impl = static_cast<NpArticulationJointReducedCoordinate*>(mInboundJoint); PX_ASSERT(getArticulation().getConcreteType() == PxConcreteType::eARTICULATION_REDUCED_COORDINATE); //(1) visualize any angular dofs/limits... const PxMat33 cA2w_m(cA2w.q), cB2w_m(cB2w.q); PxTransform parentFrame = cB2w; if (cA2w.q.dot(cB2w.q) < 0) cB2w.q = -cB2w.q; //const PxTransform cB2cA = cA2w.transformInv(cB2w); const PxTransform cA2cB = cB2w.transformInv(cA2w); Sc::ArticulationJointCore& joint = impl->getCore(); if(joint.getMotion(PxArticulationAxis::eTWIST)) { const PxArticulationLimit pair = joint.getLimit(PxArticulationAxis::Enum(PxArticulationAxis::eTWIST)); jointViz.visualizeAngularLimit(parentFrame, pair.low, pair.high); } if (joint.getMotion(PxArticulationAxis::eSWING1)) { const PxArticulationLimit pair = joint.getLimit(PxArticulationAxis::Enum(PxArticulationAxis::eSWING1)); PxTransform tmp = parentFrame; tmp.q = tmp.q * PxQuat(-PxPiDivTwo, PxVec3(0.f, 0.f, 1.f)); jointViz.visualizeAngularLimit(tmp, -pair.high, -pair.low); } if (joint.getMotion(PxArticulationAxis::eSWING2)) { const PxArticulationLimit pair = joint.getLimit(PxArticulationAxis::Enum(PxArticulationAxis::eSWING2)); PxTransform tmp = parentFrame; tmp.q = tmp.q * PxQuat(PxPiDivTwo, PxVec3(0.f, 1.f, 0.f)); jointViz.visualizeAngularLimit(tmp, -pair.high, -pair.low); } for (PxU32 i = PxArticulationAxis::eX; i <= PxArticulationAxis::eZ; ++i) { if (joint.getMotion(PxArticulationAxis::Enum(i)) == PxArticulationMotion::eLIMITED) { const PxU32 index = i - PxArticulationAxis::eX; const PxArticulationLimit pair = joint.getLimit(PxArticulationAxis::Enum(i)); const PxReal ordinate = cA2cB.p[index]; const PxVec3& origin = cB2w.p; const PxVec3& axis = cA2w_m[index]; const bool active = ordinate < pair.low || ordinate > pair.high; const PxVec3 p0 = origin + axis * pair.low; const PxVec3 p1 = origin + axis * pair.high; jointViz.visualizeLine(p0, p1, active ? 0xff0000u : 0xffffffu); } } } } void NpArticulationReducedCoordinate::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { const PxU32 nbLinks = mArticulationLinks.size(); for (PxU32 i = 0; i < nbLinks; i++) mArticulationLinks[i]->visualize(out, scene, scale); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif void NpScene::visualize() { PX_PROFILE_ZONE("NpScene::visualize", getContextId()); NP_READ_CHECK(this); mRenderBuffer.clear(); // clear last frame visualizations #if PX_ENABLE_DEBUG_VISUALIZATION const PxReal scale = mScene.getVisualizationParameter(PxVisualizationParameter::eSCALE); if(scale == 0.0f) return; PxRenderOutput out(mRenderBuffer); // Visualize scene axes const PxReal worldAxes = scale * mScene.getVisualizationParameter(PxVisualizationParameter::eWORLD_AXES); if(worldAxes != 0) Cm::renderOutputDebugBasis(out, PxDebugBasis(PxVec3(worldAxes))); // Visualize articulations const PxU32 articulationCount = mArticulations.size(); for(PxU32 i=0;i<articulationCount;i++) static_cast<const NpArticulationReducedCoordinate *>(mArticulations.getEntries()[i])->visualize(out, *this, scale); // Visualize rigid actors const PxU32 rigidDynamicCount = mRigidDynamics.size(); for(PxU32 i=0; i<rigidDynamicCount; i++) mRigidDynamics[i]->visualize(out, *this, scale); const PxU32 rigidStaticCount = mRigidStatics.size(); for(PxU32 i=0; i<rigidStaticCount; i++) mRigidStatics[i]->visualize(out, *this, scale); // Visualize pruning structures const bool visStatic = mScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_STATIC) != 0.0f; const bool visDynamic = mScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_DYNAMIC) != 0.0f; //flushQueryUpdates(); // DE7834 if(visStatic) getSQAPI().visualize(PxU32(PX_SCENE_PRUNER_STATIC), out); if(visDynamic) getSQAPI().visualize(PxU32(PX_SCENE_PRUNER_DYNAMIC), out); if(visStatic || visDynamic) getSQAPI().visualize(PxU32(PX_SCENE_COMPOUND_PRUNER), out); if(mScene.getVisualizationParameter(PxVisualizationParameter::eMBP_REGIONS) != 0.0f) { out << PxTransform(PxIdentity); const Bp::BroadPhase* bp = mScene.getAABBManager()->getBroadPhase(); const PxU32 nbRegions = bp->getNbRegions(); for(PxU32 i=0;i<nbRegions;i++) { PxBroadPhaseRegionInfo info; bp->getRegions(&info, 1, i); if(info.mActive) out << PxU32(PxDebugColor::eARGB_YELLOW); else out << PxU32(PxDebugColor::eARGB_BLACK); Cm::renderOutputDebugBox(out, info.mRegion.mBounds); } } if(mScene.getVisualizationParameter(PxVisualizationParameter::eCULL_BOX)!=0.0f) { const PxBounds3& cullbox = mScene.getVisualizationCullingBox(); if(!cullbox.isEmpty()) { out << PxU32(PxDebugColor::eARGB_YELLOW); Cm::renderOutputDebugBox(out, cullbox); } } #if PX_SUPPORT_GPU_PHYSX // Visualize particle systems { { PxPBDParticleSystem*const* particleSystems = mPBDParticleSystems.getEntries(); const PxU32 particleSystemCount = mPBDParticleSystems.size(); for (PxU32 i = 0; i < particleSystemCount; i++) static_cast<NpPBDParticleSystem*>(particleSystems[i])->visualize(out, *this); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION { PxFLIPParticleSystem*const* particleSystems = mFLIPParticleSystems.getEntries(); const PxU32 particleSystemCount = mFLIPParticleSystems.size(); for (PxU32 i = 0; i < particleSystemCount; i++) static_cast<NpFLIPParticleSystem*>(particleSystems[i])->visualize(out, *this); } { PxMPMParticleSystem*const* particleSystems = mMPMParticleSystems.getEntries(); const PxU32 particleSystemCount = mMPMParticleSystems.size(); for (PxU32 i = 0; i < particleSystemCount; i++) static_cast<NpMPMParticleSystem*>(particleSystems[i])->visualize(out, *this); } #endif } // Visualize soft bodies { PxSoftBody*const* softBodies = mSoftBodies.getEntries(); const PxU32 softBodyCount = mSoftBodies.size(); const bool visualize = mScene.getVisualizationParameter(PxVisualizationParameter::eSIMULATION_MESH) != 0.0f; for(PxU32 i=0; i<softBodyCount; i++) softBodies[i]->setSoftBodyFlag(PxSoftBodyFlag::eDISPLAY_SIM_MESH, visualize); } // FEM-cloth // no change // visualize hair systems { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION const PxHairSystem*const* hairSystems = mHairSystems.getEntries(); const PxU32 hairSystemCount = mHairSystems.size(); for (PxU32 i = 0; i < hairSystemCount; i++) static_cast<const NpHairSystem*>(hairSystems[i])->visualize(out, *this); #endif } #endif #if PX_SUPPORT_PVD mScenePvdClient.visualize(mRenderBuffer); #endif #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif }
38,518
C++
32.436632
240
0.718391
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFactory.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_FACTORY_H #define NP_FACTORY_H #include "foundation/PxPool.h" #include "foundation/PxMutex.h" #include "foundation/PxHashSet.h" #include "GuMeshFactory.h" #include "PxPhysXConfig.h" #include "PxShape.h" #include "PxAggregate.h" #include "PxvGeometry.h" #include "NpFEMCloth.h" // to be deleted namespace physx { class PxCudaContextManager; class PxActor; class PxRigidActor; class PxRigidStatic; class NpRigidStatic; class PxRigidDynamic; class NpRigidDynamic; class NpConnectorArray; struct PxConstraintShaderTable; class PxConstraintConnector; class PxConstraint; class NpConstraint; class PxArticulationReducedCoordinate; class NpArticulationReducedCoordinate; class PxArticulationLink; class NpArticulationLink; class NpArticulationJointReducedCoordinate; class PxSoftBody; class PxFEMCloth; class PxParticleSystem; class PxHairSystem; #if PX_SUPPORT_GPU_PHYSX class NpSoftBody; class NpFEMCloth; class NpPBDParticleSystem; class NpFLIPParticleSystem; class NpMPMParticleSystem; class NpHairSystem; class NpFEMSoftBodyMaterial; class NpFEMClothMaterial; class NpPBDMaterial; class NpFLIPMaterial; class NpMPMMaterial; #endif class PxMaterial; class NpMaterial; class PxFEMSoftBodyMaterial; class PxFEMClothMaterial; class PxPBDMaterial; class PxFLIPMaterial; class PxMPMMaterial; class PxGeometry; class NpShape; class NpAggregate; class NpPtrTableStorageManager; namespace Cm { class Collection; } class NpFactoryListener : public Gu::MeshFactoryListener { protected: virtual ~NpFactoryListener(){} }; class NpFactory : public Gu::MeshFactory { PX_NOCOPY(NpFactory) public: NpFactory(); private: ~NpFactory(); template <typename PxMaterialType, typename NpMaterialType> NpShape* createShapeInternal(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxMaterialType*const* materials, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum flag); public: static void createInstance(); static void destroyInstance(); static void onParticleBufferRelease(PxParticleBuffer* buffer); void release(); void addCollection(const Cm::Collection& collection); PX_INLINE static NpFactory& getInstance() { return *mInstance; } // Rigid dynamic PxRigidDynamic* createRigidDynamic(const PxTransform& pose); void addRigidDynamic(PxRigidDynamic*, bool lock=true); void releaseRigidDynamicToPool(NpRigidDynamic&); // PT: TODO: add missing functions // PxU32 getNbRigidDynamics() const; // PxU32 getRigidDynamics(PxRigidDynamic** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; // Rigid static PxRigidStatic* createRigidStatic(const PxTransform& pose); void addRigidStatic(PxRigidStatic*, bool lock=true); void releaseRigidStaticToPool(NpRigidStatic&); // PT: TODO: add missing functions // PxU32 getNbRigidStatics() const; // PxU32 getRigidStatics(PxRigidStatic** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; // Shapes NpShape* createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxMaterial*const* materials, PxU16 materialCount, bool isExclusive); NpShape* createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxFEMSoftBodyMaterial*const* materials, PxU16 materialCount, bool isExclusive); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX NpShape* createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxFEMClothMaterial*const* materials, PxU16 materialCount, bool isExclusive); #endif void addShape(PxShape*, bool lock=true); void releaseShapeToPool(NpShape&); PxU32 getNbShapes() const; PxU32 getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; // Constraints PxConstraint* createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize); void addConstraint(PxConstraint*, bool lock=true); void releaseConstraintToPool(NpConstraint&); // PT: TODO: add missing functions // PxU32 getNbConstraints() const; // PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; // Articulations void addArticulation(PxArticulationReducedCoordinate*, bool lock=true); void releaseArticulationToPool(PxArticulationReducedCoordinate& articulation); PxArticulationReducedCoordinate* createArticulationRC(); NpArticulationReducedCoordinate* createNpArticulationRC(); // Articulation links NpArticulationLink* createNpArticulationLink(NpArticulationReducedCoordinate& root, NpArticulationLink* parent, const PxTransform& pose); void releaseArticulationLinkToPool(NpArticulationLink& articulation); PxArticulationLink* createArticulationLink(NpArticulationReducedCoordinate& root, NpArticulationLink* parent, const PxTransform& pose); NpArticulationJointReducedCoordinate* createNpArticulationJointRC(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame); void releaseArticulationJointRCToPool(NpArticulationJointReducedCoordinate& articulationJoint); #if PX_SUPPORT_GPU_PHYSX //Soft bodys PxSoftBody* createSoftBody(PxCudaContextManager& cudaContextManager); void releaseSoftBodyToPool(PxSoftBody& softBody); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION // FEMCloth PxFEMCloth* createFEMCloth(PxCudaContextManager& cudaContextManager); void releaseFEMClothToPool(PxFEMCloth& femCloth); #endif //Particle systems PxPBDParticleSystem* createPBDParticleSystem(PxU32 maxNeighborhood, PxCudaContextManager& cudaContextManager); void releasePBDParticleSystemToPool(PxPBDParticleSystem& particleSystem); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION //Particle systems PxFLIPParticleSystem* createFLIPParticleSystem(PxCudaContextManager& cudaContextManager); void releaseFLIPParticleSystemToPool(PxFLIPParticleSystem& particleSystem); //Particle systems PxMPMParticleSystem* createMPMParticleSystem(PxCudaContextManager& cudaContextManager); void releaseMPMParticleSystemToPool(PxMPMParticleSystem& particleSystem); #endif //Particle buffers PxParticleBuffer* createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager); //Diffuse Particle buffers PxParticleAndDiffuseBuffer* createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager); //Particle cloth buffers PxParticleClothBuffer* createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager); //Particle rigid buffers PxParticleRigidBuffer* createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION // HairSystem PxHairSystem* createHairSystem(PxCudaContextManager& cudaContextManager); void releaseHairSystemToPool(PxHairSystem& hairSystem); #endif #endif // Aggregates PxAggregate* createAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint); void addAggregate(PxAggregate*, bool lock=true); void releaseAggregateToPool(NpAggregate&); // PT: TODO: add missing functions // PxU32 getNbAggregates() const; // PxU32 getAggregates(PxAggregate** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; // Materials PxMaterial* createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution); void releaseMaterialToPool(NpMaterial& material); #if PX_SUPPORT_GPU_PHYSX PxFEMSoftBodyMaterial* createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction); void releaseFEMMaterialToPool(PxFEMSoftBodyMaterial& material); PxFEMClothMaterial* createFEMClothMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal thickness); void releaseFEMClothMaterialToPool(PxFEMClothMaterial& material); PxPBDMaterial* createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient, PxReal gravityScale); void releasePBDMaterialToPool(PxPBDMaterial& material); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFLIPMaterial* createFLIPMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal gravityScale); void releaseFLIPMaterialToPool(PxFLIPMaterial& material); #endif 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); void releaseMPMMaterialToPool(PxMPMMaterial& material); #endif // It's easiest to track these uninvasively, so it's OK to use the Px pointers void onActorRelease(PxActor*); void onConstraintRelease(PxConstraint*); void onAggregateRelease(PxAggregate*); void onArticulationRelease(PxArticulationReducedCoordinate*); void onShapeRelease(PxShape*); #if PX_SUPPORT_GPU_PHYSX void addParticleBuffer(PxParticleBuffer* buffer, bool lock = true); void onParticleBufferReleaseInternal(PxParticleBuffer* buffer); #endif NpConnectorArray* acquireConnectorArray(); void releaseConnectorArray(NpConnectorArray*); PX_FORCE_INLINE NpPtrTableStorageManager& getPtrTableStorageManager() { return *mPtrTableStorageManager; } #if PX_SUPPORT_PVD void setNpFactoryListener( NpFactoryListener& ); #endif private: PxPool<NpConnectorArray> mConnectorArrayPool; PxMutex mConnectorArrayPoolLock; NpPtrTableStorageManager* mPtrTableStorageManager; PxHashSet<PxAggregate*> mAggregateTracking; PxHashSet<PxArticulationReducedCoordinate*> mArticulationTracking; PxHashSet<PxConstraint*> mConstraintTracking; PxHashSet<PxActor*> mActorTracking; PxCoalescedHashSet<PxShape*> mShapeTracking; #if PX_SUPPORT_GPU_PHYSX PxHashSet<PxParticleBuffer*> mParticleBufferTracking; #endif PxPool2<NpRigidDynamic, 4096> mRigidDynamicPool; PxMutex mRigidDynamicPoolLock; PxPool2<NpRigidStatic, 4096> mRigidStaticPool; PxMutex mRigidStaticPoolLock; PxPool2<NpShape, 4096> mShapePool; PxMutex mShapePoolLock; PxPool2<NpAggregate, 4096> mAggregatePool; PxMutex mAggregatePoolLock; PxPool2<NpConstraint, 4096> mConstraintPool; PxMutex mConstraintPoolLock; PxPool2<NpMaterial, 4096> mMaterialPool; PxMutex mMaterialPoolLock; PxPool2<NpArticulationReducedCoordinate, 4096> mArticulationRCPool; PxMutex mArticulationRCPoolLock; PxPool2<NpArticulationLink, 4096> mArticulationLinkPool; PxMutex mArticulationLinkPoolLock; PxPool2<NpArticulationJointReducedCoordinate, 4096> mArticulationRCJointPool; PxMutex mArticulationJointRCPoolLock; #if PX_SUPPORT_GPU_PHYSX PxPool2<NpSoftBody, 4096> mSoftBodyPool; PxMutex mSoftBodyPoolLock; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxPool2<NpFEMCloth, 4096> mFEMClothPool; PxMutex mFEMClothPoolLock; #endif PxPool2<NpPBDParticleSystem, 4096> mPBDParticleSystemPool; PxMutex mPBDParticleSystemPoolLock; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxPool2<NpFLIPParticleSystem, 4096> mFLIPParticleSystemPool; PxMutex mFLIPParticleSystemPoolLock; PxPool2<NpMPMParticleSystem, 4096> mMPMParticleSystemPool; PxMutex mMPMParticleSystemPoolLock; #endif PxPool2<NpFEMSoftBodyMaterial, 4096> mFEMMaterialPool; PxMutex mFEMMaterialPoolLock; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxPool2<NpFEMClothMaterial, 4096> mFEMClothMaterialPool; PxMutex mFEMClothMaterialPoolLock; #endif PxPool2<NpPBDMaterial, 4096> mPBDMaterialPool; PxMutex mPBDMaterialPoolLock; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxPool2<NpFLIPMaterial, 4096> mFLIPMaterialPool; PxMutex mFLIPMaterialPoolLock; PxPool2<NpMPMMaterial, 4096> mMPMMaterialPool; PxMutex mMPMMaterialPoolLock; /*PxPool2<NpFEMSoftBodyMaterial, 4096> mFEMMaterialPool; PxMutex mFEMMaterialPoolLock;*/ PxPool2<NpHairSystem, 4096> mHairSystemPool; PxMutex mHairSystemPoolLock; #endif #endif static NpFactory* mInstance; PxU64 mGpuMemStat; #if PX_SUPPORT_PVD NpFactoryListener* mNpFactoryListener; #endif }; void NpDestroyRigidActor(NpRigidStatic* np); void NpDestroyRigidDynamic(NpRigidDynamic* np); void NpDestroyArticulationLink(NpArticulationLink* np); void NpDestroyArticulationJoint(PxArticulationJointReducedCoordinate* np); void NpDestroyArticulation(PxArticulationReducedCoordinate* artic); void NpDestroyAggregate(NpAggregate* np); void NpDestroyShape(NpShape* np); void NpDestroyConstraint(NpConstraint* np); #if PX_SUPPORT_GPU_PHYSX void NpDestroySoftBody(NpSoftBody* softBody); void NpDestroyFEMCloth(NpFEMCloth* femCloth); void NpDestroyParticleSystem(NpPBDParticleSystem* particleSystem); void NpDestroyParticleSystem(NpFLIPParticleSystem* particleSystem); void NpDestroyParticleSystem(NpMPMParticleSystem* particleSystem); void NpDestroyHairSystem(NpHairSystem* hairSystem); #endif } #endif
15,981
C
40.084833
341
0.757212
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationJointReducedCoordinate.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 "NpCheck.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationReducedCoordinate.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; namespace physx { //PX_SERIALIZATION NpArticulationJointReducedCoordinate* NpArticulationJointReducedCoordinate::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationJointReducedCoordinate* obj = PX_PLACEMENT_NEW(address, NpArticulationJointReducedCoordinate(PxBaseFlags(0))); address += sizeof(NpArticulationJointReducedCoordinate); obj->importExtraData(context); obj->resolveReferences(context); return obj; } void NpArticulationJointReducedCoordinate::resolveReferences(PxDeserializationContext& context) { //mImpl.resolveReferences(context, *this); context.translatePxBase(mParent); context.translatePxBase(mChild); mCore.setRoot(this); NpArticulationReducedCoordinate* articulation = static_cast<NpArticulationReducedCoordinate*>(&mParent->getRoot()); mCore.setArticulation(&articulation->getCore()); } //~PX_SERIALIZATION NpArticulationJointReducedCoordinate::NpArticulationJointReducedCoordinate(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame) : PxArticulationJointReducedCoordinate(PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_JOINT), mCore(parentFrame, childFrame), mParent(&parent), mChild(&child) { NpArticulationReducedCoordinate* articulation = static_cast<NpArticulationReducedCoordinate*>(&parent.getRoot()); mCore.setArticulation(&articulation->getCore()); mCore.setRoot(this); } NpArticulationJointReducedCoordinate::~NpArticulationJointReducedCoordinate() { } void NpArticulationJointReducedCoordinate::setJointType(PxArticulationJointType::Enum jointType) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationJointReducedCoordinate::setJointType() not allowed while the articulation is in a scene. Call will be ignored."); return; } PX_CHECK_AND_RETURN(jointType != PxArticulationJointType::eUNDEFINED, "PxArticulationJointReducedCoordinate::setJointType valid joint type(ePRISMATIC, eREVOLUTE, eREVOLUTE_UNWRAPPED, eSPHERICAL, eFIX) need to be set"); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, type, static_cast<PxArticulationJointReducedCoordinate&>(*this), jointType) scSetJointType(jointType); } PxArticulationJointType::Enum NpArticulationJointReducedCoordinate::getJointType() const { return mCore.getJointType(); } #if PX_CHECKED bool NpArticulationJointReducedCoordinate::isValidMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { bool valid = true; switch (mCore.getJointType()) { case PxArticulationJointType::ePRISMATIC: { if (axis < PxArticulationAxis::eX && motion != PxArticulationMotion::eLOCKED) valid = false; else if(motion != PxArticulationMotion::eLOCKED) { //Check to ensure that we only have zero DOFs already active... for (PxU32 i = PxArticulationAxis::eX; i <= PxArticulationAxis::eZ; i++) { if(i != PxU32(axis) && mCore.getMotion(PxArticulationAxis::Enum(i)) != PxArticulationMotion::eLOCKED) valid = false; } } break; } case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { if (axis >= PxArticulationAxis::eX && motion != PxArticulationMotion::eLOCKED) valid = false; else if (motion != PxArticulationMotion::eLOCKED) { for (PxU32 i = PxArticulationAxis::eTWIST; i < PxArticulationAxis::eX; i++) { if (i != PxU32(axis) && mCore.getMotion(PxArticulationAxis::Enum(i)) != PxArticulationMotion::eLOCKED) valid = false; } } break; } case PxArticulationJointType::eSPHERICAL: { if (axis >= PxArticulationAxis::eX && motion != PxArticulationMotion::eLOCKED) valid = false; break; } case PxArticulationJointType::eFIX: { if (motion != PxArticulationMotion::eLOCKED) valid = false; break; } case PxArticulationJointType::eUNDEFINED: { valid = false; break; } default: break; } return valid; } #endif void NpArticulationJointReducedCoordinate::setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationJointReducedCoordinate::setMotion() not allowed while the articulation is in a scene. Call will be ignored."); return; } PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eUNDEFINED, "PxArticulationJointReducedCoordinate::setMotion valid joint type(ePRISMATIC, eREVOLUTE, eREVOUTE_UNWRAPPED, eSPHERICAL or eFIX) has to be set before setMotion"); PX_CHECK_AND_RETURN(isValidMotion(axis, motion), "PxArticulationJointReducedCoordinate::setMotion illegal configuration for the joint type that is set."); scSetMotion(axis, motion); #if PX_SUPPORT_OMNI_PVD PxArticulationMotion::Enum motions[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) motions[ax] = mCore.getMotion(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, motion, static_cast<PxArticulationJointReducedCoordinate&>(*this), motions, PxArticulationAxis::eCOUNT); #endif static_cast<NpArticulationReducedCoordinate*>(&getChild().getArticulation())->mTopologyChanged = true; } PxArticulationMotion::Enum NpArticulationJointReducedCoordinate::getMotion(PxArticulationAxis::Enum axis) const { return mCore.getMotion(axis); } void NpArticulationJointReducedCoordinate::setFrictionCoefficient(const PxReal coefficient) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setFrictionCoefficient() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, frictionCoefficient, static_cast<PxArticulationJointReducedCoordinate&>(*this), coefficient); scSetFrictionCoefficient(coefficient); } PxReal NpArticulationJointReducedCoordinate::getFrictionCoefficient() const { NP_READ_CHECK(getNpScene()); return mCore.getFrictionCoefficient(); } void NpArticulationJointReducedCoordinate::setMaxJointVelocity(const PxReal maxJointV) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setMaxJointVelocity() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, maxJointVelocity, static_cast<PxArticulationJointReducedCoordinate&>(*this), maxJointV); scSetMaxJointVelocity(maxJointV); } PxReal NpArticulationJointReducedCoordinate::getMaxJointVelocity() const { NP_READ_CHECK(getNpScene()); return mCore.getMaxJointVelocity(); } void NpArticulationJointReducedCoordinate::setLimitParams(PxArticulationAxis::Enum axis, const PxArticulationLimit& pair) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(PxIsFinite(pair.low) && PxIsFinite(pair.high) && pair.low <= pair.high, "PxArticulationJointReducedCoordinate::setLimitParams(): Invalid limit parameters; lowLimit must be <= highLimit."); PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eSPHERICAL || (PxAbs(pair.low) <= PxPi && PxAbs(pair.high) <= PxPi), "PxArticulationJointReducedCoordinate::setLimitParams() only supports limit angles in range [-Pi, Pi] for joints of type PxArticulationJointType::eSPHERICAL"); PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eREVOLUTE || (PxAbs(pair.low) <= 2.0f*PxPi && PxAbs(pair.high) <= 2.0f*PxPi), "PxArticulationJointReducedCoordinate::setLimitParams() only supports limit angles in range [-2Pi, 2Pi] for joints of type PxArticulationJointType::eREVOLUTE"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setLimitParams() not allowed while simulation is running. Call will be ignored.") scSetLimit(axis, pair); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxArticulationJointReducedCoordinate& joint = *this; PxReal limits[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) limits[ax] = mCore.getLimit(static_cast<PxArticulationAxis::Enum>(ax)).low; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, limitLow, joint, limits, PxArticulationAxis::eCOUNT); for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) limits[ax] = mCore.getLimit(static_cast<PxArticulationAxis::Enum>(ax)).high; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, limitHigh, joint, limits, PxArticulationAxis::eCOUNT); OMNI_PVD_WRITE_SCOPE_END #endif } PxArticulationLimit NpArticulationJointReducedCoordinate::getLimitParams(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); return mCore.getLimit(axis); } void NpArticulationJointReducedCoordinate::setDriveParams(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setDriveParams() not allowed while simulation is running. Call will be ignored.") scSetDrive(axis, drive); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxArticulationJointReducedCoordinate& joint = *this; PxReal stiffnesss[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) stiffnesss[ax] = mCore.getDrive(static_cast<PxArticulationAxis::Enum>(ax)).stiffness; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveStiffness, joint, stiffnesss, PxArticulationAxis::eCOUNT); PxReal dampings[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) dampings[ax] = mCore.getDrive(static_cast<PxArticulationAxis::Enum>(ax)).damping; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveDamping, joint, dampings, PxArticulationAxis::eCOUNT); PxReal maxforces[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) maxforces[ax] = mCore.getDrive(static_cast<PxArticulationAxis::Enum>(ax)).maxForce; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveMaxForce, joint, maxforces, PxArticulationAxis::eCOUNT); PxArticulationDriveType::Enum drivetypes[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) drivetypes[ax] = mCore.getDrive(static_cast<PxArticulationAxis::Enum>(ax)).driveType; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveType, joint, drivetypes, PxArticulationAxis::eCOUNT); OMNI_PVD_WRITE_SCOPE_END #endif } PxArticulationDrive NpArticulationJointReducedCoordinate::getDriveParams(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); return mCore.getDrive(axis); } void NpArticulationJointReducedCoordinate::setDriveTarget(PxArticulationAxis::Enum axis, const PxReal target, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eSPHERICAL || PxAbs(target) <= PxPi, "PxArticulationJointReducedCoordinate::setDriveTarget() only supports target angle in range [-Pi, Pi] for joints of type PxArticulationJointType::eSPHERICAL"); PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eREVOLUTE || PxAbs(target) <= 2.0f*PxPi, "PxArticulationJointReducedCoordinate::setDriveTarget() only supports target angle in range [-2Pi, 2Pi] for joints of type PxArticulationJointType::eREVOLUTE"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationJointReducedCoordinate::setDriveTarget() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationJointReducedCoordinate::setDriveTarget(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } if (autowake && npScene) { NpArticulationReducedCoordinate* npArticulation = static_cast<NpArticulationReducedCoordinate*>(&mParent->getArticulation()); npArticulation->autoWakeInternal(); } scSetDriveTarget(axis, target); #if PX_SUPPORT_OMNI_PVD PxReal targets[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) targets[ax] = mCore.getTargetP(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveTarget, static_cast<PxArticulationJointReducedCoordinate&>(*this), targets, PxArticulationAxis::eCOUNT); #endif } void NpArticulationJointReducedCoordinate::setDriveVelocity(PxArticulationAxis::Enum axis, const PxReal targetVel, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationJointReducedCoordinate::setDriveVelocity() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationJointReducedCoordinate::setDriveVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } if (autowake && npScene) { NpArticulationReducedCoordinate* npArticulation = static_cast<NpArticulationReducedCoordinate*>(&mParent->getArticulation()); npArticulation->autoWakeInternal(); } scSetDriveVelocity(axis, targetVel); #if PX_SUPPORT_OMNI_PVD PxReal velocities[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) velocities[ax] = mCore.getTargetV(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveVelocity, static_cast<PxArticulationJointReducedCoordinate&>(*this), velocities, PxArticulationAxis::eCOUNT); #endif } PxReal NpArticulationJointReducedCoordinate::getDriveTarget(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); return mCore.getTargetP(axis); } PxReal NpArticulationJointReducedCoordinate::getDriveVelocity(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); return mCore.getTargetV(axis); } void NpArticulationJointReducedCoordinate::setArmature(PxArticulationAxis::Enum axis, const PxReal armature) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setArmature() not allowed while simulation is running. Call will be ignored.") scSetArmature(axis, armature); #if PX_SUPPORT_OMNI_PVD PxReal armatures[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) armatures[ax] = mCore.getArmature(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, armature, static_cast<PxArticulationJointReducedCoordinate&>(*this), armatures, PxArticulationAxis::eCOUNT); #endif } PxReal NpArticulationJointReducedCoordinate::getArmature(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); return mCore.getArmature(axis); } PxTransform NpArticulationJointReducedCoordinate::getParentPose() const { NP_READ_CHECK(getNpScene()); // PT:: tag: scalar transform*transform return mParent->getCMassLocalPose().transform(mCore.getParentPose()); } void NpArticulationJointReducedCoordinate::setParentPose(const PxTransform& t) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(t.isSane(), "PxArticulationJointReducedCoordinate::setParentPose: Input pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setParentPose() not allowed while simulation is running. Call will be ignored.") #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxArticulationJointReducedCoordinate& joint = *this; OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, parentTranslation, joint, t.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, parentRotation, joint, t.q) OMNI_PVD_WRITE_SCOPE_END #endif if (mParent == NULL) return; scSetParentPose(mParent->getCMassLocalPose().transformInv(t.getNormalized())); } PxTransform NpArticulationJointReducedCoordinate::getChildPose() const { NP_READ_CHECK(getNpScene()); // PT:: tag: scalar transform*transform return mChild->getCMassLocalPose().transform(mCore.getChildPose()); } void NpArticulationJointReducedCoordinate::setChildPose(const PxTransform& t) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(t.isSane(), "PxArticulationJointReducedCoordinate::setChildPose: Input pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationJointReducedCoordinate::setChildPose() not allowed while simulation is running. Call will be ignored.") #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxArticulationJointReducedCoordinate& joint = *this; OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, childTranslation, joint, t.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, childRotation, joint, t.q) OMNI_PVD_WRITE_SCOPE_END #endif scSetChildPose(mChild->getCMassLocalPose().transformInv(t.getNormalized())); } void NpArticulationJointReducedCoordinate::setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(jointPos), "PxArticulationJointReducedCoordinate::setJointPosition: jointPos is not valid."); PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eSPHERICAL || PxAbs(jointPos) <= PxPi, "PxArticulationJointReducedCoordinate::setJointPosition() only supports jointPos in range [-Pi, Pi] for joints of type PxArticulationJointType::eSPHERICAL"); PX_CHECK_AND_RETURN(getJointType() != PxArticulationJointType::eREVOLUTE || PxAbs(jointPos) <= 2.0f*PxPi, "PxArticulationJointReducedCoordinate::setJointPosition() only supports jointPos in range [-2Pi, 2Pi] for joints of type PxArticulationJointType::eREVOLUTE"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationJointReducedCoordinate::setJointPosition() not allowed while simulation is running. Call will be ignored."); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationJointReducedCoordinate::setJointPosition(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } scSetJointPosition(axis, jointPos); #if PX_SUPPORT_OMNI_PVD PxReal positions[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) positions[ax] = mCore.getJointPosition(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointPosition, static_cast<PxArticulationJointReducedCoordinate&>(*this), positions, PxArticulationAxis::eCOUNT); #endif } PxReal NpArticulationJointReducedCoordinate::getJointPosition(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationJointReducedCoordinate::getJointPosition() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", 0.f); return mCore.getJointPosition(axis); } void NpArticulationJointReducedCoordinate::setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(jointVel), "PxArticulationJointReducedCoordinate::setJointVelocity: jointVel is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationJointReducedCoordinate::setJointVelocity() not allowed while simulation is running. Call will be ignored."); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationJointReducedCoordinate::setJointVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } scSetJointVelocity(axis, jointVel); #if PX_SUPPORT_OMNI_PVD PxReal velocities[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) velocities[ax] = mCore.getJointVelocity(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointVelocity, static_cast<PxArticulationJointReducedCoordinate&>(*this), velocities, PxArticulationAxis::eCOUNT); #endif } PxReal NpArticulationJointReducedCoordinate::getJointVelocity(PxArticulationAxis::Enum axis) const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationJointReducedCoordinate::getJointVelocity() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", 0.f); return mCore.getJointVelocity(axis); } void NpArticulationJointReducedCoordinate::release() { NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, NULL); if(getNpScene()) getNpScene()->scRemoveArticulationJoint(*this); PX_ASSERT(!isAPIWriteForbidden()); NpDestroyArticulationJoint(mCore.getRoot()); } }
24,393
C++
45.553435
305
0.779732
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneClient.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_PVD #include "common/PxProfileZone.h" #include "common/PxRenderBuffer.h" #include "PxParticleSystem.h" #include "PxPBDParticleSystem.h" //#include "PxFLIPParticleSystem.h" //#include "PxMPMParticleSystem.h" #include "PxPhysics.h" #include "PxConstraintDesc.h" #include "NpPvdSceneClient.h" #include "ScBodySim.h" #include "ScConstraintSim.h" #include "ScConstraintCore.h" #include "PxsMaterialManager.h" #include "PvdTypeNames.h" #include "PxPvdUserRenderer.h" #include "PxvNphaseImplementationContext.h" #include "NpConstraint.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "NpSoftBody.h" //#include "NpFEMCloth.h" #include "NpHairSystem.h" #include "NpAggregate.h" #include "NpScene.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationReducedCoordinate.h" using namespace physx; using namespace physx::Vd; using namespace physx::pvdsdk; namespace { PX_FORCE_INLINE PxU64 getContextId(NpScene& scene) { return scene.getScScene().getContextId(); } /////////////////////////////////////////////////////////////////////////////// // Sc-to-Np PX_FORCE_INLINE static NpConstraint* getNpConstraint(Sc::ConstraintCore* scConstraint) { return reinterpret_cast<NpConstraint*>(reinterpret_cast<char*>(scConstraint) - NpConstraint::getCoreOffset()); } /////////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE static const PxActor* getPxActor(const NpActor* scActor) { return scActor->getPxActor(); } struct CreateOp { CreateOp& operator=(const CreateOp&); physx::pvdsdk::PvdDataStream& mStream; PvdMetaDataBinding& mBinding; PsPvd* mPvd; PxScene& mScene; CreateOp(physx::pvdsdk::PvdDataStream& str, PvdMetaDataBinding& bind, PsPvd* pvd, PxScene& scene) : mStream(str), mBinding(bind), mPvd(pvd), mScene(scene) { } template <typename TDataType> void operator()(const TDataType& dtype) { mBinding.createInstance(mStream, dtype, mScene, PxGetPhysics(), mPvd); } void operator()(const PxArticulationLink&) { } }; struct UpdateOp { UpdateOp& operator=(const UpdateOp&); physx::pvdsdk::PvdDataStream& mStream; PvdMetaDataBinding& mBinding; UpdateOp(physx::pvdsdk::PvdDataStream& str, PvdMetaDataBinding& bind) : mStream(str), mBinding(bind) { } template <typename TDataType> void operator()(const TDataType& dtype) { mBinding.sendAllProperties(mStream, dtype); } }; struct DestroyOp { DestroyOp& operator=(const DestroyOp&); physx::pvdsdk::PvdDataStream& mStream; PvdMetaDataBinding& mBinding; PxScene& mScene; DestroyOp(physx::pvdsdk::PvdDataStream& str, PvdMetaDataBinding& bind, PxScene& scene) : mStream(str), mBinding(bind), mScene(scene) { } template <typename TDataType> void operator()(const TDataType& dtype) { mBinding.destroyInstance(mStream, dtype, mScene); } void operator()(const PxArticulationLink& dtype) { mBinding.destroyInstance(mStream, dtype); } }; template <typename TOperator> inline void BodyTypeOperation(const NpActor* scBody, TOperator op) { // const bool isArticulationLink = scBody->getActorType_() == PxActorType::eARTICULATION_LINK; const bool isArticulationLink = scBody->getNpType() == NpType::eBODY_FROM_ARTICULATION_LINK; if(isArticulationLink) { const NpArticulationLink* link = static_cast<const NpArticulationLink*>(scBody); op(*static_cast<const PxArticulationLink*>(link)); } else { const NpRigidDynamic* npRigidDynamic = static_cast<const NpRigidDynamic*>(scBody); op(*static_cast<const PxRigidDynamic*>(npRigidDynamic)); } } template <typename TOperator> inline void ActorTypeOperation(const PxActor* actor, TOperator op) { switch(actor->getType()) { case PxActorType::eRIGID_STATIC: op(*static_cast<const PxRigidStatic*>(actor)); break; case PxActorType::eRIGID_DYNAMIC: op(*static_cast<const PxRigidDynamic*>(actor)); break; case PxActorType::eARTICULATION_LINK: op(*static_cast<const PxArticulationLink*>(actor)); break; case PxActorType::eSOFTBODY: #if PX_SUPPORT_GPU_PHYSX op(*static_cast<const PxSoftBody*>(actor)); #endif break; case PxActorType::eFEMCLOTH: //op(*static_cast<const PxFEMCloth*>(actor)); break; case PxActorType::ePBD_PARTICLESYSTEM: op(*static_cast<const PxPBDParticleSystem*>(actor)); break; case PxActorType::eFLIP_PARTICLESYSTEM: //op(*static_cast<const PxFLIPParticleSystem*>(actor)); break; case PxActorType::eMPM_PARTICLESYSTEM: //op(*static_cast<const PxMPMParticleSystem*>(actor)); break; case PxActorType::eHAIRSYSTEM: //op(*static_cast<const PxHairSystem*>(actor)); break; case PxActorType::eACTOR_COUNT: case PxActorType::eACTOR_FORCE_DWORD: PX_ASSERT(false); break; }; } namespace { struct PvdConstraintVisualizer : public PxConstraintVisualizer { PX_NOCOPY(PvdConstraintVisualizer) public: physx::pvdsdk::PvdUserRenderer& mRenderer; PvdConstraintVisualizer(const void* id, physx::pvdsdk::PvdUserRenderer& r) : mRenderer(r) { mRenderer.setInstanceId(id); } virtual void visualizeJointFrames(const PxTransform& parent, const PxTransform& child) PX_OVERRIDE { mRenderer.visualizeJointFrames(parent, child); } virtual void visualizeLinearLimit(const PxTransform& t0, const PxTransform& t1, PxReal value) PX_OVERRIDE { mRenderer.visualizeLinearLimit(t0, t1, PxF32(value)); } virtual void visualizeAngularLimit(const PxTransform& t0, PxReal lower, PxReal upper) PX_OVERRIDE { mRenderer.visualizeAngularLimit(t0, PxF32(lower), PxF32(upper)); } virtual void visualizeLimitCone(const PxTransform& t, PxReal tanQSwingY, PxReal tanQSwingZ) PX_OVERRIDE { mRenderer.visualizeLimitCone(t, PxF32(tanQSwingY), PxF32(tanQSwingZ)); } virtual void visualizeDoubleCone(const PxTransform& t, PxReal angle) PX_OVERRIDE { mRenderer.visualizeDoubleCone(t, PxF32(angle)); } virtual void visualizeLine( const PxVec3& p0, const PxVec3& p1, PxU32 color) PX_OVERRIDE { const PxDebugLine line(p0, p1, color); mRenderer.drawLines(&line, 1); } }; } class SceneRendererClient : public RendererEventClient, public physx::PxUserAllocated { PX_NOCOPY(SceneRendererClient) public: SceneRendererClient(PvdUserRenderer* renderer, PxPvd* pvd):mRenderer(renderer) { mStream = PvdDataStream::create(pvd); mStream->createInstance(renderer); } ~SceneRendererClient() { mStream->destroyInstance(mRenderer); mStream->release(); } virtual void handleBufferFlush(const uint8_t* inData, uint32_t inLength) { mStream->setPropertyValue(mRenderer, "events", inData, inLength); } private: PvdUserRenderer* mRenderer; PvdDataStream* mStream; }; } // namespace PvdSceneClient::PvdSceneClient(NpScene& scene) : mPvd (NULL), mScene (scene), mPvdDataStream (NULL), mUserRender (NULL), mRenderClient (NULL), mIsConnected (false) { } PvdSceneClient::~PvdSceneClient() { if(mPvd) mPvd->removeClient(this); } void PvdSceneClient::updateCamera(const char* name, const PxVec3& origin, const PxVec3& up, const PxVec3& target) { if(mIsConnected) mPvdDataStream->updateCamera(name, origin, up, target); } void PvdSceneClient::drawPoints(const PxDebugPoint* points, PxU32 count) { if(mUserRender) mUserRender->drawPoints(points, count); } void PvdSceneClient::drawLines(const PxDebugLine* lines, PxU32 count) { if(mUserRender) mUserRender->drawLines(lines, count); } void PvdSceneClient::drawTriangles(const PxDebugTriangle* triangles, PxU32 count) { if(mUserRender) mUserRender->drawTriangles(triangles, count); } void PvdSceneClient::drawText(const PxDebugText& text) { if(mUserRender) mUserRender->drawText(text); } void PvdSceneClient::setScenePvdFlag(PxPvdSceneFlag::Enum flag, bool value) { if(value) mFlags |= flag; else mFlags &= ~flag; } void PvdSceneClient::onPvdConnected() { if(mIsConnected || !mPvd) return; mIsConnected = true; mPvdDataStream = PvdDataStream::create(mPvd); mUserRender = PvdUserRenderer::create(); mRenderClient = PX_NEW(SceneRendererClient)(mUserRender, mPvd); mUserRender->setClient(mRenderClient); sendEntireScene(); } void PvdSceneClient::onPvdDisconnected() { if(!mIsConnected) return; mIsConnected = false; PX_DELETE(mRenderClient); mUserRender->release(); mUserRender = NULL; mPvdDataStream->release(); mPvdDataStream = NULL; } void PvdSceneClient::updatePvdProperties() { mMetaDataBinding.sendAllProperties(*mPvdDataStream, mScene); } void PvdSceneClient::releasePvdInstance() { if(mPvdDataStream) { PxScene* theScene = &mScene; // remove from parent mPvdDataStream->removeObjectRef(&PxGetPhysics(), "Scenes", theScene); mPvdDataStream->destroyInstance(theScene); } } // PT: this is only called once, from "onPvdConnected" void PvdSceneClient::sendEntireScene() { NpScene* npScene = &mScene; if(npScene->getFlagsFast() & PxSceneFlag::eREQUIRE_RW_LOCK) // getFlagsFast() will trigger a warning of lock check npScene->lockRead(PX_FL); PxPhysics& physics = PxGetPhysics(); { PxScene* theScene = &mScene; mPvdDataStream->createInstance(theScene); updatePvdProperties(); // Create parent/child relationship. mPvdDataStream->setPropertyValue(theScene, "Physics", reinterpret_cast<const void*>(&physics)); mPvdDataStream->pushBackObjectRef(&physics, "Scenes", theScene); } // materials: { PxsMaterialManager& manager = mScene.getScScene().getMaterialManager(); PxsMaterialManagerIterator<PxsMaterialCore> iter(manager); PxsMaterialCore* mat; while(iter.getNextMaterial(mat)) { const PxMaterial* theMaterial = mat->mMaterial; if(mPvd->registerObject(theMaterial)) mMetaDataBinding.createInstance(*mPvdDataStream, *theMaterial, physics); }; } if(mPvd->getInstrumentationFlags() & PxPvdInstrumentationFlag::eDEBUG) { PxArray<PxActor*> actorArray; // RBs // static: { PxU32 numActors = npScene->getNbActors(PxActorTypeFlag::eRIGID_STATIC | PxActorTypeFlag::eRIGID_DYNAMIC); actorArray.resize(numActors); npScene->getActors(PxActorTypeFlag::eRIGID_STATIC | PxActorTypeFlag::eRIGID_DYNAMIC, actorArray.begin(), actorArray.size()); for(PxU32 i = 0; i < numActors; i++) { PxActor* pxActor = actorArray[i]; if(pxActor->getConcreteType()==PxConcreteType::eRIGID_STATIC) mMetaDataBinding.createInstance(*mPvdDataStream, *static_cast<PxRigidStatic*>(pxActor), *npScene, physics, mPvd); else mMetaDataBinding.createInstance(*mPvdDataStream, *static_cast<PxRigidDynamic*>(pxActor), *npScene, physics, mPvd); } } // articulations & links { PxArray<PxArticulationReducedCoordinate*> articulations; PxU32 numArticulations = npScene->getNbArticulations(); articulations.resize(numArticulations); npScene->getArticulations(articulations.begin(), articulations.size()); for(PxU32 i = 0; i < numArticulations; i++) mMetaDataBinding.createInstance(*mPvdDataStream, *articulations[i], *npScene, physics, mPvd); } // joints { Sc::ConstraintCore*const * constraints = mScene.getScScene().getConstraints(); PxU32 nbConstraints = mScene.getScScene().getNbConstraints(); for(PxU32 i = 0; i < nbConstraints; i++) { updateConstraint(*constraints[i], PxPvdUpdateType::CREATE_INSTANCE); updateConstraint(*constraints[i], PxPvdUpdateType::UPDATE_ALL_PROPERTIES); } } } if(npScene->getFlagsFast() & PxSceneFlag::eREQUIRE_RW_LOCK) npScene->unlockRead(); } void PvdSceneClient::updateConstraint(const Sc::ConstraintCore& scConstraint, PxU32 updateType) { PxConstraintConnector* conn = scConstraint.getPxConnector(); if(conn && checkPvdDebugFlag()) conn->updatePvdProperties(*mPvdDataStream, scConstraint.getPxConstraint(), PxPvdUpdateType::Enum(updateType)); } void PvdSceneClient::createPvdInstance(const PxActor* actor) { if(checkPvdDebugFlag()) ActorTypeOperation(actor, CreateOp(*mPvdDataStream, mMetaDataBinding, mPvd, mScene)); } void PvdSceneClient::updatePvdProperties(const PxActor* actor) { if(checkPvdDebugFlag()) ActorTypeOperation(actor, UpdateOp(*mPvdDataStream, mMetaDataBinding)); } void PvdSceneClient::releasePvdInstance(const PxActor* actor) { if(checkPvdDebugFlag()) ActorTypeOperation(actor, DestroyOp(*mPvdDataStream, mMetaDataBinding, mScene)); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpActor* actor) { // PT: why not UPDATE_PVD_PROPERTIES_CHECK() here? createPvdInstance(getPxActor(actor)); } void PvdSceneClient::updatePvdProperties(const NpActor* actor) { // PT: why not UPDATE_PVD_PROPERTIES_CHECK() here? updatePvdProperties(getPxActor(actor)); } void PvdSceneClient::releasePvdInstance(const NpActor* actor) { // PT: why not UPDATE_PVD_PROPERTIES_CHECK() here? releasePvdInstance(getPxActor(actor)); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpRigidDynamic* body) { if(checkPvdDebugFlag() && body->getNpType() != NpType::eBODY_FROM_ARTICULATION_LINK) BodyTypeOperation(body, CreateOp(*mPvdDataStream, mMetaDataBinding, mPvd, mScene)); } void PvdSceneClient::createPvdInstance(const NpArticulationLink* body) { if(checkPvdDebugFlag() && body->getNpType() != NpType::eBODY_FROM_ARTICULATION_LINK) BodyTypeOperation(body, CreateOp(*mPvdDataStream, mMetaDataBinding, mPvd, mScene)); } void PvdSceneClient::releasePvdInstance(const NpRigidDynamic* body) { releasePvdInstance(getPxActor(body)); } void PvdSceneClient::releasePvdInstance(const NpArticulationLink* body) { releasePvdInstance(getPxActor(body)); } void PvdSceneClient::updateBodyPvdProperties(const NpActor* body) { if(checkPvdDebugFlag()) { if(body->getNpType() == NpType::eBODY_FROM_ARTICULATION_LINK) updatePvdProperties(static_cast<const NpArticulationLink*>(body)); else if(body->getNpType() == NpType::eBODY) updatePvdProperties(static_cast<const NpRigidDynamic*>(body)); else PX_ASSERT(0); } } void PvdSceneClient::updatePvdProperties(const NpRigidDynamic* body) { if(checkPvdDebugFlag()) BodyTypeOperation(body, UpdateOp(*mPvdDataStream, mMetaDataBinding)); } void PvdSceneClient::updatePvdProperties(const NpArticulationLink* body) { if(checkPvdDebugFlag()) BodyTypeOperation(body, UpdateOp(*mPvdDataStream, mMetaDataBinding)); } void PvdSceneClient::updateKinematicTarget(const NpActor* body, const PxTransform& p) { if(checkPvdDebugFlag()) { if(body->getNpType() == NpType::eBODY_FROM_ARTICULATION_LINK) mPvdDataStream->setPropertyValue(static_cast<const NpArticulationLink*>(body), "KinematicTarget", p); else if(body->getNpType() == NpType::eBODY) mPvdDataStream->setPropertyValue(static_cast<const NpRigidDynamic*>(body), "KinematicTarget", p); else PX_ASSERT(0); } } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::releasePvdInstance(const NpRigidStatic* rigidStatic) { releasePvdInstance(static_cast<const NpActor*>(rigidStatic)); } void PvdSceneClient::createPvdInstance(const NpRigidStatic* rigidStatic) { if(checkPvdDebugFlag()) mMetaDataBinding.createInstance(*mPvdDataStream, *rigidStatic, mScene, PxGetPhysics(), mPvd); } void PvdSceneClient::updatePvdProperties(const NpRigidStatic* rigidStatic) { if(checkPvdDebugFlag()) mMetaDataBinding.sendAllProperties(*mPvdDataStream, *rigidStatic); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpConstraint* constraint) { if(checkPvdDebugFlag()) updateConstraint(constraint->getCore(), PxPvdUpdateType::CREATE_INSTANCE); } void PvdSceneClient::updatePvdProperties(const NpConstraint* constraint) { if(checkPvdDebugFlag()) updateConstraint(constraint->getCore(), PxPvdUpdateType::UPDATE_ALL_PROPERTIES); } void PvdSceneClient::releasePvdInstance(const NpConstraint* constraint) { const Sc::ConstraintCore& scConstraint = constraint->getCore(); PxConstraintConnector* conn; if(checkPvdDebugFlag() && (conn = scConstraint.getPxConnector()) != NULL) conn->updatePvdProperties(*mPvdDataStream, scConstraint.getPxConstraint(), PxPvdUpdateType::RELEASE_INSTANCE); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpArticulationReducedCoordinate* articulation) { if (checkPvdDebugFlag()) { mMetaDataBinding.createInstance(*mPvdDataStream, *articulation, mScene, PxGetPhysics(), mPvd); } } void PvdSceneClient::updatePvdProperties(const NpArticulationReducedCoordinate* articulation) { if(checkPvdDebugFlag()) { mMetaDataBinding.sendAllProperties(*mPvdDataStream, *articulation); } } void PvdSceneClient::releasePvdInstance(const NpArticulationReducedCoordinate* articulation) { if (checkPvdDebugFlag()) { mMetaDataBinding.destroyInstance(*mPvdDataStream, *articulation, mScene); } } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpArticulationJointReducedCoordinate* articulationJoint) { PX_UNUSED(articulationJoint); } void PvdSceneClient::updatePvdProperties(const NpArticulationJointReducedCoordinate* articulationJoint) { if (checkPvdDebugFlag()) { mMetaDataBinding.sendAllProperties(*mPvdDataStream, *articulationJoint); } } void PvdSceneClient::releasePvdInstance(const NpArticulationJointReducedCoordinate* articulationJoint) { PX_UNUSED(articulationJoint); } ///////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpArticulationSpatialTendon* articulationTendon) { PX_UNUSED(articulationTendon); } void PvdSceneClient::updatePvdProperties(const NpArticulationSpatialTendon* articulationTendon) { PX_UNUSED(articulationTendon); } void PvdSceneClient::releasePvdInstance(const NpArticulationSpatialTendon* articulationTendon) { PX_UNUSED(articulationTendon); } ///////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpArticulationFixedTendon* articulationTendon) { PX_UNUSED(articulationTendon); } void PvdSceneClient::updatePvdProperties(const NpArticulationFixedTendon* articulationTendon) { PX_UNUSED(articulationTendon); } void PvdSceneClient::releasePvdInstance(const NpArticulationFixedTendon* articulationTendon) { PX_UNUSED(articulationTendon); } ///////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpArticulationSensor* sensor) { PX_UNUSED(sensor); } void PvdSceneClient::updatePvdProperties(const NpArticulationSensor* sensor) { PX_UNUSED(sensor); } void PvdSceneClient::releasePvdInstance(const NpArticulationSensor* sensor) { PX_UNUSED(sensor); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const PxsMaterialCore* materialCore) { if(checkPvdDebugFlag()) { const PxMaterial* theMaterial = materialCore->mMaterial; if(mPvd->registerObject(theMaterial)) mMetaDataBinding.createInstance(*mPvdDataStream, *theMaterial, PxGetPhysics()); } } void PvdSceneClient::updatePvdProperties(const PxsMaterialCore* materialCore) { if(checkPvdDebugFlag()) mMetaDataBinding.sendAllProperties(*mPvdDataStream, *materialCore->mMaterial); } void PvdSceneClient::releasePvdInstance(const PxsMaterialCore* materialCore) { if(checkPvdDebugFlag() && mPvd->unRegisterObject(materialCore->mMaterial)) mMetaDataBinding.destroyInstance(*mPvdDataStream, *materialCore->mMaterial, PxGetPhysics()); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const PxsFEMSoftBodyMaterialCore* materialCore) { if (checkPvdDebugFlag()) { const PxFEMSoftBodyMaterial* theMaterial = materialCore->mMaterial; if (mPvd->registerObject(theMaterial)) mMetaDataBinding.createInstance(*mPvdDataStream, *theMaterial, PxGetPhysics()); } } void PvdSceneClient::updatePvdProperties(const PxsFEMSoftBodyMaterialCore* materialCore) { if (checkPvdDebugFlag()) mMetaDataBinding.sendAllProperties(*mPvdDataStream, *materialCore->mMaterial); } void PvdSceneClient::releasePvdInstance(const PxsFEMSoftBodyMaterialCore* materialCore) { if (checkPvdDebugFlag() && mPvd->unRegisterObject(materialCore->mMaterial)) mMetaDataBinding.destroyInstance(*mPvdDataStream, *materialCore->mMaterial, PxGetPhysics()); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const PxsFEMClothMaterialCore*) { // no PVD support but method is "needed" since macro code is shared among all material types } void PvdSceneClient::updatePvdProperties(const PxsFEMClothMaterialCore*) { // no PVD support but method is "needed" since macro code is shared among all material types } void PvdSceneClient::releasePvdInstance(const PxsFEMClothMaterialCore*) { // no PVD support but method is "needed" since macro code is shared among all material types } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const PxsPBDMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::updatePvdProperties(const PxsPBDMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::releasePvdInstance(const PxsPBDMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::createPvdInstance(const PxsFLIPMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::updatePvdProperties(const PxsFLIPMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::releasePvdInstance(const PxsFLIPMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::createPvdInstance(const PxsMPMMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::updatePvdProperties(const PxsMPMMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } void PvdSceneClient::releasePvdInstance(const PxsMPMMaterialCore* /*materialCore*/) { // PX_ASSERT(0); } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpShape* npShape, PxActor& owner) { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.createPVDInstance", getContextId(mScene)); mMetaDataBinding.createInstance(*mPvdDataStream, *npShape, static_cast<PxRigidActor&>(owner), PxGetPhysics(), mPvd); } } static void addShapesToPvd(PxU32 nbShapes, NpShape* const* shapes, PxActor& pxActor, PsPvd* pvd, PvdDataStream& stream, PvdMetaDataBinding& binding) { PxPhysics& physics = PxGetPhysics(); for(PxU32 i=0;i<nbShapes;i++) { const NpShape* npShape = shapes[i]; binding.createInstance(stream, *npShape, static_cast<PxRigidActor&>(pxActor), physics, pvd); } } void PvdSceneClient::addBodyAndShapesToPvd(NpRigidDynamic& b) { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.createPVDInstance", getContextId(mScene)); createPvdInstance(&b); PxActor& pxActor = *b.getCore().getPxActor(); NpShape* const* shapes; const PxU32 nbShapes = NpRigidDynamicGetShapes(b, shapes); addShapesToPvd(nbShapes, shapes, pxActor, mPvd, *mPvdDataStream, mMetaDataBinding); } } void PvdSceneClient::addStaticAndShapesToPvd(NpRigidStatic& s) { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.createPVDInstance", getContextId(mScene)); createPvdInstance(&s); PxActor& pxActor = static_cast<PxRigidStatic&>(s); NpShape* const* shapes; const PxU32 nbShapes = NpRigidStaticGetShapes(s, shapes); addShapesToPvd(nbShapes, shapes, pxActor, mPvd, *mPvdDataStream, mMetaDataBinding); } } void PvdSceneClient::updateMaterials(const NpShape* npShape) { if(checkPvdDebugFlag()) mMetaDataBinding.updateMaterials(*mPvdDataStream, *npShape, mPvd); } void PvdSceneClient::updatePvdProperties(const NpShape* npShape) { if(checkPvdDebugFlag()) mMetaDataBinding.sendAllProperties(*mPvdDataStream, *npShape); } void PvdSceneClient::releaseAndRecreateGeometry(const NpShape* npShape) { if(checkPvdDebugFlag()) mMetaDataBinding.releaseAndRecreateGeometry(*mPvdDataStream, *npShape, NpPhysics::getInstance(), mPvd); } void PvdSceneClient::releasePvdInstance(const NpShape* npShape, PxActor& owner) { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.releasePVDInstance", getContextId(mScene)); mMetaDataBinding.destroyInstance(*mPvdDataStream, *npShape, static_cast<PxRigidActor&>(owner)); const PxU32 numMaterials = npShape->getNbMaterials(); PX_ALLOCA(materialPtr, PxMaterial*, numMaterials); npShape->getMaterials(materialPtr, numMaterials); for(PxU32 idx = 0; idx < numMaterials; ++idx) releasePvdInstance(&(static_cast<NpMaterial*>(materialPtr[idx])->mMaterial)); } } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::originShift(PxVec3 shift) { mMetaDataBinding.originShift(*mPvdDataStream, &mScene, shift); } void PvdSceneClient::frameStart(PxReal simulateElapsedTime) { PX_PROFILE_ZONE("Basic.pvdFrameStart", mScene.getScScene().getContextId()); if(!mIsConnected) return; mPvdDataStream->flushPvdCommand(); mMetaDataBinding.sendBeginFrame(*mPvdDataStream, &mScene, simulateElapsedTime); } void PvdSceneClient::frameEnd() { PX_PROFILE_ZONE("Basic.pvdFrameEnd", mScene.getScScene().getContextId()); if(!mIsConnected) { if(mPvd) mPvd->flush(); // Even if we aren't connected, we may need to flush buffered events. return; } PxScene* theScene = &mScene; mMetaDataBinding.sendStats(*mPvdDataStream, theScene); // flush our data to the main connection mPvd->flush(); // End the frame *before* we send the dynamic object current data. // This ensures that contacts end up synced with the rest of the system. // Note that contacts were sent much earler in NpScene::fetchResults. mMetaDataBinding.sendEndFrame(*mPvdDataStream, &mScene); if(mPvd->getInstrumentationFlags() & PxPvdInstrumentationFlag::eDEBUG) { PX_PROFILE_ZONE("PVD.sceneUpdate", getContextId(mScene)); PvdVisualizer* vizualizer = NULL; const bool visualizeJoints = getScenePvdFlagsFast() & PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS; if(visualizeJoints) vizualizer = this; mMetaDataBinding.updateDynamicActorsAndArticulations(*mPvdDataStream, theScene, vizualizer); } // frame end moved to update contacts to have them in the previous frame. } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpAggregate* npAggregate) { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.createPVDInstance", getContextId(mScene)); mMetaDataBinding.createInstance(*mPvdDataStream, *npAggregate, mScene); } } void PvdSceneClient::updatePvdProperties(const NpAggregate* npAggregate) { if(checkPvdDebugFlag()) mMetaDataBinding.sendAllProperties(*mPvdDataStream, *npAggregate); } void PvdSceneClient::attachAggregateActor(const NpAggregate* npAggregate, NpActor* actor) { if(checkPvdDebugFlag()) mMetaDataBinding.attachAggregateActor(*mPvdDataStream, *npAggregate, *getPxActor(actor)); } void PvdSceneClient::detachAggregateActor(const NpAggregate* npAggregate, NpActor* actor) { if(checkPvdDebugFlag()) mMetaDataBinding.detachAggregateActor(*mPvdDataStream, *npAggregate, *getPxActor(actor)); } void PvdSceneClient::releasePvdInstance(const NpAggregate* npAggregate) { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.releasePVDInstance", getContextId(mScene)); mMetaDataBinding.destroyInstance(*mPvdDataStream, *npAggregate, mScene); } } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX void PvdSceneClient::createPvdInstance(const NpSoftBody* softBody) { PX_UNUSED(softBody); //Todo } void PvdSceneClient::updatePvdProperties(const NpSoftBody* softBody) { PX_UNUSED(softBody); //Todo } void PvdSceneClient::attachAggregateActor(const NpSoftBody* softBody, NpActor* actor) { PX_UNUSED(softBody); PX_UNUSED(actor); //Todo } void PvdSceneClient::detachAggregateActor(const NpSoftBody* softBody, NpActor* actor) { PX_UNUSED(softBody); PX_UNUSED(actor); //Todo } void PvdSceneClient::releasePvdInstance(const NpSoftBody* softBody) { PX_UNUSED(softBody); //Todo } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpFEMCloth* femCloth) { PX_UNUSED(femCloth); //Todo } void PvdSceneClient::updatePvdProperties(const NpFEMCloth* femCloth) { PX_UNUSED(femCloth); //Todo } void PvdSceneClient::attachAggregateActor(const NpFEMCloth* femCloth, NpActor* actor) { PX_UNUSED(femCloth); PX_UNUSED(actor); //Todo } void PvdSceneClient::detachAggregateActor(const NpFEMCloth* femCloth, NpActor* actor) { PX_UNUSED(femCloth); PX_UNUSED(actor); //Todo } void PvdSceneClient::releasePvdInstance(const NpFEMCloth* femCloth) { PX_UNUSED(femCloth); //Todo } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpPBDParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } void PvdSceneClient::updatePvdProperties(const NpPBDParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } void PvdSceneClient::attachAggregateActor(const NpPBDParticleSystem* particleSystem, NpActor* actor) { PX_UNUSED(particleSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::detachAggregateActor(const NpPBDParticleSystem* particleSystem, NpActor* actor) { PX_UNUSED(particleSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::releasePvdInstance(const NpPBDParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpFLIPParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } void PvdSceneClient::updatePvdProperties(const NpFLIPParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } void PvdSceneClient::attachAggregateActor(const NpFLIPParticleSystem* particleSystem, NpActor* actor) { PX_UNUSED(particleSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::detachAggregateActor(const NpFLIPParticleSystem* particleSystem, NpActor* actor) { PX_UNUSED(particleSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::releasePvdInstance(const NpFLIPParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpMPMParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } void PvdSceneClient::updatePvdProperties(const NpMPMParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } void PvdSceneClient::attachAggregateActor(const NpMPMParticleSystem* particleSystem, NpActor* actor) { PX_UNUSED(particleSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::detachAggregateActor(const NpMPMParticleSystem* particleSystem, NpActor* actor) { PX_UNUSED(particleSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::releasePvdInstance(const NpMPMParticleSystem* particleSystem) { PX_UNUSED(particleSystem); //Todo } /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::createPvdInstance(const NpHairSystem* hairSystem) { PX_UNUSED(hairSystem); //Todo } void PvdSceneClient::updatePvdProperties(const NpHairSystem* hairSystem) { PX_UNUSED(hairSystem); //Todo } void PvdSceneClient::attachAggregateActor(const NpHairSystem* hairSystem, NpActor* actor) { PX_UNUSED(hairSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::detachAggregateActor(const NpHairSystem* hairSystem, NpActor* actor) { PX_UNUSED(hairSystem); PX_UNUSED(actor); //Todo } void PvdSceneClient::releasePvdInstance(const NpHairSystem* hairSystem) { PX_UNUSED(hairSystem); //Todo } #endif /////////////////////////////////////////////////////////////////////////////// void PvdSceneClient::updateJoints() { if(checkPvdDebugFlag()) { PX_PROFILE_ZONE("PVD.updateJoints", getContextId(mScene)); const bool visualizeJoints = getScenePvdFlagsFast() & PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS; Sc::ConstraintCore*const * constraints = mScene.getScScene().getConstraints(); const PxU32 nbConstraints = mScene.getScScene().getNbConstraints(); PxI64 constraintCount = 0; for(PxU32 i=0; i<nbConstraints; i++) { Sc::ConstraintCore* constraint = constraints[i]; PxPvdUpdateType::Enum updateType = getNpConstraint(constraint)->isDirty() ? PxPvdUpdateType::UPDATE_ALL_PROPERTIES : PxPvdUpdateType::UPDATE_SIM_PROPERTIES; updateConstraint(*constraint, updateType); PxConstraintConnector* conn = constraint->getPxConnector(); // visualization is updated here { PxU32 typeId = 0; void* joint = NULL; if(conn) joint = conn->getExternalReference(typeId); // visualize: Sc::ConstraintSim* sim = constraint->getSim(); if(visualizeJoints && sim && sim->getConstantsLL() && joint && constraint->getVisualize()) { Sc::BodySim* b0 = sim->getBody(0); Sc::BodySim* b1 = sim->getBody(1); PxTransform t0 = b0 ? b0->getBody2World() : PxTransform(PxIdentity); PxTransform t1 = b1 ? b1->getBody2World() : PxTransform(PxIdentity); PvdConstraintVisualizer viz(joint, *mUserRender); (*constraint->getVisualize())(viz, sim->getConstantsLL(), t0, t1, 0xffffFFFF); } } ++constraintCount; } mUserRender->flushRenderEvents(); } } void PvdSceneClient::updateContacts() { if(!checkPvdDebugFlag()) return; PX_PROFILE_ZONE("PVD.updateContacts", getContextId(mScene)); // if contacts are disabled, send empty array and return const PxScene* theScene = &mScene; if(!(getScenePvdFlagsFast() & PxPvdSceneFlag::eTRANSMIT_CONTACTS)) { mMetaDataBinding.sendContacts(*mPvdDataStream, *theScene); return; } PxsContactManagerOutputIterator outputIter; Sc::ContactIterator contactIter; mScene.getScScene().initContactsIterator(contactIter, outputIter); Sc::ContactIterator::Pair* pair; Sc::Contact* contact; PxArray<Sc::Contact> contacts; while ((pair = contactIter.getNextPair()) != NULL) { while ((contact = pair->getNextContact()) != NULL) contacts.pushBack(*contact); } mMetaDataBinding.sendContacts(*mPvdDataStream, *theScene, contacts); } void PvdSceneClient::updateSceneQueries() { if(checkPvdDebugFlag() && (getScenePvdFlagsFast() & PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES)) mMetaDataBinding.sendSceneQueries(*mPvdDataStream, mScene, mPvd); } void PvdSceneClient::visualize(PxArticulationLink& link) { #if PX_ENABLE_DEBUG_VISUALIZATION NpArticulationLink& npLink = static_cast<NpArticulationLink&>(link); const void* itemId = npLink.getInboundJoint(); if(itemId && mUserRender) { PvdConstraintVisualizer viz(itemId, *mUserRender); npLink.visualizeJoint(viz); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION PX_UNUSED(link); #endif } void PvdSceneClient::visualize(const PxRenderBuffer& debugRenderable) { if(mUserRender) { // PT: I think the mUserRender object can contain extra data (including things coming from the user), because the various // draw functions are exposed e.g. in PxPvdSceneClient.h. So I suppose we have to keep the render buffer around regardless // of the connection flags. Thus I only skip the "drawRenderbuffer" call, for minimal intrusion into this file. if(checkPvdDebugFlag()) { mUserRender->drawRenderbuffer( reinterpret_cast<const PxDebugPoint*>(debugRenderable.getPoints()), debugRenderable.getNbPoints(), reinterpret_cast<const PxDebugLine*>(debugRenderable.getLines()), debugRenderable.getNbLines(), reinterpret_cast<const PxDebugTriangle*>(debugRenderable.getTriangles()), debugRenderable.getNbTriangles()); } mUserRender->flushRenderEvents(); } } #endif
37,936
C++
28.115119
158
0.721926
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationSensor.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PxArticulationReducedCoordinate.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxMemory.h" #include "ScArticulationSensor.h" #include "NpBase.h" #ifndef NP_ARTICULATION_SENSOR_H #define NP_ARTICULATION_SENSOR_H namespace physx { typedef PxU32 ArticulationSensorHandle; class NpArticulationSensor : public PxArticulationSensor, public NpBase { public: // PX_SERIALIZATION NpArticulationSensor(PxBaseFlags baseFlags) : PxArticulationSensor(baseFlags), NpBase(PxEmpty), mCore(PxEmpty) {} void preExportDataReset() {} virtual void exportExtraData(PxSerializationContext& ) {} void importExtraData(PxDeserializationContext& ) {} void resolveReferences(PxDeserializationContext& ); virtual void requiresObjects(PxProcessPxBaseCallback&) {} virtual bool isSubordinate() const { return true; } static NpArticulationSensor* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationSensor(PxArticulationLink* link, const PxTransform& relativePose); virtual ~NpArticulationSensor() {} virtual void release(); virtual PxSpatialForce getForces() const; virtual PxTransform getRelativePose() const; virtual void setRelativePose(const PxTransform&); virtual PxArticulationLink* getLink() const; virtual PxU32 getIndex() const; virtual PxArticulationReducedCoordinate* getArticulation() const; virtual PxArticulationSensorFlags getFlags() const; virtual void setFlag(PxArticulationSensorFlag::Enum flag, bool enabled); PX_FORCE_INLINE Sc::ArticulationSensorCore& getSensorCore() { return mCore; } PX_FORCE_INLINE const Sc::ArticulationSensorCore& getSensorCore() const { return mCore; } PX_FORCE_INLINE ArticulationSensorHandle getHandle() { return mHandle; } PX_FORCE_INLINE void setHandle(ArticulationSensorHandle handle) { mHandle = handle; } private: PxArticulationLink* mLink; Sc::ArticulationSensorCore mCore; ArticulationSensorHandle mHandle; }; } #endif //NP_ARTICULATION_SENSOR_H
3,817
C
43.395348
96
0.771024
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdPhysicsClient.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 PVD_PHYSICS_CLIENT_H #define PVD_PHYSICS_CLIENT_H #if PX_SUPPORT_PVD #include "foundation/PxErrorCallback.h" #include "foundation/PxHashMap.h" #include "PxPvdClient.h" #include "PvdMetaDataPvdBinding.h" #include "NpFactory.h" #include "foundation/PxMutex.h" #include "PsPvd.h" namespace physx { class PxProfileMemoryEventBuffer; namespace Vd { class PvdPhysicsClient : public PvdClient, public PxErrorCallback, public NpFactoryListener, public PxUserAllocated { PX_NOCOPY(PvdPhysicsClient) public: PvdPhysicsClient(PsPvd* pvd); virtual ~PvdPhysicsClient(); bool isConnected() const; void onPvdConnected(); void onPvdDisconnected(); void flush(); physx::pvdsdk::PvdDataStream* getDataStream(); void sendEntireSDK(); void destroyPvdInstance(const PxPhysics* physics); // NpFactoryListener virtual void onMeshFactoryBufferRelease(const PxBase* object, PxType typeID); /// NpFactoryListener // PxErrorCallback void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line); private: void createPvdInstance(const PxTriangleMesh* triMesh); void destroyPvdInstance(const PxTriangleMesh* triMesh); void createPvdInstance(const PxTetrahedronMesh* tetMesh); void destroyPvdInstance(const PxTetrahedronMesh* tetMesh); void createPvdInstance(const PxConvexMesh* convexMesh); void destroyPvdInstance(const PxConvexMesh* convexMesh); void createPvdInstance(const PxHeightField* heightField); void destroyPvdInstance(const PxHeightField* heightField); void createPvdInstance(const PxMaterial* mat); void destroyPvdInstance(const PxMaterial* mat); void updatePvdProperties(const PxMaterial* mat); void createPvdInstance(const PxFEMSoftBodyMaterial* mat); void destroyPvdInstance(const PxFEMSoftBodyMaterial* mat); void updatePvdProperties(const PxFEMSoftBodyMaterial* mat); void createPvdInstance(const PxFEMClothMaterial* mat); void destroyPvdInstance(const PxFEMClothMaterial* mat); void updatePvdProperties(const PxFEMClothMaterial* mat); void createPvdInstance(const PxPBDMaterial* mat); void destroyPvdInstance(const PxPBDMaterial* mat); void updatePvdProperties(const PxPBDMaterial* mat); PsPvd* mPvd; PvdDataStream* mPvdDataStream; PvdMetaDataBinding mMetaDataBinding; bool mIsConnected; }; } // namespace Vd } // namespace physx #endif // PX_SUPPORT_PVD #endif // PVD_PHYSICS_CLIENT_H
4,071
C
37.056074
115
0.787276
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMCloth.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "NpFEMCloth.h" #include "NpCheck.h" #include "NpScene.h" #include "NpShape.h" #include "geometry/PxTriangleMesh.h" #include "geometry/PxTriangleMeshGeometry.h" #include "PxPhysXGpu.h" #include "PxvGlobals.h" #include "GuTriangleMesh.h" #include "NpRigidDynamic.h" #include "NpRigidStatic.h" #include "NpArticulationLink.h" #include "GuTriangleMesh.h" #include "ScFEMClothSim.h" using namespace physx; namespace physx { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFEMCloth::NpFEMCloth(PxCudaContextManager& cudaContextManager) : NpActorTemplate(PxConcreteType::eFEM_CLOTH, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, NpType::eFEMCLOTH), mShape(NULL), mCudaContextManager(&cudaContextManager) { } NpFEMCloth::NpFEMCloth(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager) : NpActorTemplate(baseFlags), mShape(NULL), mCudaContextManager(&cudaContextManager) { } PxBounds3 NpFEMCloth::getWorldBounds(float inflation) const { NP_READ_CHECK(getNpScene()); if (!getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Querying bounds of a PxFEMCloth which is not part of a PxScene is not supported."); return PxBounds3::empty(); } const Sc::FEMClothSim* sim = mCore.getSim(); PX_ASSERT(sim); PX_SIMD_GUARD; const PxBounds3 bounds = sim->getBounds(); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } void NpFEMCloth::setFEMClothFlag(PxFEMClothFlag::Enum flag, bool val) { PxFEMClothFlags flags = mCore.getFlags(); if (val) flags.raise(flag); else flags.clear(flag); mCore.setFlags(flags); } void NpFEMCloth::setFEMClothFlags(PxFEMClothFlags flags) { mCore.setFlags(flags); } PxFEMClothFlags NpFEMCloth::getFEMClothFlag() const { return mCore.getFlags(); } #if 0 // disabled until future use. void NpFEMCloth::setDrag(const PxReal drag) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setDrag() not allowed while simulation is running. Call will be ignored.") mCore.setDrag(drag); UPDATE_PVD_PROPERTY } PxReal NpFEMCloth::getDrag() const { return mCore.getDrag(); } void NpFEMCloth::setLift(const PxReal lift) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setLift() not allowed while simulation is running. Call will be ignored.") mCore.setLift(lift); UPDATE_PVD_PROPERTY } PxReal NpFEMCloth::getLift() const { return mCore.getLift(); } void NpFEMCloth::setWind(const PxVec3& wind) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setWind() not allowed while simulation is running. Call will be ignored.") mCore.setWind(wind); UPDATE_PVD_PROPERTY } PxVec3 NpFEMCloth::getWind() const { return mCore.getWind(); } void NpFEMCloth::setAirDensity(const PxReal airDensity) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setAirDensity() not allowed while simulation is running. Call will be ignored.") mCore.setAirDensity(airDensity); UPDATE_PVD_PROPERTY } float NpFEMCloth::getAirDensity() const { return mCore.getAirDensity(); } void NpFEMCloth::setBendingActivationAngle(const PxReal angle) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setBendingActivationAngle() not allowed while simulation is running. Call will be ignored.") mCore.setBendingActivationAngle(angle); UPDATE_PVD_PROPERTY } PxReal NpFEMCloth::getBendingActivationAngle() const { return mCore.getBendingActivationAngle(); } #endif void NpFEMCloth::setParameter(const PxFEMParameters& paramters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setParameter() not allowed while simulation is running. Call will be ignored.") mCore.setParameter(paramters); UPDATE_PVD_PROPERTY } PxFEMParameters NpFEMCloth::getParameter() const { NP_READ_CHECK(getNpScene()); return mCore.getParameter(); } void NpFEMCloth::setBendingScales(const PxReal* const bendingScales, PxU32 nbElements) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setBendingScales() not allowed while simulation is running. Call will be ignored.") mCore.setBendingScales(bendingScales, nbElements); UPDATE_PVD_PROPERTY } const PxReal* NpFEMCloth::getBendingScales() const { NP_READ_CHECK(getNpScene()); return mCore.getBendingScales(); } PxU32 NpFEMCloth::getNbBendingScales() const { NP_READ_CHECK(getNpScene()); return mCore.getNbBendingScales(); } void NpFEMCloth::setMaxVelocity(const PxReal v) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setMaxVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxVelocity(v); UPDATE_PVD_PROPERTY } PxReal NpFEMCloth::getMaxVelocity() const { return mCore.getMaxVelocity(); } void NpFEMCloth::setMaxDepenetrationVelocity(const PxReal v) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setMaxDepenetrationVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxDepenetrationVelocity(v); UPDATE_PVD_PROPERTY } PxReal NpFEMCloth::getMaxDepenetrationVelocity() const { return mCore.getMaxDepenetrationVelocity(); } void NpFEMCloth::setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setNbCollisionPairUpdatesPerTimestep() not allowed while simulation is running. Call will be ignored.") mCore.setNbCollisionPairUpdatesPerTimestep(frequency); UPDATE_PVD_PROPERTY } PxU32 NpFEMCloth::getNbCollisionPairUpdatesPerTimestep() const { return mCore.getNbCollisionPairUpdatesPerTimestep(); } void NpFEMCloth::setNbCollisionSubsteps(const PxU32 frequency) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setNbCollisionSubsteps() not allowed while simulation is running. Call will be ignored.") mCore.setNbCollisionSubsteps(frequency); UPDATE_PVD_PROPERTY } PxU32 NpFEMCloth::getNbCollisionSubsteps() const { return mCore.getNbCollisionSubsteps(); } PxVec4* NpFEMCloth::getPositionInvMassBufferD() { PX_CHECK_AND_RETURN_NULL(mShape != NULL, " NpFEMCloth::getPositionInvMassBufferD: FEM cloth does not have a shape, attach shape first."); Dy::FEMClothCore& core = mCore.getCore(); return core.mPositionInvMass; } PxVec4* NpFEMCloth::getVelocityBufferD() { PX_CHECK_AND_RETURN_NULL(mShape != NULL, " NpFEMCloth::getVelocityBufferD: FEM cloth does not have a shape, attach shape first."); Dy::FEMClothCore& core = mCore.getCore(); return core.mVelocity; } PxVec4* NpFEMCloth::getRestPositionBufferD() { PX_CHECK_AND_RETURN_NULL(mShape != NULL, " NpFEMCloth::getRestPositionBufferD: FEM cloth does not have a shape, attach shape first."); Dy::FEMClothCore& core = mCore.getCore(); return core.mRestPosition; } void NpFEMCloth::markDirty(PxFEMClothDataFlags flags) { NP_WRITE_CHECK(getNpScene()); Dy::FEMClothCore& core = mCore.getCore(); core.mDirtyFlags |= flags; } PxCudaContextManager* NpFEMCloth::getCudaContextManager() const { return mCudaContextManager; } void NpFEMCloth::setCudaContextManager(PxCudaContextManager* cudaContextManager) { mCudaContextManager = cudaContextManager; } void NpFEMCloth::setSolverIterationCounts(PxU32 positionIters) // maybe use PxU16? { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(positionIters > 0, "NpFEMCloth::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(positionIters <= 255, "NpFEMCloth::setSolverIterationCounts: positionIters must be no greater than 255!"); //PX_CHECK_AND_RETURN(velocityIters > 0, "NpFEMCloth::setSolverIterationCounts: velocityIters must be more than zero!"); //PX_CHECK_AND_RETURN(velocityIters <= 255, "NpFEMCloth::setSolverIterationCounts: velocityIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxFEMCloth::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") //mCore.setSolverIterationCounts((velocityIters & 0xff) << 8 | (positionIters & 0xff)); mCore.setSolverIterationCounts(positionIters & 0xff); } void NpFEMCloth::getSolverIterationCounts(PxU32& positionIters) const { NP_READ_CHECK(getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); //velocityIters = PxU32(x >> 8); positionIters = PxU32(x & 0xff); } PxShape* NpFEMCloth::getShape() { return mShape; } bool NpFEMCloth::attachShape(PxShape& shape) { NpShape* npShape = static_cast<NpShape*>(&shape); PX_CHECK_AND_RETURN_NULL(npShape->getGeometryTypeFast() == PxGeometryType::eTRIANGLEMESH, "NpFEMCloth::attachShape: Geometry type must be triangle mesh geometry"); PX_CHECK_AND_RETURN_NULL(mShape == NULL, "NpFEMCloth::attachShape: FEM-cloth can just have one shape"); PX_CHECK_AND_RETURN_NULL(shape.isExclusive(), "NpFEMCloth::attachShape: shape must be exclusive"); Dy::FEMClothCore& core = mCore.getCore(); PX_CHECK_AND_RETURN_NULL(core.mPositionInvMass == NULL, "NpFEMCloth::attachShape: mPositionInvMass already exists, overwrite not allowed, call detachShape first"); PX_CHECK_AND_RETURN_NULL(core.mVelocity == NULL, "NpFEMCloth::attachShape: mClothVelocity already exists, overwrite not allowed, call detachShape first"); PX_CHECK_AND_RETURN_NULL(core.mRestPosition == NULL, "NpFEMCloth::attachShape: mClothRestPosition already exists, overwrite not allowed, call detachShape first"); const PxTriangleMeshGeometry& geom = static_cast<const PxTriangleMeshGeometry&>(npShape->getGeometry()); Gu::TriangleMesh* guMesh = static_cast<Gu::TriangleMesh*>(geom.triangleMesh); #if PX_CHECKED const PxU32 triangleReference = guMesh->getNbTriangleReferences(); PX_CHECK_AND_RETURN_NULL(triangleReference > 0, "NpFEMCloth::attachShape: cloth triangle mesh has cooked with eENABLE_VERT_MAPPING"); #endif mShape = npShape; PX_ASSERT(shape.getActor() == NULL); npShape->onActorAttach(*this); updateMaterials(); const PxU32 numVerts = guMesh->getNbVerticesFast(); core.mPositionInvMass = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVerts); core.mVelocity = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVerts); core.mRestPosition = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVerts); return true; } void NpFEMCloth::addRigidFilter(PxRigidActor* actor, PxU32 vertId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::addRigidFilter: Cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::addRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::addRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); return mCore.addRigidFilter(core, vertId); } void NpFEMCloth::removeRigidFilter(PxRigidActor* actor, PxU32 vertId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::removeRigidFilter: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::removeRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::removeRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeRigidFilter(core, vertId); } PxU32 NpFEMCloth::addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpFEMCloth::addRigidAttachment: cloth must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::addRigidAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(constraint == NULL || constraint->isValid(), "NpFEMCloth::addRigidAttachment: PxConeLimitedConstraint needs to be valid if specified.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpFEMCloth::addRigidAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); Sc::BodyCore* core = getBodyCore(actor); PxVec3 aPose = actorSpacePose; if(actor && actor->getConcreteType()==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* stat = static_cast<NpRigidStatic*>(actor); aPose = stat->getGlobalPose().transform(aPose); } return mCore.addRigidAttachment(core, vertId, aPose, constraint); } void NpFEMCloth::removeRigidAttachment(PxRigidActor* actor, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::removeRigidAttachment: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::removeRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::removeRigidAttachment: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeRigidAttachment(core, handle); } void NpFEMCloth::addTriRigidFilter(PxRigidActor* actor, PxU32 triangleIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::addTriRigidFilter: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::addTriRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::addTriRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); return mCore.addTriRigidFilter(core, triangleIdx); } void NpFEMCloth::removeTriRigidFilter(PxRigidActor* actor, PxU32 triangleId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::releaseTriRigidAttachment: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::releaseTriRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::releaseTriRigidAttachment: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeTriRigidFilter(core, triangleId); } PxU32 NpFEMCloth::addTriRigidAttachment(PxRigidActor* actor, PxU32 triangleIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpFEMCloth::addTriRigidAttachment: cloth must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::addTriRigidAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(constraint == NULL || constraint->isValid(), "NpFEMCloth::addTriRigidAttachment: PxConeLimitedConstraint needs to be valid if specified.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpFEMCloth::addTriRigidAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); Sc::BodyCore* core = getBodyCore(actor); PxVec3 aPose = actorSpacePose; if(actor && actor->getConcreteType()==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* stat = static_cast<NpRigidStatic*>(actor); aPose = stat->getGlobalPose().transform(aPose); } return mCore.addTriRigidAttachment(core, triangleIdx, barycentric, aPose, constraint); } void NpFEMCloth::removeTriRigidAttachment(PxRigidActor* actor, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::releaseTriRigidAttachment: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpFEMCloth::releaseTriRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::releaseTriRigidAttachment: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeTriRigidAttachment(core, handle); } void NpFEMCloth::addClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::addClothAttachment: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN((otherCloth == NULL || otherCloth->getScene() != NULL), "NpFEMCloth::addClothFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::addClothFilter: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(otherCloth); Sc::FEMClothCore* otherCore = &dyn->getCore(); return mCore.addClothFilter(otherCore, otherTriIdx, triIdx); } void NpFEMCloth::removeClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(otherCloth != NULL, "NpFEMCloth::removeClothFilter: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::removeClothFilter: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN(otherCloth->getScene() != NULL, "NpFEMCloth::removeClothFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::removeClothFilter: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(otherCloth); Sc::FEMClothCore* otherCore = &dyn->getCore(); mCore.removeClothFilter(otherCore, otherTriIdx, triIdx); } PxU32 NpFEMCloth::addClothAttachment(PxFEMCloth* otherCloth, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpFEMCloth::addClothAttachment: cloth must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL((otherCloth == NULL || otherCloth->getScene() != NULL), "NpFEMCloth::addClothAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpFEMCloth::addClothAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(otherCloth); Sc::FEMClothCore* otherCore = &dyn->getCore(); return mCore.addClothAttachment(otherCore, otherTriIdx, otherTriBarycentric, triIdx, triBarycentric); } void NpFEMCloth::removeClothAttachment(PxFEMCloth* otherCloth, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(otherCloth != NULL, "NpFEMCloth::releaseClothAttachment: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFEMCloth::releaseClothAttachment: cloth must be inserted into the scene."); PX_CHECK_AND_RETURN(otherCloth->getScene() != NULL, "NpFEMCloth::releaseClothAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpFEMCloth::releaseClothAttachment: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(otherCloth); Sc::FEMClothCore* otherCore = &dyn->getCore(); mCore.removeClothAttachment(otherCore, handle); } void NpFEMCloth::detachShape() { Dy::FEMClothCore& core = mCore.getCore(); if (core.mPositionInvMass) { PX_DEVICE_FREE(mCudaContextManager, core.mPositionInvMass); core.mPositionInvMass = NULL; } if (core.mVelocity) { PX_DEVICE_FREE(mCudaContextManager, core.mVelocity); core.mVelocity = NULL; } if (core.mRestPosition) { PX_DEVICE_FREE(mCudaContextManager, core.mRestPosition); core.mRestPosition = NULL; } if (mShape) mShape->onActorDetach(); mShape = NULL; } void NpFEMCloth::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); if (npScene) { npScene->scRemoveFEMCloth(*this); npScene->removeFromFEMClothList(*this); } detachShape(); PX_ASSERT(!isAPIWriteForbidden()); NpDestroyFEMCloth(this); } void NpFEMCloth::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); mName = debugName; } const char* NpFEMCloth::getName() const { NP_READ_CHECK(getNpScene()); return mName; } bool NpFEMCloth::isSleeping() const { Sc::FEMClothSim* sim = mCore.getSim(); if (sim) { return sim->isSleeping(); } return true; } void NpFEMCloth::updateMaterials() { Dy::FEMClothCore& core = mCore.getCore(); core.clearMaterials(); for (PxU32 i = 0; i < mShape->getNbMaterials(); ++i) { PxFEMClothMaterial* material; mShape->getClothMaterials(&material, 1, i); core.setMaterial(static_cast<NpFEMClothMaterial*>(material)->mMaterial.mMaterialIndex); } } #endif } #endif //PX_SUPPORT_GPU_PHYSX
23,752
C++
34.665165
177
0.745874
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSceneQueries.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 "NpSceneQueries.h" #include "common/PxProfileZone.h" #include "GuBounds.h" #include "CmTransformUtils.h" #include "NpShape.h" #include "NpActor.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "GuActorShapeMap.h" using namespace physx; using namespace Sq; using namespace Gu; #if PX_SUPPORT_PVD #include "NpPvdSceneQueryCollector.h" #endif PX_IMPLEMENT_OUTPUT_ERROR static PX_FORCE_INLINE NpShape* getShapeFromPayload(const PrunerPayload& payload) { return reinterpret_cast<NpShape*>(payload.data[0]); } static PX_FORCE_INLINE NpActor* getActorFromPayload(const PrunerPayload& payload) { return reinterpret_cast<NpActor*>(payload.data[1]); } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE ActorShapeData createActorShapeData(PrunerData data, PrunerCompoundId id) { return (ActorShapeData(id) << 32) | ActorShapeData(data); } static PX_FORCE_INLINE PrunerData getPrunerData(ActorShapeData data) { return PrunerData(data); } static PX_FORCE_INLINE PrunerCompoundId getCompoundID(ActorShapeData data) { return PrunerCompoundId(data >> 32); } /////////////////////////////////////////////////////////////////////////////// namespace { class NpSqAdapter : public QueryAdapter { public: NpSqAdapter() {} virtual ~NpSqAdapter() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter // QueryAdapter virtual PrunerHandle findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const; virtual void getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const; virtual void getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const; //~QueryAdapter ActorShapeMap mDatabase; }; } PrunerHandle NpSqAdapter::findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const { const NpActor& npActor = NpActor::getFromPxActor(*cache.actor); const PxU32 actorIndex = npActor.getBaseIndex(); PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); const ActorShapeData actorShapeData = mDatabase.find(actorIndex, &npActor, static_cast<NpShape*>(cache.shape)); const PrunerData prunerData = getPrunerData(actorShapeData); compoundId = getCompoundID(actorShapeData); prunerIndex = getPrunerIndex(prunerData); return getPrunerHandle(prunerData); } void NpSqAdapter::getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const { NpShape* npShape = getShapeFromPayload(payload); filterData = npShape->getQueryFilterData(); } void NpSqAdapter::getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const { NpShape* npShape = getShapeFromPayload(payload); NpActor* npActor = getActorFromPayload(payload); actorShape.actor = static_cast<PxRigidActor*>(static_cast<const Sc::RigidCore&>(npActor->getActorCore()).getPxActor()); actorShape.shape = npShape; PX_ASSERT(actorShape.shape == npShape->getCore().getPxShape()); } const PxGeometry& NpSqAdapter::getGeometry(const PrunerPayload& payload) const { NpShape* npShape = getShapeFromPayload(payload); return npShape->getCore().getGeometry(); } #if PX_SUPPORT_PVD bool NpSceneQueries::transmitSceneQueries() { if(!mPVDClient) return false; if(!(mPVDClient->checkPvdDebugFlag() && (mPVDClient->getScenePvdFlagsFast() & PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES))) return false; return true; } void NpSceneQueries::raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) { mSingleSqCollector.raycast(origin, unitDir, distance, hit, hitsNum, filterData, multipleHits); } void NpSceneQueries::sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) { mSingleSqCollector.sweep(geometry, pose, unitDir, distance, hit, hitsNum, filterData, multipleHits); } void NpSceneQueries::overlap(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData) { mSingleSqCollector.overlapMultiple(geometry, pose, hit, hitsNum, filterData); } #endif static PX_FORCE_INLINE void setPayload(PrunerPayload& pp, const NpShape* npShape, const NpActor* npActor) { pp.data[0] = size_t(npShape); pp.data[1] = size_t(npActor); } static PX_FORCE_INLINE bool isDynamicActor(const PxRigidActor& actor) { const PxType actorType = actor.getConcreteType(); return actorType != PxConcreteType::eRIGID_STATIC; } namespace { struct DatabaseCleaner : PrunerPayloadRemovalCallback { DatabaseCleaner(NpSqAdapter& adapter) : mAdapter(adapter){} virtual void invoke(PxU32 nbRemoved, const PrunerPayload* removed) { PxU32 actorIndex = NP_UNUSED_BASE_INDEX; const NpActor* cachedActor = NULL; while(nbRemoved--) { const PrunerPayload& payload = *removed++; const NpActor* npActor = getActorFromPayload(payload); if(npActor!=cachedActor) { actorIndex = npActor->getBaseIndex(); cachedActor = npActor; } PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); bool status = mAdapter.mDatabase.remove(actorIndex, npActor, getShapeFromPayload(payload), NULL); PX_ASSERT(status); PX_UNUSED(status); } } NpSqAdapter& mAdapter; PX_NOCOPY(DatabaseCleaner) }; } namespace { class InternalPxSQ : public PxSceneQuerySystem, public PxUserAllocated { public: InternalPxSQ(const PxSceneDesc& desc, PVDCapture* pvd, PxU64 contextID, Pruner* staticPruner, Pruner* dynamicPruner) : mQueries(pvd, contextID, staticPruner, dynamicPruner, desc.dynamicTreeRebuildRateHint, SQ_PRUNER_EPSILON, desc.limits, mAdapter), mUpdateMode (desc.sceneQueryUpdateMode), mRefCount (1) {} virtual ~InternalPxSQ(){} PX_FORCE_INLINE Sq::PrunerManager& SQ() { return mQueries.mSQManager; } PX_FORCE_INLINE const Sq::PrunerManager& SQ() const { return mQueries.mSQManager; } virtual void release() { mRefCount--; if(!mRefCount) PX_DELETE_THIS; } virtual void acquireReference() { mRefCount++; } virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) { SQ().preallocate(prunerIndex, nbShapes); } // PT: TODO: returning PxSQShapeHandle means we have to store them in PhysX, inside the shape manager's mSceneQueryData array. But if we'd change the API here // and also pass the actor/shape couple instead of cached PxSQShapeHandle to functions like removeSQShape, it would simplify the internal PhysX code and truly // decouple the SQ parts from the rest. It is unclear what the consequences would be on performance: on one hand the PxSQ implementation would need a // hashmap or something to remap actor/shape to the SQ data, on the other hand the current code for that in PhysX is only fast for non-shared shapes. // (see findSceneQueryData) // // Another appealing side-effect here is that there probably wouldn't be a "compound ID" anymore: we just pass the actor/shape couple and it's up to // the implementation to know that this actor was added "as a compound" or not. Again, consequences on the code are unknown. We might have to just try. // // It might become quite tedious for the sync function though, since that one caches *PxSQPrunerHandles*. We don't want to do the "ref finding" equivalent each // frame for each shape, so some kind of cache is needed. That probably means these cached items must appear and be handled on the PhysX/internal side of // the API. That being said and as noted already in another part of the code: // PT: TODO: this is similar to findPrunerData in QueryAdapter. Maybe we could unify these. // => so the ref-finding code could stay, and just reuse findPrunerData (like the query cache). It wouldn't fully decouple the internal PhysX code from SQ, // since we'd still store an array of "PrunerData" internally. *BUT* we could still drop mSceneQueryData. So, still worth trying. // // The nail in the coffin for this idea though is that we still need to provide an internal implementation of PxSQ, and that one does use mSceneQueryData. // So we're struck with this array, unless we decide that there is NO internal implementation, and it's all moved to Extensions all the time. // // If we move the implementation to Extension, suddenly we need to link to SceneQuery.lib, which was not the case previously. At this point it becomes // appealing to just move the Sq code to Gu: it solves the link errors, we could finally include it from Sc, we'd get rid of cross-DLL calls between // Sq and Gu, etc virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure) { const NpShape& npShape = static_cast<const NpShape&>(shape); const NpActor& npActor = NpActor::getFromPxActor(actor); PrunerPayload payload; setPayload(payload, &npShape, &npActor); const PrunerCompoundId pcid = compoundHandle ? PrunerCompoundId(*compoundHandle) : INVALID_COMPOUND_ID; const PrunerData prunerData = SQ().addPrunerShape(payload, isDynamicActor(actor), pcid, bounds, transform, hasPruningStructure); const PxU32 actorIndex = npActor.getBaseIndex(); PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); mAdapter.mDatabase.add(actorIndex, &npActor, &npShape, createActorShapeData(prunerData, pcid)); } virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape) { const NpActor& npActor = NpActor::getFromPxActor(actor); const NpShape& npShape = static_cast<const NpShape&>(shape); const PxU32 actorIndex = npActor.getBaseIndex(); PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); ActorShapeData actorShapeData; mAdapter.mDatabase.remove(actorIndex, &npActor, &npShape, &actorShapeData); const PrunerData data = getPrunerData(actorShapeData); const PrunerCompoundId compoundId = getCompoundID(actorShapeData); SQ().removePrunerShape(compoundId, data, NULL); } virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) { const NpActor& npActor = NpActor::getFromPxActor(actor); const NpShape& npShape = static_cast<const NpShape&>(shape); const PxU32 actorIndex = npActor.getBaseIndex(); PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); const ActorShapeData actorShapeData = mAdapter.mDatabase.find(actorIndex, &npActor, &npShape); const PrunerData shapeHandle = getPrunerData(actorShapeData); const PrunerCompoundId pcid = getCompoundID(actorShapeData); SQ().markForUpdate(pcid, shapeHandle, transform); } virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& pxbvh, const PxTransform* transforms) { const BVH& bvh = static_cast<const BVH&>(pxbvh); const PxU32 numSqShapes = bvh.BVH::getNbBounds(); const NpActor& npActor = NpActor::getFromPxActor(actor); PX_ALLOCA(payloads, PrunerPayload, numSqShapes); for(PxU32 i=0; i<numSqShapes; i++) setPayload(payloads[i], static_cast<const NpShape*>(shapes[i]), &npActor); const PxU32 actorIndex = npActor.getBaseIndex(); PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); PX_ALLOCA(shapeHandles, PrunerData, numSqShapes); SQ().addCompoundShape(bvh, PrunerCompoundId(actorIndex), actor.getGlobalPose(), shapeHandles, payloads, transforms, isDynamicActor(actor)); for(PxU32 i=0; i<numSqShapes; i++) { // PT: TODO: actorIndex is now redundant! mAdapter.mDatabase.add(actorIndex, &npActor, static_cast<const NpShape*>(shapes[i]), createActorShapeData(shapeHandles[i], actorIndex)); } return PxSQCompoundHandle(actorIndex); } virtual void removeSQCompound(PxSQCompoundHandle compoundHandle) { DatabaseCleaner cleaner(mAdapter); SQ().removeCompoundActor(PrunerCompoundId(compoundHandle), &cleaner); } virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) { SQ().updateCompoundActor(PrunerCompoundId(compoundHandle), compoundTransform); } virtual void flushUpdates() { SQ().flushUpdates(); } virtual void flushMemory() { SQ().flushMemory(); } virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const { SQ().visualize(prunerIndex, out); } virtual void shiftOrigin(const PxVec3& shift) { SQ().shiftOrigin(shift); } virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex) { return SQ().prepareSceneQueriesUpdate(PruningIndex::Enum(prunerIndex)); } virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle) { SQ().sceneQueryBuildStep(handle); } virtual void setDynamicTreeRebuildRateHint(PxU32 dynTreeRebuildRateHint) { SQ().setDynamicTreeRebuildRateHint(dynTreeRebuildRateHint); } virtual PxU32 getDynamicTreeRebuildRateHint() const { return SQ().getDynamicTreeRebuildRateHint(); } virtual void forceRebuildDynamicTree(PxU32 prunerIndex) { SQ().forceRebuildDynamicTree(prunerIndex); } virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const { return mUpdateMode; } virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum mode) { mUpdateMode = mode; } virtual PxU32 getStaticTimestamp() const { return SQ().getStaticTimestamp(); } virtual void finalizeUpdates() { switch(mUpdateMode) { case PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED: SQ().afterSync(true, true); break; case PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED: SQ().afterSync(true, false); break; case PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED: SQ().afterSync(false, false); break; } } virtual void merge(const PxPruningStructure& pxps) { Pruner* staticPruner = SQ().getPruner(PruningIndex::eSTATIC); if(staticPruner) staticPruner->merge(pxps.getStaticMergeData()); Pruner* dynamicPruner = SQ().getPruner(PruningIndex::eDYNAMIC); if(dynamicPruner) dynamicPruner->merge(pxps.getDynamicMergeData()); } virtual bool raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { return mQueries._raycast(origin, unitDir, distance, hitCall, hitFlags, filterData, filterCall, cache, flags); } virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const { return mQueries._sweep(geometry, pose, unitDir, distance, hitCall, hitFlags, filterData, filterCall, cache, inflation, flags); } virtual bool overlap( const PxGeometry& geometry, const PxTransform& transform, PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { return mQueries._overlap( geometry, transform, hitCall, filterData, filterCall, cache, flags); } virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const { const NpActor& npActor = NpActor::getFromPxActor(actor); const NpShape& npShape = static_cast<const NpShape&>(shape); const PxU32 actorIndex = npActor.getBaseIndex(); PX_ASSERT(actorIndex!=NP_UNUSED_BASE_INDEX); const ActorShapeData actorShapeData = mAdapter.mDatabase.find(actorIndex, &npActor, &npShape); const PrunerData prunerData = getPrunerData(actorShapeData); prunerIndex = getPrunerIndex(prunerData); return PxSQPrunerHandle(getPrunerHandle(prunerData)); } virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) { PX_ASSERT(prunerIndex==PruningIndex::eDYNAMIC); if(prunerIndex==PruningIndex::eDYNAMIC) SQ().sync(handles, boundsIndices, bounds, transforms, count, ignoredIndices); } SceneQueries mQueries; NpSqAdapter mAdapter; PxSceneQueryUpdateMode::Enum mUpdateMode; PxU32 mRefCount; }; } #include "SqFactory.h" static CompanionPrunerType getCompanionType(PxDynamicTreeSecondaryPruner::Enum type) { switch(type) { case PxDynamicTreeSecondaryPruner::eNONE: return COMPANION_PRUNER_NONE; case PxDynamicTreeSecondaryPruner::eBUCKET: return COMPANION_PRUNER_BUCKET; case PxDynamicTreeSecondaryPruner::eINCREMENTAL: return COMPANION_PRUNER_INCREMENTAL; case PxDynamicTreeSecondaryPruner::eBVH: return COMPANION_PRUNER_AABB_TREE; case PxDynamicTreeSecondaryPruner::eLAST: return COMPANION_PRUNER_NONE; } return COMPANION_PRUNER_NONE; } static BVHBuildStrategy getBuildStrategy(PxBVHBuildStrategy::Enum bs) { switch(bs) { case PxBVHBuildStrategy::eFAST: return BVH_SPLATTER_POINTS; case PxBVHBuildStrategy::eDEFAULT: return BVH_SPLATTER_POINTS_SPLIT_GEOM_CENTER; case PxBVHBuildStrategy::eSAH: return BVH_SAH; case PxBVHBuildStrategy::eLAST: return BVH_SPLATTER_POINTS; } return BVH_SPLATTER_POINTS; } static Pruner* create(PxPruningStructureType::Enum type, PxU64 contextID, PxDynamicTreeSecondaryPruner::Enum secondaryType, PxBVHBuildStrategy::Enum buildStrategy, PxU32 nbObjectsPerNode) { // PT: to force testing the bucket pruner // return createBucketPruner(contextID); // return createIncrementalPruner(contextID); const CompanionPrunerType cpType = getCompanionType(secondaryType); const BVHBuildStrategy bs = getBuildStrategy(buildStrategy); Pruner* pruner = NULL; switch(type) { case PxPruningStructureType::eNONE: { pruner = createBucketPruner(contextID); break; } case PxPruningStructureType::eDYNAMIC_AABB_TREE: { pruner = createAABBPruner(contextID, true, cpType, bs, nbObjectsPerNode); break; } case PxPruningStructureType::eSTATIC_AABB_TREE: { pruner = createAABBPruner(contextID, false, cpType, bs, nbObjectsPerNode); break; } // PT: for tests case PxPruningStructureType::eLAST: { pruner = createIncrementalPruner(contextID); break; } // case PxPruningStructureType::eLAST: break; } return pruner; } static PxSceneQuerySystem* getPxSQ(const PxSceneDesc& desc, PVDCapture* pvd, PxU64 contextID) { if(desc.sceneQuerySystem) { desc.sceneQuerySystem->acquireReference(); return desc.sceneQuerySystem; } else { Pruner* staticPruner = create(desc.staticStructure, contextID, desc.dynamicTreeSecondaryPruner, desc.staticBVHBuildStrategy, desc.staticNbObjectsPerNode); Pruner* dynamicPruner = create(desc.dynamicStructure, contextID, desc.dynamicTreeSecondaryPruner, desc.dynamicBVHBuildStrategy, desc.dynamicNbObjectsPerNode); return PX_NEW(InternalPxSQ)(desc, pvd, contextID, staticPruner, dynamicPruner); } } #if PX_SUPPORT_PVD #define PVD_PARAM this #else #define PVD_PARAM NULL #endif NpSceneQueries::NpSceneQueries(const PxSceneDesc& desc, Vd::PvdSceneClient* pvd, PxU64 contextID) : mSQ (getPxSQ(desc, PVD_PARAM, contextID)) #if PX_SUPPORT_PVD // PT: warning, pvd object not created yet at this point ,mPVDClient (pvd) ,mSingleSqCollector (pvd, false) #endif { PX_UNUSED(pvd); PX_UNUSED(contextID); } NpSceneQueries::~NpSceneQueries() { if(mSQ) { mSQ->release(); mSQ = NULL; } } void NpSceneQueries::sync(PxU32 prunerIndex, const ScPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) { mSQ->sync(prunerIndex, handles, indices, bounds, transforms, count, ignoredIndices); } #include "NpScene.h" // PT: TODO: eventually move NP_READ_CHECK to internal PxSQ version ? bool NpScene::raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxHitCallback<PxRaycastHit>& hits, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { NP_READ_CHECK(this); return mNpSQ.mSQ->raycast(origin, unitDir, distance, hits, hitFlags, filterData, filterCall, cache, flags); } bool NpScene::overlap( const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { NP_READ_CHECK(this); return mNpSQ.mSQ->overlap(geometry, pose, hits, filterData, filterCall, cache, flags); } bool NpScene::sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxHitCallback<PxSweepHit>& hits, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const { NP_READ_CHECK(this); return mNpSQ.mSQ->sweep(geometry, pose, unitDir, distance, hits, hitFlags, filterData, filterCall, cache, inflation, flags); } void NpScene::setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) { NP_WRITE_CHECK(this); getSQAPI().setUpdateMode(updateMode); updatePvdProperties(); } PxSceneQueryUpdateMode::Enum NpScene::getUpdateMode() const { NP_READ_CHECK(this); return getSQAPI().getUpdateMode(); } void NpScene::setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint) { NP_WRITE_CHECK(this); PX_CHECK_AND_RETURN((dynamicTreeRebuildRateHint >= 4), "PxScene::setDynamicTreeRebuildRateHint(): Param has to be >= 4!"); getSQAPI().setDynamicTreeRebuildRateHint(dynamicTreeRebuildRateHint); updatePvdProperties(); } PxU32 NpScene::getDynamicTreeRebuildRateHint() const { NP_READ_CHECK(this); return getSQAPI().getDynamicTreeRebuildRateHint(); } void NpScene::forceRebuildDynamicTree(PxU32 prunerIndex) { PX_PROFILE_ZONE("API.forceDynamicTreeRebuild", getContextId()); NP_WRITE_CHECK(this); PX_SIMD_GUARD; getSQAPI().forceRebuildDynamicTree(prunerIndex); } PxU32 NpScene::getStaticTimestamp() const { return getSQAPI().getStaticTimestamp(); } PxPruningStructureType::Enum NpScene::getStaticStructure() const { return mPrunerType[0]; } PxPruningStructureType::Enum NpScene::getDynamicStructure() const { return mPrunerType[1]; } void NpScene::flushUpdates() { PX_PROFILE_ZONE("API.flushQueryUpdates", getContextId()); NP_WRITE_CHECK(this); PX_SIMD_GUARD; getSQAPI().flushUpdates(); } namespace { class SqRefFinder: public Sc::SqRefFinder { PX_NOCOPY(SqRefFinder) public: SqRefFinder(const PxSceneQuerySystem& pxsq) : mPXSQ(pxsq) {} const PxSceneQuerySystem& mPXSQ; virtual ScPrunerHandle find(const PxRigidBody* body, const PxShape* shape, PxU32& prunerIndex) { return mPXSQ.getHandle(*body, *shape, prunerIndex); } }; } void NpScene::syncSQ() { PxSceneQuerySystem& pm = getSQAPI(); { const PxU32 numBodies = mScene.getNumActiveCompoundBodies(); const Sc::BodyCore*const* bodies = mScene.getActiveCompoundBodiesArray(); // PT: we emulate "getGlobalPose" here by doing the equivalent matrix computation directly. // This works because the code is the same for rigid dynamic & articulation links. // PT: TODO: SIMD for(PxU32 i = 0; i < numBodies; i++) { // PT: we don't have access to Np from here so we have to go through Px, which is a bit ugly. // If this creates perf issues an alternative would be to just store the ID along with the body // pointer in the active compound bodies array. PxActor* actor = bodies[i]->getPxActor(); PX_ASSERT(actor); const PxU32 id = static_cast<PxRigidActor*>(actor)->getInternalActorIndex(); PX_ASSERT(id!=0xffffffff); pm.updateSQCompound(PxSQCompoundHandle(id), bodies[i]->getBody2World() * bodies[i]->getBody2Actor().getInverse()); } } SqRefFinder sqRefFinder(pm); mScene.syncSceneQueryBounds(mNpSQ, sqRefFinder); pm.finalizeUpdates(); } void NpScene::forceSceneQueryRebuild() { // PT: what is this function anyway? What's the difference between this and forceDynamicTreeRebuild ? Why is the implementation different? syncSQ(); } void NpScene::sceneQueriesStaticPrunerUpdate(PxBaseTask* ) { PX_PROFILE_ZONE("SceneQuery.sceneQueriesStaticPrunerUpdate", getContextId()); // run pruner build only, this will build the new tree only, no commit happens getSQAPI().sceneQueryBuildStep(mStaticBuildStepHandle); } void NpScene::sceneQueriesDynamicPrunerUpdate(PxBaseTask*) { PX_PROFILE_ZONE("SceneQuery.sceneQueriesDynamicPrunerUpdate", getContextId()); // run pruner build only, this will build the new tree only, no commit happens getSQAPI().sceneQueryBuildStep(mDynamicBuildStepHandle); } void NpScene::sceneQueriesUpdate(PxBaseTask* completionTask, bool controlSimulation) { PX_SIMD_GUARD; PxSQBuildStepHandle runUpdateTasksStatic = NULL; PxSQBuildStepHandle runUpdateTasksDynamic = NULL; { // write guard must end before scene queries tasks kicks off worker threads NP_WRITE_CHECK(this); PX_PROFILE_START_CROSSTHREAD("Basic.sceneQueriesUpdate", getContextId()); if(mSQUpdateRunning) { //fetchSceneQueries doesn't get called outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchSceneQueries was not called!"); return; } PxSceneQuerySystem& pxsq = getSQAPI(); // flush scene queries updates pxsq.flushUpdates(); // prepare scene queries for build - copy bounds runUpdateTasksStatic = pxsq.prepareSceneQueryBuildStep(PX_SCENE_PRUNER_STATIC); runUpdateTasksDynamic = pxsq.prepareSceneQueryBuildStep(PX_SCENE_PRUNER_DYNAMIC); mStaticBuildStepHandle = runUpdateTasksStatic; mDynamicBuildStepHandle = runUpdateTasksDynamic; mSQUpdateRunning = true; } { PX_PROFILE_ZONE("Sim.sceneQueriesTaskSetup", getContextId()); if (controlSimulation) { { PX_PROFILE_ZONE("Sim.resetDependencies", getContextId()); // Only reset dependencies, etc if we own the TaskManager. Will be false // when an NpScene is controlled by an APEX scene. mTaskManager->resetDependencies(); } mTaskManager->startSimulation(); } mSceneQueriesCompletion.setContinuation(*mTaskManager, completionTask); if(runUpdateTasksStatic) mSceneQueriesStaticPrunerUpdate.setContinuation(&mSceneQueriesCompletion); if(runUpdateTasksDynamic) mSceneQueriesDynamicPrunerUpdate.setContinuation(&mSceneQueriesCompletion); mSceneQueriesCompletion.removeReference(); if(runUpdateTasksStatic) mSceneQueriesStaticPrunerUpdate.removeReference(); if(runUpdateTasksDynamic) mSceneQueriesDynamicPrunerUpdate.removeReference(); } } bool NpScene::checkSceneQueriesInternal(bool block) { PX_PROFILE_ZONE("Basic.checkSceneQueries", getContextId()); return mSceneQueriesDone.wait(block ? PxSync::waitForever : 0); } bool NpScene::checkQueries(bool block) { return checkSceneQueriesInternal(block); } bool NpScene::fetchQueries(bool block) { if(!mSQUpdateRunning) { //fetchSceneQueries doesn't get called outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchQueries: fetchQueries() called illegally! It must be called after sceneQueriesUpdate()"); return false; } if(!checkSceneQueriesInternal(block)) return false; { PX_SIMD_GUARD; NP_WRITE_CHECK(this); // we use cross thread profile here, to show the event in cross thread view // PT: TODO: why do we want to show it in the cross thread view? PX_PROFILE_START_CROSSTHREAD("Basic.fetchQueries", getContextId()); // flush updates and commit if work is done getSQAPI().flushUpdates(); PX_PROFILE_STOP_CROSSTHREAD("Basic.fetchQueries", getContextId()); PX_PROFILE_STOP_CROSSTHREAD("Basic.sceneQueriesUpdate", getContextId()); mSceneQueriesDone.reset(); mSQUpdateRunning = false; } return true; }
30,251
C++
36.862328
213
0.747645
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpActor.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_ACTOR_H #define NP_ACTOR_H #include "NpConnector.h" #include "NpBase.h" namespace physx { class NpShapeManager; class NpAggregate; class NpScene; class NpShape; const Sc::BodyCore* getBodyCore(const PxRigidActor* actor); PX_FORCE_INLINE Sc::BodyCore* getBodyCore(PxRigidActor* actor) { const Sc::BodyCore* core = getBodyCore(static_cast<const PxRigidActor*>(actor)); return const_cast<Sc::BodyCore*>(core); } class NpActor : public NpBase { public: // PX_SERIALIZATION NpActor(const PxEMPTY) : NpBase(PxEmpty) {} void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpActor(NpType::Enum type); void removeConstraints(PxRigidActor& owner); void removeFromAggregate(PxActor& owner); NpAggregate* getNpAggregate(PxU32& index) const; void setAggregate(NpAggregate* np, PxActor& owner); PxAggregate* getAggregate() const; void scSetDominanceGroup(PxDominanceGroup v); void scSetOwnerClient(PxClientID inId); void removeConstraintsFromScene(); PX_FORCE_INLINE void addConstraintsToScene() // inline the fast path for addActors() { if(mConnectorArray) addConstraintsToSceneInternal(); } PxU32 findConnector(NpConnectorType::Enum type, PxBase* object) const; void addConnector(NpConnectorType::Enum type, PxBase* object, const char* errMsg); void removeConnector(PxActor& owner, NpConnectorType::Enum type, PxBase* object, const char* errorMsg); PxU32 getNbConnectors(NpConnectorType::Enum type) const; static NpShapeManager* getShapeManager_(PxRigidActor& actor); // bit misplaced here, but we don't want a separate subclass just for this static const NpShapeManager* getShapeManager_(const PxRigidActor& actor); // bit misplaced here, but we don't want a separate subclass just for this static NpActor& getFromPxActor(PxActor& actor) { return *PxPointerOffset<NpActor*>(&actor, ptrdiff_t(sOffsets.pxActorToNpActor[actor.getConcreteType()])); } static const NpActor& getFromPxActor(const PxActor& actor) { return *PxPointerOffset<const NpActor*>(&actor, ptrdiff_t(sOffsets.pxActorToNpActor[actor.getConcreteType()])); } const PxActor* getPxActor() const; static NpScene* getNpSceneFromActor(const PxActor& actor) { return getFromPxActor(actor).getNpScene(); } PX_FORCE_INLINE NpConnectorIterator getConnectorIterator(NpConnectorType::Enum type) { if (mConnectorArray) return NpConnectorIterator(&mConnectorArray->front(), mConnectorArray->size(), type); else return NpConnectorIterator(NULL, 0, type); } static void onActorRelease(PxActor* actor); template<typename T> PxU32 getConnectors(NpConnectorType::Enum type, T** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const { PxU32 nbConnectors = 0; if(mConnectorArray) { for(PxU32 i=0; i<mConnectorArray->size(); i++) { NpConnector& c = (*mConnectorArray)[i]; if(c.mType == type && nbConnectors < bufferSize && i>=startIndex) userBuffer[nbConnectors++] = static_cast<T*>(c.mObject); } } return nbConnectors; } PX_INLINE PxActorFlags getActorFlags() const { return getActorCore().getActorFlags(); } PX_INLINE PxDominanceGroup getDominanceGroup() const { return getActorCore().getDominanceGroup(); } PX_INLINE PxClientID getOwnerClient() const { return getActorCore().getOwnerClient(); } PX_INLINE void scSetActorFlags(PxActorFlags v) { PX_ASSERT(!isAPIWriteForbidden()); // PT: TODO: move this check out of here, they should be done in Np! #if PX_CHECKED const PxActorFlags aFlags = getActorFlags(); const NpType::Enum npType = getNpType(); if((!aFlags.isSet(PxActorFlag::eDISABLE_SIMULATION)) && v.isSet(PxActorFlag::eDISABLE_SIMULATION) && (npType != NpType::eBODY) && (npType != NpType::eRIGID_STATIC)) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxActor::setActorFlag: PxActorFlag::eDISABLE_SIMULATION is only supported by PxRigidDynamic and PxRigidStatic objects."); } #endif getActorCore().setActorFlags(v); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE const Sc::ActorCore& getActorCore() const { return *reinterpret_cast<const Sc::ActorCore*>(size_t(this) + sNpOffsets.npToSc[getNpType()]); } PX_FORCE_INLINE Sc::ActorCore& getActorCore() { return *reinterpret_cast<Sc::ActorCore*>(size_t(this) + sNpOffsets.npToSc[getNpType()]); } PX_INLINE const Sc::RigidCore& getScRigidCore() const { return static_cast<const Sc::RigidCore&>(getActorCore()); } PX_INLINE Sc::RigidCore& getScRigidCore() { return static_cast<Sc::RigidCore&>(getActorCore()); } PX_FORCE_INLINE void scSwitchToNoSim() { NpScene* scene = getNpScene(); if(scene && (!scene->isAPIWriteForbidden())) scene->scSwitchRigidToNoSim(*this); } PX_FORCE_INLINE void scSwitchFromNoSim() { NpScene* scene = getNpScene(); if(scene && (!scene->isAPIWriteForbidden())) scene->scSwitchRigidFromNoSim(*this); } protected: ~NpActor() {} const char* mName; // Lazy-create array for connector objects like constraints, observers, ... // Most actors have no such objects, so we bias this class accordingly: NpConnectorArray* mConnectorArray; private: void addConstraintsToSceneInternal(); void removeConnector(PxActor& owner, PxU32 index); struct Offsets { size_t pxActorToNpActor[PxConcreteType::ePHYSX_CORE_COUNT]; Offsets(); }; public: static const Offsets sOffsets; struct NpOffsets { size_t npToSc[NpType::eTYPE_COUNT]; NpOffsets(); }; static const NpOffsets sNpOffsets; }; } #endif
8,230
C
39.348039
179
0.669623
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPhysics.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_PHYSICS_H #define NP_PHYSICS_H #include "PxPhysics.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "GuMeshFactory.h" #include "NpMaterial.h" #include "NpFEMSoftBodyMaterial.h" #include "NpFEMClothMaterial.h" #include "NpPBDMaterial.h" #include "NpFLIPMaterial.h" #include "NpMPMMaterial.h" #include "NpPhysicsInsertionCallback.h" #include "NpMaterialManager.h" #include "ScPhysics.h" #ifdef LINUX #include <string.h> #endif #if PX_SUPPORT_GPU_PHYSX #include "device/PhysXIndicator.h" #endif #include "PsPvd.h" #if PX_SUPPORT_OMNI_PVD class OmniPvdPxSampler; namespace physx { class PxOmniPvd; } #endif namespace physx { #if PX_SUPPORT_PVD namespace Vd { class PvdPhysicsClient; } #endif struct NpMaterialIndexTranslator { NpMaterialIndexTranslator() : indicesNeedTranslation(false) {} PxHashMap<PxU16, PxU16> map; bool indicesNeedTranslation; }; class NpScene; struct PxvOffsetTable; #if PX_VC #pragma warning(push) #pragma warning(disable:4996) // We have to implement deprecated member functions, do not warn. #endif template <typename T> class NpMaterialAccessor; class NpPhysics : public PxPhysics, public PxUserAllocated { PX_NOCOPY(NpPhysics) struct NpDelListenerEntry : public PxUserAllocated { NpDelListenerEntry(const PxDeletionEventFlags& de, bool restrictedObjSet) : flags(de) , restrictedObjectSet(restrictedObjSet) { } PxHashSet<const PxBase*> registeredObjects; // specifically registered objects for deletion events PxDeletionEventFlags flags; bool restrictedObjectSet; }; NpPhysics( const PxTolerancesScale& scale, const PxvOffsetTable& pxvOffsetTable, bool trackOutstandingAllocations, physx::pvdsdk::PsPvd* pvd, PxFoundation&, physx::PxOmniPvd* omniPvd); virtual ~NpPhysics(); public: static NpPhysics* createInstance( PxU32 version, PxFoundation& foundation, const PxTolerancesScale& scale, bool trackOutstandingAllocations, physx::pvdsdk::PsPvd* pvd, physx::PxOmniPvd* omniPvd); static PxU32 releaseInstance(); static NpPhysics& getInstance() { return *mInstance; } virtual void release() PX_OVERRIDE; virtual PxOmniPvd* getOmniPvd() PX_OVERRIDE; virtual PxScene* createScene(const PxSceneDesc&) PX_OVERRIDE; void releaseSceneInternal(PxScene&); virtual PxU32 getNbScenes() const PX_OVERRIDE; virtual PxU32 getScenes(PxScene** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxRigidStatic* createRigidStatic(const PxTransform&) PX_OVERRIDE; virtual PxRigidDynamic* createRigidDynamic(const PxTransform&) PX_OVERRIDE; virtual PxArticulationReducedCoordinate* createArticulationReducedCoordinate() PX_OVERRIDE; virtual PxSoftBody* createSoftBody(PxCudaContextManager& cudaContextManager) PX_OVERRIDE; virtual PxHairSystem* createHairSystem(PxCudaContextManager& cudaContextManager) PX_OVERRIDE; virtual PxFEMCloth* createFEMCloth(PxCudaContextManager& cudaContextManager) PX_OVERRIDE; virtual PxPBDParticleSystem* createPBDParticleSystem(PxCudaContextManager& cudaContextManager, PxU32 maxNeighborhood) PX_OVERRIDE; virtual PxFLIPParticleSystem* createFLIPParticleSystem(PxCudaContextManager& cudaContextManager) PX_OVERRIDE; virtual PxMPMParticleSystem* createMPMParticleSystem(PxCudaContextManager& cudaContextManager) PX_OVERRIDE; virtual PxConstraint* createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) PX_OVERRIDE; virtual PxAggregate* createAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint) PX_OVERRIDE; virtual PxShape* createShape(const PxGeometry&, PxMaterial*const *, PxU16, bool, PxShapeFlags shapeFlags) PX_OVERRIDE; virtual PxShape* createShape(const PxGeometry&, PxFEMSoftBodyMaterial*const *, PxU16, bool, PxShapeFlags shapeFlags) PX_OVERRIDE; virtual PxShape* createShape(const PxGeometry&, PxFEMClothMaterial*const *, PxU16, bool, PxShapeFlags shapeFlags) PX_OVERRIDE; virtual PxU32 getNbShapes() const PX_OVERRIDE; virtual PxU32 getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE; virtual PxMaterial* createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution) PX_OVERRIDE; virtual PxU32 getNbMaterials() const PX_OVERRIDE; virtual PxU32 getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxFEMSoftBodyMaterial* createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction) PX_OVERRIDE; virtual PxU32 getNbFEMSoftBodyMaterials() const PX_OVERRIDE; virtual PxU32 getFEMSoftBodyMaterials(PxFEMSoftBodyMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxFEMClothMaterial* createFEMClothMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal thickness) PX_OVERRIDE; virtual PxU32 getNbFEMClothMaterials() const PX_OVERRIDE; virtual PxU32 getFEMClothMaterials(PxFEMClothMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxPBDMaterial* createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient, PxReal gravityScale) PX_OVERRIDE; virtual PxU32 getNbPBDMaterials() const PX_OVERRIDE; virtual PxU32 getPBDMaterials(PxPBDMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxFLIPMaterial* createFLIPMaterial(PxReal friction, PxReal damping, PxReal maxVelocity, PxReal viscosity, PxReal gravityScale) PX_OVERRIDE; virtual PxU32 getNbFLIPMaterials() const PX_OVERRIDE; virtual PxU32 getFLIPMaterials(PxFLIPMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxMPMMaterial* createMPMMaterial(PxReal friction, PxReal damping, PxReal maxVelocity, bool isPlastic, PxReal youngsModulus, PxReal poissons, PxReal hardening, PxReal criticalCompression, PxReal criticalStretch, PxReal tensileDamageSensitivity, PxReal compressiveDamageSensitivity, PxReal attractiveForceResidual, PxReal gravityScale) PX_OVERRIDE; virtual PxU32 getNbMPMMaterials() const PX_OVERRIDE; virtual PxU32 getMPMMaterials(PxMPMMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxTriangleMesh* createTriangleMesh(PxInputStream&) PX_OVERRIDE; virtual PxU32 getNbTriangleMeshes() const PX_OVERRIDE; virtual PxU32 getTriangleMeshes(PxTriangleMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxTetrahedronMesh* createTetrahedronMesh(PxInputStream&) PX_OVERRIDE; virtual PxU32 getNbTetrahedronMeshes() const PX_OVERRIDE; virtual PxU32 getTetrahedronMeshes(PxTetrahedronMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const PX_OVERRIDE; virtual PxSoftBodyMesh* createSoftBodyMesh(PxInputStream&) PX_OVERRIDE; virtual PxHeightField* createHeightField(PxInputStream& stream) PX_OVERRIDE; virtual PxU32 getNbHeightFields() const PX_OVERRIDE; virtual PxU32 getHeightFields(PxHeightField** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxConvexMesh* createConvexMesh(PxInputStream&) PX_OVERRIDE; virtual PxU32 getNbConvexMeshes() const PX_OVERRIDE; virtual PxU32 getConvexMeshes(PxConvexMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxBVH* createBVH(PxInputStream&) PX_OVERRIDE; virtual PxU32 getNbBVHs() const PX_OVERRIDE; virtual PxU32 getBVHs(PxBVH** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxParticleBuffer* createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager) PX_OVERRIDE; virtual PxParticleAndDiffuseBuffer* createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager) PX_OVERRIDE; virtual PxParticleClothBuffer* createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager) PX_OVERRIDE; virtual PxParticleRigidBuffer* createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager) PX_OVERRIDE; #if PX_SUPPORT_GPU_PHYSX void registerPhysXIndicatorGpuClient(); void unregisterPhysXIndicatorGpuClient(); #else PX_FORCE_INLINE void registerPhysXIndicatorGpuClient() {} PX_FORCE_INLINE void unregisterPhysXIndicatorGpuClient() {} #endif virtual PxPruningStructure* createPruningStructure(PxRigidActor*const* actors, PxU32 nbActors) PX_OVERRIDE; virtual const PxTolerancesScale& getTolerancesScale() const PX_OVERRIDE; virtual PxFoundation& getFoundation() PX_OVERRIDE; PX_INLINE NpScene* getScene(PxU32 i) const { return mSceneArray[i]; } PX_INLINE PxU32 getNumScenes() const { return mSceneArray.size(); } virtual void registerDeletionListener(PxDeletionListener& observer, const PxDeletionEventFlags& deletionEvents, bool restrictedObjectSet) PX_OVERRIDE; virtual void unregisterDeletionListener(PxDeletionListener& observer) PX_OVERRIDE; virtual void registerDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) PX_OVERRIDE; virtual void unregisterDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) PX_OVERRIDE; void notifyDeletionListeners(const PxBase*, void* userData, PxDeletionEventFlag::Enum deletionEvent); PX_FORCE_INLINE void notifyDeletionListenersUserRelease(const PxBase* b, void* userData) { notifyDeletionListeners(b, userData, PxDeletionEventFlag::eUSER_RELEASE); } PX_FORCE_INLINE void notifyDeletionListenersMemRelease(const PxBase* b, void* userData) { notifyDeletionListeners(b, userData, PxDeletionEventFlag::eMEMORY_RELEASE); } virtual PxInsertionCallback& getPhysicsInsertionCallback() PX_OVERRIDE { return mObjectInsertion; } bool sendMaterialTable(NpScene&); NpMaterialManager<NpMaterial>& getMaterialManager() { return mMasterMaterialManager; } #if PX_SUPPORT_GPU_PHYSX NpMaterialManager<NpFEMSoftBodyMaterial>& getFEMSoftBodyMaterialManager() { return mMasterFEMSoftBodyMaterialManager; } NpMaterialManager<NpPBDMaterial>& getPBDMaterialManager() { return mMasterPBDMaterialManager; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpMaterialManager<NpFEMClothMaterial>& getFEMClothMaterialManager() { return mMasterFEMClothMaterialManager; } NpMaterialManager<NpFLIPMaterial>& getFLIPMaterialManager() { return mMasterFLIPMaterialManager; } NpMaterialManager<NpMPMMaterial>& getMPMMaterialManager() { return mMasterMPMMaterialManager; } #endif #endif NpMaterial* addMaterial(NpMaterial* np); void removeMaterialFromTable(NpMaterial&); void updateMaterial(NpMaterial&); #if PX_SUPPORT_GPU_PHYSX NpFEMSoftBodyMaterial* addMaterial(NpFEMSoftBodyMaterial* np); void removeMaterialFromTable(NpFEMSoftBodyMaterial&); void updateMaterial(NpFEMSoftBodyMaterial&); NpPBDMaterial* addMaterial(NpPBDMaterial* np); void removeMaterialFromTable(NpPBDMaterial&); void updateMaterial(NpPBDMaterial&); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFEMClothMaterial* addMaterial(NpFEMClothMaterial* np); void removeMaterialFromTable(NpFEMClothMaterial&); void updateMaterial(NpFEMClothMaterial&); NpFLIPMaterial* addMaterial(NpFLIPMaterial* np); void removeMaterialFromTable(NpFLIPMaterial&); void updateMaterial(NpFLIPMaterial&); NpMPMMaterial* addMaterial(NpMPMMaterial* np); void removeMaterialFromTable(NpMPMMaterial&); void updateMaterial(NpMPMMaterial&); #endif #endif static void initOffsetTables(PxvOffsetTable& pxvOffsetTable); static bool apiReentryLock; #if PX_SUPPORT_OMNI_PVD OmniPvdPxSampler* mOmniPvdSampler; PxOmniPvd* mOmniPvd; #endif private: typedef PxCoalescedHashMap<PxDeletionListener*, NpDelListenerEntry*> DeletionListenerMap; PxArray<NpScene*> mSceneArray; Sc::Physics mPhysics; NpMaterialManager<NpMaterial> mMasterMaterialManager; #if PX_SUPPORT_GPU_PHYSX NpMaterialManager<NpFEMSoftBodyMaterial> mMasterFEMSoftBodyMaterialManager; NpMaterialManager<NpPBDMaterial> mMasterPBDMaterialManager; #endif NpPhysicsInsertionCallback mObjectInsertion; struct MeshDeletionListener: public Gu::MeshFactoryListener { void onMeshFactoryBufferRelease(const PxBase* object, PxType type) { PX_UNUSED(type); NpPhysics::getInstance().notifyDeletionListeners(object, NULL, PxDeletionEventFlag::eMEMORY_RELEASE); } }; PxMutex mDeletionListenerMutex; DeletionListenerMap mDeletionListenerMap; MeshDeletionListener mDeletionMeshListener; bool mDeletionListenersExist; PxMutex mSceneAndMaterialMutex; // guarantees thread safety for API calls related to scene and material containers PxFoundation& mFoundation; #if PX_SUPPORT_GPU_PHYSX PhysXIndicator mPhysXIndicator; PxU32 mNbRegisteredGpuClients; PxMutex mPhysXIndicatorMutex; #endif #if PX_SUPPORT_PVD physx::pvdsdk::PsPvd* mPvd; Vd::PvdPhysicsClient* mPvdPhysicsClient; #endif static PxU32 mRefCount; static NpPhysics* mInstance; friend class NpCollection; #if PX_SUPPORT_OMNI_PVD public: class OmniPvdListener : public physx::NpFactoryListener { public: virtual void onMeshFactoryBufferRelease(const PxBase*, PxType) {} virtual void onObjectAdd(const PxBase*); virtual void onObjectRemove(const PxBase*); } mOmniPvdListener; private: #endif // GW: these must be the last defined members for now. Otherwise it appears to mess up the offsets // expected when linking SDK dlls against unit tests due to differing values of PX_ENABLE_FEATURES_UNDER_CONSTRUCTION... // this warrants further investigation and hopefully a better solution #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpMaterialManager<NpFEMClothMaterial> mMasterFEMClothMaterialManager; NpMaterialManager<NpFLIPMaterial> mMasterFLIPMaterialManager; NpMaterialManager<NpMPMMaterial> mMasterMPMMaterialManager; #endif #endif }; template <> class NpMaterialAccessor<NpMaterial> { public: static NpMaterialManager<NpMaterial>& getMaterialManager(NpPhysics& physics) { return physics.getMaterialManager(); } }; #if PX_SUPPORT_GPU_PHYSX template <> class NpMaterialAccessor<NpFEMSoftBodyMaterial> { public: static NpMaterialManager<NpFEMSoftBodyMaterial>& getMaterialManager(NpPhysics& physics) { return physics.getFEMSoftBodyMaterialManager(); } }; template <> class NpMaterialAccessor<NpPBDMaterial> { public: static NpMaterialManager<NpPBDMaterial>& getMaterialManager(NpPhysics& physics) { return physics.getPBDMaterialManager(); } }; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION template <> class NpMaterialAccessor<NpFEMClothMaterial> { public: static NpMaterialManager<NpFEMClothMaterial>& getMaterialManager(NpPhysics& physics) { return physics.getFEMClothMaterialManager(); } }; template <> class NpMaterialAccessor<NpFLIPMaterial> { public: static NpMaterialManager<NpFLIPMaterial>& getMaterialManager(NpPhysics& physics) { return physics.getFLIPMaterialManager(); } }; template <> class NpMaterialAccessor<NpMPMMaterial> { public: static NpMaterialManager<NpMPMMaterial>& getMaterialManager(NpPhysics& physics) { return physics.getMPMMaterialManager(); } }; #endif #endif #if PX_VC #pragma warning(pop) #endif } #endif
18,160
C
42.035545
359
0.77109
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationReducedCoordinate.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 "NpArticulationReducedCoordinate.h" #include "NpArticulationTendon.h" #include "NpArticulationSensor.h" #include "DyFeatherstoneArticulation.h" #include "ScArticulationSim.h" #include "ScConstraintSim.h" #include "foundation/PxAlignedMalloc.h" #include "foundation/PxPool.h" #include "PxPvdDataStream.h" #include "NpAggregate.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; void PxArticulationCache::release() { PxcScratchAllocator* scratchAlloc = reinterpret_cast<PxcScratchAllocator*>(scratchAllocator); PX_DELETE(scratchAlloc); scratchAllocator = NULL; PX_FREE(scratchMemory); PX_FREE_THIS; } // PX_SERIALIZATION NpArticulationReducedCoordinate* NpArticulationReducedCoordinate::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationReducedCoordinate* obj = PX_PLACEMENT_NEW(address, NpArticulationReducedCoordinate(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpArticulationReducedCoordinate); obj->importExtraData(context); obj->resolveReferences(context); return obj; } void NpArticulationReducedCoordinate::preExportDataReset() { //for now, no support for loop joint serialization PxArray<NpConstraint*> emptyLoopJoints; PxMemCopy(&mLoopJoints, &emptyLoopJoints, sizeof(PxArray<NpConstraint*>)); } //~PX_SERIALIZATION NpArticulationReducedCoordinate::NpArticulationReducedCoordinate() : PxArticulationReducedCoordinate(PxConcreteType::eARTICULATION_REDUCED_COORDINATE, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), NpBase(NpType::eARTICULATION), mNumShapes(0), mAggregate(NULL), mName(NULL), mCacheVersion(0), mTopologyChanged(false) { } void NpArticulationReducedCoordinate::setArticulationFlags(PxArticulationFlags flags) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setArticulationFlags() not allowed while simulation is running. Call will be ignored."); scSetArticulationFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, articulationFlags, static_cast<const PxArticulationReducedCoordinate&>(*this), flags); } void NpArticulationReducedCoordinate::setArticulationFlag(PxArticulationFlag::Enum flag, bool value) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setArticulationFlag() not allowed while simulation is running. Call will be ignored."); PxArticulationFlags flags = mCore.getArticulationFlags(); if(value) flags |= flag; else flags &= (~flag); scSetArticulationFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, articulationFlags, static_cast<const PxArticulationReducedCoordinate&>(*this), flags); } PxArticulationFlags NpArticulationReducedCoordinate::getArticulationFlags() const { NP_READ_CHECK(getNpScene()); return mCore.getArticulationFlags(); } PxU32 NpArticulationReducedCoordinate::getDofs() const { NP_READ_CHECK(getNpScene()); // core will check if in scene and return 0xFFFFFFFF if not. return mCore.getDofs(); } PxArticulationCache* NpArticulationReducedCoordinate::createCache() const { NP_READ_CHECK(getNpScene()); // doesn't modify the scene, only reads PX_CHECK_AND_RETURN_NULL(getNpScene(), "PxArticulationReducedCoordinate::createCache: Articulation must be in a scene."); PxArticulationCache* cache = mCore.createCache(); if (cache) cache->version = mCacheVersion; return cache; } PxU32 NpArticulationReducedCoordinate::getCacheDataSize() const { NP_READ_CHECK(getNpScene()); // doesn't modify the scene, only reads // core will check if in scene and return 0xFFFFFFFF if not. return mCore.getCacheDataSize(); } void NpArticulationReducedCoordinate::zeroCache(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); // doesn't modify the scene, only reads PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::zeroCache: Articulation must be in a scene."); // need to check cache version as correct cache size is required for zeroing PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::zeroCache: cache is invalid, articulation configuration has changed! "); return mCore.zeroCache(cache); } void NpArticulationReducedCoordinate::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags, bool autowake) { PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::applyCache: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::applyCache: cache is invalid, articulation configuration has changed! "); PX_CHECK_AND_RETURN(!(getScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API), "PxArticulationReducedCoordinate::applyCache : it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); //if we try to do a bulk op when sim is running, return with error if (getNpScene()->getSimulationStage() != Sc::SimulationStage::eCOMPLETE) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::applyCache() not allowed while simulation is running. Call will be ignored."); return; } if (!(getScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API)) { const bool forceWake = mCore.applyCache(cache, flags); if (flags & (PxArticulationCacheFlag::ePOSITION | PxArticulationCacheFlag::eROOT_TRANSFORM)) { const PxU32 linkCount = mArticulationLinks.size(); //KS - the below code forces contact managers to be updated/cached data to be dropped and //shape transforms to be updated. for (PxU32 i = 0; i < linkCount; ++i) { NpArticulationLink* link = mArticulationLinks[i]; //in the lowlevel articulation, we have already updated bodyCore's body2World const PxTransform internalPose = link->getCore().getBody2World(); link->scSetBody2World(internalPose); } } wakeUpInternal(forceWake, autowake); } } void NpArticulationReducedCoordinate::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags) const { PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::copyInternalStateToCache: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::copyInternalStateToCache: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::copyInternalStateToCache() not allowed while simulation is running. Call will be ignored."); PX_CHECK_AND_RETURN(!(getScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API), "PxArticulationReducedCoordinate::copyInternalStateToCache : it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); const bool isGpuSimEnabled = getNpScene()->getFlags() & PxSceneFlag::eENABLE_GPU_DYNAMICS; mCore.copyInternalStateToCache(cache, flags, isGpuSimEnabled); } void NpArticulationReducedCoordinate::packJointData(const PxReal* maximum, PxReal* reduced) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::packJointData: Articulation must be in a scene."); mCore.packJointData(maximum, reduced); } void NpArticulationReducedCoordinate::unpackJointData(const PxReal* reduced, PxReal* maximum) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::unpackJointData: Articulation must be in a scene."); mCore.unpackJointData(reduced, maximum); } void NpArticulationReducedCoordinate::commonInit() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::commonInit: Articulation must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::commonInit() not allowed while simulation is running. Call will be ignored."); mCore.commonInit(); } void NpArticulationReducedCoordinate::computeGeneralizedGravityForce(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeGeneralizedGravityForce: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version ==mCacheVersion, "PxArticulationReducedCoordinate::computeGeneralizedGravityForce: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeGeneralizedGravityForce() not allowed while simulation is running. Call will be ignored."); mCore.computeGeneralizedGravityForce(cache); } void NpArticulationReducedCoordinate::computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeCoriolisAndCentrifugalForce: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeCoriolisAndCentrifugalForce: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeCoriolisAndCentrifugalForce() not allowed while simulation is running. Call will be ignored."); mCore.computeCoriolisAndCentrifugalForce(cache); } void NpArticulationReducedCoordinate::computeGeneralizedExternalForce(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeGeneralizedExternalForce: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeGeneralizedExternalForce: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeGeneralizedExternalForce() not allowed while simulation is running. Call will be ignored."); mCore.computeGeneralizedExternalForce(cache); } void NpArticulationReducedCoordinate::computeJointAcceleration(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeJointAcceleration: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeJointAcceleration: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeJointAcceleration() not allowed while simulation is running. Call will be ignored."); mCore.computeJointAcceleration(cache); } void NpArticulationReducedCoordinate::computeJointForce(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeJointForce: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeJointForce: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeJointForce() not allowed while simulation is running. Call will be ignored."); mCore.computeJointForce(cache); } void NpArticulationReducedCoordinate::computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeDenseJacobian: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeDenseJacobian: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeDenseJacobian() not allowed while simulation is running. Call will be ignored."); mCore.computeDenseJacobian(cache, nRows, nCols); } void NpArticulationReducedCoordinate::computeCoefficientMatrix(PxArticulationCache& cache) const { NpScene* npScene = getNpScene(); NP_READ_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxArticulationReducedCoordinate::computeCoefficientMatrix: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeCoefficientMatrix: cache is invalid, articulation configuration has changed! "); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationReducedCoordinate::computeCoefficientMatrix() not allowed while simulation is running. Call will be ignored."); npScene->updateConstants(mLoopJoints); mCore.computeCoefficientMatrix(cache); } bool NpArticulationReducedCoordinate::computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* const jointTorque, const PxU32 maxIter) const { if (!getNpScene()) return PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxArticulationReducedCoordinate::computeLambda: Articulation must be in a scene."); NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::computeLambda() not allowed while simulation is running. Call will be ignored.", false); if (cache.version != mCacheVersion) return PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxArticulationReducedCoordinate::computeLambda: cache is invalid, articulation configuration has changed!"); return mCore.computeLambda(cache, initialState, jointTorque, getScene()->getGravity(), maxIter); } void NpArticulationReducedCoordinate::computeGeneralizedMassMatrix(PxArticulationCache& cache) const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::computeGeneralizedMassMatrix: Articulation must be in a scene."); PX_CHECK_AND_RETURN(cache.version == mCacheVersion, "PxArticulationReducedCoordinate::computeGeneralizedMassMatrix: cache is invalid, articulation configuration has changed!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::computeGeneralizedMassMatrix() not allowed while simulation is running. Call will be ignored."); mCore.computeGeneralizedMassMatrix(cache); } void NpArticulationReducedCoordinate::addLoopJoint(PxConstraint* joint) { NP_WRITE_CHECK(getNpScene()); #if PX_CHECKED PxRigidActor* actor0; PxRigidActor* actor1; joint->getActors(actor0, actor1); PxArticulationLink* link0 = NULL; PxArticulationLink* link1 = NULL; if(actor0 && actor0->getConcreteType()==PxConcreteType::eARTICULATION_LINK) link0 = static_cast<PxArticulationLink*>(actor0); if(actor1 && actor1->getConcreteType()==PxConcreteType::eARTICULATION_LINK) link1 = static_cast<PxArticulationLink*>(actor1); PX_CHECK_AND_RETURN((link0 || link1), "PxArticulationReducedCoordinate::addLoopJoint : at least one of the PxRigidActors need to be PxArticulationLink!"); PxArticulationReducedCoordinate* base0 = NULL; PxArticulationReducedCoordinate* base1 = NULL; if (link0) base0 = &link0->getArticulation(); if (link1) base1 = &link1->getArticulation(); PX_CHECK_AND_RETURN((base0 == this || base1 == this), "PxArticulationReducedCoordinate::addLoopJoint : at least one of the PxArticulationLink belongs to this articulation!"); #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::addLoopJoint() not allowed while simulation is running. Call will be ignored.") const PxU32 size = mLoopJoints.size(); if (size >= mLoopJoints.capacity()) mLoopJoints.reserve(size * 2 + 1); NpConstraint* constraint = static_cast<NpConstraint*>(joint); mLoopJoints.pushBack(constraint); Sc::ArticulationSim* scArtSim = mCore.getSim(); Sc::ConstraintSim* cSim = constraint->getCore().getSim(); if(scArtSim) scArtSim->addLoopConstraint(cSim); } void NpArticulationReducedCoordinate::removeLoopJoint(PxConstraint* joint) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::removeLoopJoint() not allowed while simulation is running. Call will be ignored.") NpConstraint* constraint = static_cast<NpConstraint*>(joint); mLoopJoints.findAndReplaceWithLast(constraint); Sc::ArticulationSim* scArtSim = mCore.getSim(); Sc::ConstraintSim* cSim = constraint->getCore().getSim(); scArtSim->removeLoopConstraint(cSim); } PxU32 NpArticulationReducedCoordinate::getNbLoopJoints() const { NP_READ_CHECK(getNpScene()); return mLoopJoints.size(); } PxU32 NpArticulationReducedCoordinate::getLoopJoints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mLoopJoints.begin(), mLoopJoints.size()); } PxU32 NpArticulationReducedCoordinate::getCoefficientMatrixSize() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_NULL(getNpScene(), "PxArticulationReducedCoordinate::getCoefficientMatrixSize: Articulation must be in a scene."); // core will check if in scene and return 0xFFFFFFFF if not. return mCore.getCoefficientMatrixSize(); } void NpArticulationReducedCoordinate::setRootGlobalPose(const PxTransform& pose, bool autowake) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(!mArticulationLinks.empty(), "PxArticulationReducedCoordinate::setRootGlobalPose() called on empty articulation."); PX_CHECK_AND_RETURN(pose.isValid(), "PxArticulationReducedCoordinate::setRootGlobalPose pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setRootGlobalPose() not allowed while simulation is running. Call will be ignored."); NpArticulationLink* root = mArticulationLinks[0]; root->setGlobalPoseInternal(pose, autowake); } PxTransform NpArticulationReducedCoordinate::getRootGlobalPose() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(!mArticulationLinks.empty(), "PxArticulationReducedCoordinate::getRootGlobalPose() called on empty articulation.", PxTransform(PxIdentity)); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getRootGlobalPose() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxTransform(PxIdentity)); NpArticulationLink* root = mArticulationLinks[0]; return root->getGlobalPose(); } void NpArticulationReducedCoordinate::setRootLinearVelocity(const PxVec3& linearVelocity, bool autowake) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(!mArticulationLinks.empty(), "PxArticulationReducedCoordinate::setRootLinearVelocity() called on empty articulation."); PX_CHECK_AND_RETURN(linearVelocity.isFinite(), "PxArticulationReducedCoordinate::setRootLinearVelocity velocity is not finite."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(getNpScene(), "PxArticulationReducedCoordinate::setRootLinearVelocity() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance(). Call will be ignored."); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::setRootLinearVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } NpArticulationLink* root = mArticulationLinks[0]; root->scSetLinearVelocity(linearVelocity); if(getNpScene()) { const bool forceWakeup = !(linearVelocity.isZero()); wakeUpInternal(forceWakeup, autowake); } } void NpArticulationReducedCoordinate::setRootAngularVelocity(const PxVec3& angularVelocity, bool autowake) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(!mArticulationLinks.empty(), "PxArticulationReducedCoordinate::setRootAngularVelocity() called on empty articulation."); PX_CHECK_AND_RETURN(angularVelocity.isFinite(), "PxArticulationReducedCoordinate::setRootAngularVelocity velocity is not finite."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(getNpScene(), "PxArticulationReducedCoordinate::setRootAngularVelocity() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance(). Call will be ignored."); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::setRootAngularVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } NpArticulationLink* root = mArticulationLinks[0]; root->scSetAngularVelocity(angularVelocity); if (getNpScene()) { const bool forceWakeup = !(angularVelocity.isZero()); wakeUpInternal(forceWakeup, autowake); } } PxVec3 NpArticulationReducedCoordinate::getRootLinearVelocity() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(!mArticulationLinks.empty(), "PxArticulationReducedCoordinate::getRootLinearVelocity() called on empty articulation.", PxVec3(0.0f)); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getRootLinearVelocity() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxVec3(0.f)); NpArticulationLink* root = mArticulationLinks[0]; return root->getLinearVelocity(); } PxVec3 NpArticulationReducedCoordinate::getRootAngularVelocity() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(!mArticulationLinks.empty(), "PxArticulationReducedCoordinate::getRootAngularVelocity() called on empty articulation.", PxVec3(0.0f)); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getRootAngularVelocity() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxVec3(0.f)); NpArticulationLink* root = mArticulationLinks[0]; return root->getAngularVelocity(); } PxSpatialVelocity NpArticulationReducedCoordinate::getLinkAcceleration(const PxU32 linkId) { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getLinkAcceleration: Articulation must be in a scene.", PxSpatialVelocity()); PX_CHECK_AND_RETURN_VAL(linkId < 64, "PxArticulationReducedCoordinate::getLinkAcceleration index is not valid.", PxSpatialVelocity()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getLinkAcceleration() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxSpatialVelocity()); const bool isGpuSimEnabled = (getNpScene()->getFlags() & PxSceneFlag::eENABLE_GPU_DYNAMICS) ? true : false; return mCore.getLinkAcceleration(linkId, isGpuSimEnabled); } PxU32 NpArticulationReducedCoordinate::getGpuArticulationIndex() { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getGpuArticulationIndex: Articulation must be in a scene.", 0xffffffff); if (getScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) return mCore.getGpuArticulationIndex(); return 0xffffffff; } PxArticulationSpatialTendon* NpArticulationReducedCoordinate::createSpatialTendon() { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::createSpatialTendon() not allowed while the articulation is in a scene. Call will be ignored."); return NULL; } void* tendonMem = PX_ALLOC(sizeof(NpArticulationSpatialTendon), "NpArticulationSpatialTendon"); PxMarkSerializedMemory(tendonMem, sizeof(NpArticulationSpatialTendon)); NpArticulationSpatialTendon* tendon = PX_PLACEMENT_NEW(tendonMem, NpArticulationSpatialTendon)(this); tendon->setHandle(mSpatialTendons.size()); mSpatialTendons.pushBack(tendon); return tendon; } void NpArticulationReducedCoordinate::removeSpatialTendonInternal(NpArticulationSpatialTendon* npTendon) { //we don't need to remove low-level tendon from the articulation sim because the only case the tendon can be removed is //when the whole articulation is removed from the scene and the ArticulationSim get destroyed getNpScene()->scRemoveArticulationSpatialTendon(*npTendon); } PxArticulationFixedTendon* NpArticulationReducedCoordinate::createFixedTendon() { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::createFixedTendon() not allowed while the articulation is in a scene. Call will be ignored."); return NULL; } void* tendonMem = PX_ALLOC(sizeof(NpArticulationFixedTendon), "NpArticulationFixedTendon"); PxMarkSerializedMemory(tendonMem, sizeof(NpArticulationFixedTendon)); NpArticulationFixedTendon* tendon = PX_PLACEMENT_NEW(tendonMem, NpArticulationFixedTendon)(this); tendon->setHandle(mFixedTendons.size()); mFixedTendons.pushBack(tendon); return tendon; } void NpArticulationReducedCoordinate::removeFixedTendonInternal(NpArticulationFixedTendon* npTendon) { //we don't need to remove low-level tendon from the articulation sim because the only case the tendon can be removed is //when the whole articulation is removed from the scene and the ArticulationSim get destroyed getNpScene()->scRemoveArticulationFixedTendon(*npTendon); } void NpArticulationReducedCoordinate::removeSensorInternal(NpArticulationSensor* npSensor) { //we don't need to remove low-level sensor from the articulation sim because the only case the tendon can be removed is //when the whole articulation is removed from the scene and the ArticulationSim get destroyed getNpScene()->scRemoveArticulationSensor(*npSensor); } PxArticulationSensor* NpArticulationReducedCoordinate::createSensor(PxArticulationLink* link, const PxTransform& relativePose) { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::createSensor() not allowed while the articulation is in a scene. Call will be ignored."); return NULL; } void* sensorMem = PX_ALLOC(sizeof(NpArticulationSensor), "NpArticulationSensor"); PxMarkSerializedMemory(sensorMem, sizeof(NpArticulationSensor)); NpArticulationSensor* sensor = PX_PLACEMENT_NEW(sensorMem, NpArticulationSensor)(link, relativePose); sensor->setHandle(mSensors.size()); mSensors.pushBack(sensor); mTopologyChanged = true; return sensor; } void NpArticulationReducedCoordinate::releaseSensor(PxArticulationSensor& sensor) { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::releaseSensor() not allowed while the articulation is in a scene. Call will be ignored."); return; } NpArticulationSensor* npSensor = static_cast<NpArticulationSensor*>(&sensor); const PxU32 handle = npSensor->getHandle(); PX_CHECK_AND_RETURN(handle < mSensors.size() && mSensors[handle] == npSensor, "PxArticulationReducedCoordinate::releaseSensor: Attempt to release sensor that is not part of this articulation."); mSensors.back()->setHandle(handle); mSensors.replaceWithLast(handle); npSensor->~NpArticulationSensor(); if (npSensor->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(npSensor); mTopologyChanged = true; } PxU32 NpArticulationReducedCoordinate::getSensors(PxArticulationSensor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mSensors.begin(), mSensors.size()); } PxU32 NpArticulationReducedCoordinate::getNbSensors() { return mSensors.size(); } NpArticulationSensor* NpArticulationReducedCoordinate::getSensor(const PxU32 index) const { return mSensors[index]; } PxU32 NpArticulationReducedCoordinate::getSpatialTendons(PxArticulationSpatialTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mSpatialTendons.begin(), mSpatialTendons.size()); } PxU32 NpArticulationReducedCoordinate::getNbSpatialTendons() { return mSpatialTendons.size(); } NpArticulationSpatialTendon* NpArticulationReducedCoordinate::getSpatialTendon(const PxU32 index) const { return mSpatialTendons[index]; } PxU32 NpArticulationReducedCoordinate::getFixedTendons(PxArticulationFixedTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mFixedTendons.begin(), mFixedTendons.size()); } PxU32 NpArticulationReducedCoordinate::getNbFixedTendons() { return mFixedTendons.size(); } NpArticulationFixedTendon* NpArticulationReducedCoordinate::getFixedTendon(const PxU32 index) const { return mFixedTendons[index]; } void NpArticulationReducedCoordinate::updateKinematic(PxArticulationKinematicFlags flags) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::updateKinematic: Articulation must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::updateKinematic() not allowed while simulation is running. Call will be ignored."); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::updateKinematic(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } if(getNpScene()) { mCore.updateKinematic(flags); const PxU32 linkCount = mArticulationLinks.size(); //KS - the below code forces contact managers to be updated/cached data to be dropped and //shape transforms to be updated. for(PxU32 i = 0; i < linkCount; ++i) { NpArticulationLink* link = mArticulationLinks[i]; //in the lowlevel articulation, we have already updated bodyCore's body2World const PxTransform internalPose = link->getCore().getBody2World(); link->scSetBody2World(internalPose); } } } NpArticulationReducedCoordinate::~NpArticulationReducedCoordinate() { //release tendons for (PxU32 i = 0; i < mSpatialTendons.size(); ++i) { if (mSpatialTendons[i]) { mSpatialTendons[i]->~NpArticulationSpatialTendon(); if(mSpatialTendons[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(mSpatialTendons[i]); } } for (PxU32 i = 0; i < mFixedTendons.size(); ++i) { if (mFixedTendons[i]) { mFixedTendons[i]->~NpArticulationFixedTendon(); if(mFixedTendons[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(mFixedTendons[i]); } } for (PxU32 i = 0; i < mSensors.size(); ++i) { if (mSensors[i]) { mSensors[i]->~NpArticulationSensor(); if(mSensors[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(mSensors[i]); } } NpFactory::getInstance().onArticulationRelease(this); } PxArticulationJointReducedCoordinate* NpArticulationReducedCoordinate::createArticulationJoint(PxArticulationLink& parent, const PxTransform& parentFrame, PxArticulationLink& child, const PxTransform& childFrame) { return NpFactory::getInstance().createNpArticulationJointRC(static_cast<NpArticulationLink&>(parent), parentFrame, static_cast<NpArticulationLink&>(child), childFrame); } void NpArticulationReducedCoordinate::recomputeLinkIDs() { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::recomputeLinkIDs: Articulation must be in a scene."); if (!isAPIWriteForbidden()) { Sc::ArticulationSim* scArtSim = getCore().getSim(); if (scArtSim) { physx::NpArticulationLink*const* links = getLinks(); const PxU32 nbLinks = getNbLinks(); for (PxU32 i = 1; i < nbLinks; ++i) { physx::NpArticulationLink* link = links[i]; PxU32 cHandle = scArtSim->findBodyIndex(*link->getCore().getSim()); link->setLLIndex(cHandle); } } } } // PX_SERIALIZATION void NpArticulationReducedCoordinate::requiresObjects(PxProcessPxBaseCallback& c) { // Collect articulation links const PxU32 nbLinks = mArticulationLinks.size(); for (PxU32 i = 0; i < nbLinks; i++) c.process(*mArticulationLinks[i]); const PxU32 nbSensors = mSensors.size(); for (PxU32 i = 0; i < nbSensors; i++) c.process(*mSensors[i]); const PxU32 nbSpatialTendons = mSpatialTendons.size(); for (PxU32 i = 0; i < nbSpatialTendons; i++) c.process(*mSpatialTendons[i]); const PxU32 nbFixedTendons = mFixedTendons.size(); for (PxU32 i = 0; i < nbFixedTendons; i++) c.process(*mFixedTendons[i]); } void NpArticulationReducedCoordinate::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mArticulationLinks, stream); Cm::exportArray(mSpatialTendons, stream); Cm::exportArray(mFixedTendons, stream); Cm::exportArray(mSensors, stream); stream.writeName(mName); } void NpArticulationReducedCoordinate::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mArticulationLinks, context); Cm::importArray(mSpatialTendons, context); Cm::importArray(mFixedTendons, context); Cm::importArray(mSensors, context); context.readName(mName); } void NpArticulationReducedCoordinate::resolveReferences(PxDeserializationContext& context) { const PxU32 nbLinks = mArticulationLinks.size(); for (PxU32 i = 0; i < nbLinks; i++) { NpArticulationLink*& link = mArticulationLinks[i]; context.translatePxBase(link); } const PxU32 nbSensors = mSensors.size(); for (PxU32 i = 0; i < nbSensors; i++) { NpArticulationSensor*& sensor = mSensors[i]; context.translatePxBase(sensor); } const PxU32 nbSpatialTendons = mSpatialTendons.size(); for (PxU32 i = 0; i < nbSpatialTendons; i++) { NpArticulationSpatialTendon*& spatialTendon = mSpatialTendons[i]; context.translatePxBase(spatialTendon); } const PxU32 nbFixedTendons = mFixedTendons.size(); for (PxU32 i = 0; i < nbFixedTendons; i++) { NpArticulationFixedTendon*& fixedTendon = mFixedTendons[i]; context.translatePxBase(fixedTendon); } mAggregate = NULL; } // ~PX_SERIALIZATION void NpArticulationReducedCoordinate::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationReducedCoordinate::release() not allowed while simulation is running. Call will be ignored."); NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationReducedCoordinate::userData); //!!!AL TODO: Order should not matter in this case. Optimize by having a path which does not restrict release to leaf links or // by using a more advanced data structure PxU32 idx = 0; while (mArticulationLinks.size()) { idx = idx % mArticulationLinks.size(); if (mArticulationLinks[idx]->getNbChildren() == 0) { mArticulationLinks[idx]->releaseInternal(); // deletes joint, link and removes link from list } else { idx++; } } if (npScene) { npScene->removeArticulationTendons(*this); npScene->removeArticulationSensors(*this); npScene->scRemoveArticulation(*this); npScene->removeFromArticulationList(*this); } mArticulationLinks.clear(); NpDestroyArticulation(this); } PxArticulationLink* NpArticulationReducedCoordinate::createLink(PxArticulationLink* parent, const PxTransform& pose) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::createLink() not allowed while the articulation is in a scene. Call will be ignored."); return NULL; } PX_CHECK_AND_RETURN_NULL(pose.isSane(), "PxArticulationReducedCoordinate::createLink: pose is not valid."); if (parent && mArticulationLinks.empty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::createLink: Root articulation link must have NULL parent pointer!"); return NULL; } // Check if parent is in same articulation is done internally for checked builds if (!parent && !mArticulationLinks.empty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationReducedCoordinate::createLink: Non-root articulation link must have valid parent pointer!"); return NULL; } NpArticulationLink* parentLink = static_cast<NpArticulationLink*>(parent); NpArticulationLink* link = static_cast<NpArticulationLink*>(NpFactory::getInstance().createArticulationLink(*this, parentLink, pose.getNormalized())); if (link) { addToLinkList(*link); mTopologyChanged = true; } return link; } void NpArticulationReducedCoordinate::setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(positionIters > 0, "PxArticulationReducedCoordinate::setSolverIterationCount: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(positionIters <= 255, "PxArticulationReducedCoordinate::setSolverIterationCount: positionIters must be no greater than 255!"); PX_CHECK_AND_RETURN(velocityIters <= 255, "PxArticulationReducedCoordinate::setSolverIterationCount: velocityIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored."); scSetSolverIterationCounts((velocityIters & 0xff) << 8 | (positionIters & 0xff)); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, positionIterations, static_cast<const PxArticulationReducedCoordinate&>(*this), positionIters); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, velocityIterations, static_cast<const PxArticulationReducedCoordinate&>(*this), velocityIters); OMNI_PVD_WRITE_SCOPE_END } void NpArticulationReducedCoordinate::getSolverIterationCounts(PxU32& positionIters, PxU32& velocityIters) const { NP_READ_CHECK(getNpScene()); const PxU16 x = mCore.getSolverIterationCounts(); velocityIters = PxU32(x >> 8); positionIters = PxU32(x & 0xff); } void NpArticulationReducedCoordinate::setGlobalPose() { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::setGlobalPose: Articulation must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setGlobalPose() not allowed while simulation is running. Call will be ignored."); PX_ASSERT(!isAPIWriteForbidden()); mCore.setGlobalPose(); //This code is force PVD to update other links position { physx::NpArticulationLink*const* links = getLinks(); const PxU32 nbLinks = getNbLinks(); for (PxU32 i = 1; i < nbLinks; ++i) { physx::NpArticulationLink* link = links[i]; //in the lowlevel articulation, we have already updated bodyCore's body2World const PxTransform internalPose = link->getCore().getBody2World(); link->scSetBody2World(internalPose); } } } bool NpArticulationReducedCoordinate::isSleeping() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::isSleeping: Articulation must be in a scene.", true); PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::isSleeping() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().", true); return mCore.isSleeping(); } void NpArticulationReducedCoordinate::setSleepThreshold(PxReal threshold) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setSleepThreshold() not allowed while simulation is running. Call will be ignored."); scSetSleepThreshold(threshold); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, sleepThreshold, static_cast<const PxArticulationReducedCoordinate&>(*this), threshold); } PxReal NpArticulationReducedCoordinate::getSleepThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getSleepThreshold(); } void NpArticulationReducedCoordinate::setStabilizationThreshold(PxReal threshold) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setStabilizationThreshold() not allowed while simulation is running. Call will be ignored."); scSetFreezeThreshold(threshold); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, stabilizationThreshold, static_cast<const PxArticulationReducedCoordinate&>(*this), threshold); } PxReal NpArticulationReducedCoordinate::getStabilizationThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getFreezeThreshold(); } void NpArticulationReducedCoordinate::setWakeCounter(PxReal wakeCounterValue) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(getNpScene(), "PxArticulationReducedCoordinate::setWakeCounter() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance(). Call will be ignored."); for (PxU32 i = 0; i < mArticulationLinks.size(); i++) { mArticulationLinks[i]->scSetWakeCounter(wakeCounterValue); } scSetWakeCounter(wakeCounterValue); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, wakeCounter, static_cast<const PxArticulationReducedCoordinate&>(*this), wakeCounterValue); } PxReal NpArticulationReducedCoordinate::getWakeCounter() const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getWakeCounter() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance().", 0.0f); return mCore.getWakeCounter(); } // follows D6 wakeup logic and is used for joint and tendon autowake void NpArticulationReducedCoordinate::autoWakeInternal(void) { PxReal wakeCounter = mCore.getWakeCounter(); if (wakeCounter < getNpScene()->getWakeCounterResetValueInternal()) { wakeCounter = getNpScene()->getWakeCounterResetValueInternal(); for (PxU32 i = 0; i < mArticulationLinks.size(); i++) { mArticulationLinks[i]->scWakeUpInternal(wakeCounter); } scWakeUpInternal(wakeCounter); } } // Follows RB wakeup logic. If autowake is true, increase wakeup counter to at least the scene reset valu // If forceWakeUp is true, wakeup and leave wakeup counter unchanged, so that articulation goes to sleep // again if wakecounter was zero at forceWakeup. The value of forceWakeup has no effect if autowake is true. void NpArticulationReducedCoordinate::wakeUpInternal(bool forceWakeUp, bool autowake) { PX_ASSERT(getNpScene()); PxReal wakeCounterResetValue = getNpScene()->getWakeCounterResetValueInternal(); PxReal wakeCounter = mCore.getWakeCounter(); bool needsWakingUp = isSleeping() && (autowake || forceWakeUp); if (autowake && (wakeCounter < wakeCounterResetValue)) { wakeCounter = wakeCounterResetValue; needsWakingUp = true; } if (needsWakingUp) { for (PxU32 i = 0; i < mArticulationLinks.size(); i++) { mArticulationLinks[i]->scWakeUpInternal(wakeCounter); } scWakeUpInternal(wakeCounter); } } void NpArticulationReducedCoordinate::wakeUp() { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::wakeUp: Articulation must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(getNpScene(), "PxArticulationReducedCoordinate::wakeUp() not allowed while simulation is running, except in a split simulation in-between PxScene::fetchCollision() and PxScene::advance(). Call will be ignored."); for (PxU32 i = 0; i < mArticulationLinks.size(); i++) { mArticulationLinks[i]->scWakeUpInternal(getNpScene()->getWakeCounterResetValueInternal()); } PX_ASSERT(getNpScene()); // only allowed for an object in a scene scWakeUpInternal(getNpScene()->getWakeCounterResetValueInternal()); } void NpArticulationReducedCoordinate::putToSleep() { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene(), "PxArticulationReducedCoordinate::putToSleep: Articulation must be in a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::putToSleep() not allowed while simulation is running. Call will be ignored."); for (PxU32 i = 0; i < mArticulationLinks.size(); i++) { mArticulationLinks[i]->scPutToSleepInternal(); } PX_ASSERT(!isAPIWriteForbidden()); mCore.putToSleep(); } void NpArticulationReducedCoordinate::setMaxCOMLinearVelocity(const PxReal maxLinearVelocity) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setMaxCOMLinearVelocity() not allowed while simulation is running. Call will be ignored."); scSetMaxLinearVelocity(maxLinearVelocity); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, maxLinearVelocity, static_cast<const PxArticulationReducedCoordinate&>(*this), maxLinearVelocity); } PxReal NpArticulationReducedCoordinate::getMaxCOMLinearVelocity() const { NP_READ_CHECK(getNpScene()); return mCore.getMaxLinearVelocity(); } void NpArticulationReducedCoordinate::setMaxCOMAngularVelocity(const PxReal maxAngularVelocity) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxArticulationReducedCoordinate::setMaxCOMAngularVelocity() not allowed while simulation is running. Call will be ignored."); scSetMaxAngularVelocity(maxAngularVelocity); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, maxAngularVelocity, static_cast<const PxArticulationReducedCoordinate&>(*this), maxAngularVelocity); } PxReal NpArticulationReducedCoordinate::getMaxCOMAngularVelocity() const { NP_READ_CHECK(getNpScene()); return mCore.getMaxAngularVelocity(); } PxU32 NpArticulationReducedCoordinate::getNbLinks() const { NP_READ_CHECK(getNpScene()); return mArticulationLinks.size(); } PxU32 NpArticulationReducedCoordinate::getLinks(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mArticulationLinks.begin(), mArticulationLinks.size()); } PxU32 NpArticulationReducedCoordinate::getNbShapes() const { NP_READ_CHECK(getNpScene()); return mNumShapes; } PxBounds3 NpArticulationReducedCoordinate::getWorldBounds(float inflation) const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationReducedCoordinate::getWorldBounds() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxBounds3::empty()); PxBounds3 bounds = PxBounds3::empty(); for (PxU32 i = 0; i < mArticulationLinks.size(); i++) { bounds.include(mArticulationLinks[i]->getWorldBounds()); } PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } PxAggregate* NpArticulationReducedCoordinate::getAggregate() const { NP_READ_CHECK(getNpScene()); return mAggregate; } void NpArticulationReducedCoordinate::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); mName = debugName; } const char* NpArticulationReducedCoordinate::getName() const { NP_READ_CHECK(getNpScene()); return mName; } NpArticulationLink* NpArticulationReducedCoordinate::getRoot() { if (!mArticulationLinks.size()) return NULL; PX_ASSERT(mArticulationLinks[0]->getInboundJoint() == NULL); return mArticulationLinks[0]; } void NpArticulationReducedCoordinate::setAggregate(PxAggregate* a) { mAggregate = static_cast<NpAggregate*>(a); }
49,981
C++
39.536902
286
0.786319
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPruningStructure.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 "NpPruningStructure.h" #include "GuAABBTree.h" #include "GuAABBTreeNode.h" #include "NpBounds.h" #include "NpRigidDynamic.h" #include "NpRigidStatic.h" #include "NpShape.h" #include "GuBounds.h" #include "CmTransformUtils.h" #include "CmUtils.h" #include "SqPrunerData.h" using namespace physx; using namespace Sq; using namespace Gu; ////////////////////////////////////////////////////////////////////////// #define PS_NB_OBJECTS_PER_NODE 4 ////////////////////////////////////////////////////////////////////////// PruningStructure::PruningStructure(PxBaseFlags baseFlags) : PxPruningStructure(baseFlags) { } ////////////////////////////////////////////////////////////////////////// PruningStructure::PruningStructure() : PxPruningStructure(PxConcreteType::ePRUNING_STRUCTURE, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mNbActors(0), mActors(0), mValid(true) { for(PxU32 i=0; i<2; i++) mData[i].init(); } ////////////////////////////////////////////////////////////////////////// PruningStructure::~PruningStructure() { if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { for(PxU32 i=0; i<2; i++) { PX_FREE(mData[i].mAABBTreeIndices); PX_FREE(mData[i].mAABBTreeNodes); } PX_FREE(mActors); } } ////////////////////////////////////////////////////////////////////////// void PruningStructure::release() { // if we release the pruning structure we set the pruner structure to NUUL for (PxU32 i = 0; i < mNbActors; i++) { PX_ASSERT(mActors[i]); PxType type = mActors[i]->getConcreteType(); if (type == PxConcreteType::eRIGID_STATIC) static_cast<NpRigidStatic*>(mActors[i])->getShapeManager().setPruningStructure(NULL); else if (type == PxConcreteType::eRIGID_DYNAMIC) static_cast<NpRigidDynamic*>(mActors[i])->getShapeManager().setPruningStructure(NULL); } if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_DELETE_THIS; else this->~PruningStructure(); } template <typename ActorType> static void getShapeBounds(PxRigidActor* actor, bool dynamic, PxBounds3* bounds, PxU32& numShapes) { PruningIndex::Enum treeStructure = dynamic ? PruningIndex::eDYNAMIC : PruningIndex::eSTATIC; ActorType& a = *static_cast<ActorType*>(actor); const PxU32 nbShapes = a.getNbShapes(); for (PxU32 iShape = 0; iShape < nbShapes; iShape++) { NpShape* shape = a.getShapeManager().getShapes()[iShape]; if (shape->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE) { (gComputeBoundsTable[treeStructure])(*bounds, *shape, a); bounds++; numShapes++; } } } ////////////////////////////////////////////////////////////////////////// bool PruningStructure::build(PxRigidActor*const* actors, PxU32 nbActors) { PX_ASSERT(actors); PX_ASSERT(nbActors > 0); PxU32 numShapes[2] = { 0, 0 }; // parse the actors first to get the shapes size for (PxU32 actorsDone = 0; actorsDone < nbActors; actorsDone++) { if (actorsDone + 1 < nbActors) PxPrefetch(actors[actorsDone + 1], sizeof(NpRigidDynamic)); // worst case: PxRigidStatic is smaller PxType type = actors[actorsDone]->getConcreteType(); const PxRigidActor& actor = *(actors[actorsDone]); NpScene* scene = NpActor::getFromPxActor(actor).getNpScene(); if(scene) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PrunerStructure::build: Actor already assigned to a scene!"); return false; } const PxU32 nbShapes = actor.getNbShapes(); bool hasQueryShape = false; for (PxU32 iShape = 0; iShape < nbShapes; iShape++) { PxShape* shape; actor.getShapes(&shape, 1, iShape); if(shape->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE) { hasQueryShape = true; if (type == PxConcreteType::eRIGID_STATIC) numShapes[PruningIndex::eSTATIC]++; else numShapes[PruningIndex::eDYNAMIC]++; } } // each provided actor must have a query shape if(!hasQueryShape) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PrunerStructure::build: Provided actor has no scene query shape!"); return false; } if (type == PxConcreteType::eRIGID_STATIC) { NpRigidStatic* rs = static_cast<NpRigidStatic*>(actors[actorsDone]); if(rs->getShapeManager().getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PrunerStructure::build: Provided actor has already a pruning structure!"); return false; } rs->getShapeManager().setPruningStructure(this); } else if (type == PxConcreteType::eRIGID_DYNAMIC) { NpRigidDynamic* rd = static_cast<NpRigidDynamic*>(actors[actorsDone]); if (rd->getShapeManager().getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PrunerStructure::build: Provided actor has already a pruning structure!"); return false; } rd->getShapeManager().setPruningStructure(this); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PrunerStructure::build: Provided actor is not a rigid actor!"); return false; } } AABBTreeBounds bounds[2]; for (PxU32 i = 0; i < 2; i++) { if(numShapes[i]) { bounds[i].init(numShapes[i]); } } // now I go again and gather bounds and payload numShapes[PruningIndex::eSTATIC] = 0; numShapes[PruningIndex::eDYNAMIC] = 0; for (PxU32 actorsDone = 0; actorsDone < nbActors; actorsDone++) { PxType type = actors[actorsDone]->getConcreteType(); if (type == PxConcreteType::eRIGID_STATIC) { getShapeBounds<NpRigidStatic>(actors[actorsDone], false, &bounds[PruningIndex::eSTATIC].getBounds()[numShapes[PruningIndex::eSTATIC]], numShapes[PruningIndex::eSTATIC]); } else if (type == PxConcreteType::eRIGID_DYNAMIC) { getShapeBounds<NpRigidDynamic>(actors[actorsDone], true, &bounds[PruningIndex::eDYNAMIC].getBounds()[numShapes[PruningIndex::eDYNAMIC]], numShapes[PruningIndex::eDYNAMIC]); } } AABBTree aabbTrees[2]; for (PxU32 i = 0; i < 2; i++) { mData[i].mNbObjects = numShapes[i]; if (numShapes[i]) { // create the AABB tree NodeAllocator nodeAllocator; bool status = aabbTrees[i].build(AABBTreeBuildParams(PS_NB_OBJECTS_PER_NODE, numShapes[i], &bounds[i]), nodeAllocator); PX_UNUSED(status); PX_ASSERT(status); // store the tree nodes mData[i].mNbNodes = aabbTrees[i].getNbNodes(); mData[i].mAABBTreeNodes = PX_ALLOCATE(BVHNode, mData[i].mNbNodes, "BVHNode"); PxMemCopy(mData[i].mAABBTreeNodes, aabbTrees[i].getNodes(), sizeof(BVHNode)*mData[i].mNbNodes); mData[i].mAABBTreeIndices = PX_ALLOCATE(PxU32, mData[i].mNbObjects, "PxU32"); PxMemCopy(mData[i].mAABBTreeIndices, aabbTrees[i].getIndices(), sizeof(PxU32)*mData[i].mNbObjects); // discard the data bounds[i].release(); } } // store the actors for verification and serialization mNbActors = nbActors; mActors = PX_ALLOCATE(PxActor*, mNbActors, "PxActor*"); PxMemCopy(mActors, actors, sizeof(PxActor*)*mNbActors); return true; } ////////////////////////////////////////////////////////////////////////// PruningStructure* PruningStructure::createObject(PxU8*& address, PxDeserializationContext& context) { PruningStructure* obj = PX_PLACEMENT_NEW(address, PruningStructure(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(PruningStructure); obj->importExtraData(context); obj->resolveReferences(context); return obj; } ////////////////////////////////////////////////////////////////////////// void PruningStructure::resolveReferences(PxDeserializationContext& context) { if (!isValid()) return; for (PxU32 i = 0; i < mNbActors; i++) context.translatePxBase(mActors[i]); } ////////////////////////////////////////////////////////////////////////// void PruningStructure::requiresObjects(PxProcessPxBaseCallback& c) { if (!isValid()) return; for (PxU32 i = 0; i < mNbActors; i++) c.process(*mActors[i]); } ////////////////////////////////////////////////////////////////////////// void PruningStructure::exportExtraData(PxSerializationContext& stream) { if (!isValid()) { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "PrunerStructure::exportExtraData: Pruning structure is invalid!"); return; } for (PxU32 i = 0; i < 2; i++) { if (mData[i].mAABBTreeNodes) { // store nodes stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mData[i].mAABBTreeNodes, mData[i].mNbNodes * sizeof(BVHNode)); } if(mData[i].mAABBTreeIndices) { // store indices stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mData[i].mAABBTreeIndices, mData[i].mNbObjects * sizeof(PxU32)); } } if(mActors) { // store actor pointers stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mActors, mNbActors * sizeof(PxActor*)); } } ////////////////////////////////////////////////////////////////////////// void PruningStructure::importExtraData(PxDeserializationContext& context) { if (!isValid()) { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "PrunerStructure::importExtraData: Pruning structure is invalid!"); return; } for (PxU32 i = 0; i < 2; i++) { if (mData[i].mAABBTreeNodes) mData[i].mAABBTreeNodes = context.readExtraData<BVHNode, PX_SERIAL_ALIGN>(mData[i].mNbNodes); if(mData[i].mAABBTreeIndices) mData[i].mAABBTreeIndices = context.readExtraData<PxU32, PX_SERIAL_ALIGN>(mData[i].mNbObjects); } if (mActors) { // read actor pointers mActors = context.readExtraData<PxActor*, PX_SERIAL_ALIGN>(mNbActors); } } ////////////////////////////////////////////////////////////////////////// PxU32 PruningStructure::getNbRigidActors() const { return mNbActors; } const void* PruningStructure::getStaticMergeData() const { return &mData[PruningIndex::eSTATIC]; } const void* PruningStructure::getDynamicMergeData() const { return &mData[PruningIndex::eDYNAMIC]; } PxU32 PruningStructure::getRigidActors(PxRigidActor** userBuffer, PxU32 bufferSize, PxU32 startIndex/* =0 */) const { if(!isValid()) { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "PrunerStructure::getRigidActors: Pruning structure is invalid!"); return 0; } return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mActors, mNbActors); } ////////////////////////////////////////////////////////////////////////// void PruningStructure::invalidate(PxActor* actor) { PX_ASSERT(actor); // remove actor from the actor list to avoid mem corruption // this slow, but should be called only with error msg send to user about invalid behavior for (PxU32 i = 0; i < mNbActors; i++) { if(mActors[i] == actor) { // set pruning structure to NULL and remove the actor from the list PxType type = mActors[i]->getConcreteType(); if (type == PxConcreteType::eRIGID_STATIC) static_cast<NpRigidStatic*>(mActors[i])->getShapeManager().setPruningStructure(NULL); else if (type == PxConcreteType::eRIGID_DYNAMIC) static_cast<NpRigidDynamic*>(mActors[i])->getShapeManager().setPruningStructure(NULL); mActors[i] = mActors[mNbActors--]; break; } } mValid = false; }
12,679
C++
30.542288
175
0.664642
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationTendon.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_ARTICULATION_TENDON_H #define NP_ARTICULATION_TENDON_H #include "foundation/PxInlineArray.h" #include "PxArticulationTendon.h" #include "ScArticulationTendonCore.h" #include "ScArticulationAttachmentCore.h" #include "ScArticulationTendonJointCore.h" #include "NpBase.h" namespace physx { typedef PxU32 ArticulationAttachmentHandle; typedef PxU32 ArticulationTendonHandle; class NpArticulationReducedCoordinate; class NpArticulationAttachment; class NpArticulationSpatialTendon; class NpArticulationTendonJoint; class NpArticulationFixedTendon; class NpArticulationAttachmentArray : public PxInlineArray<NpArticulationAttachment*, 4> //!!!AL TODO: check if default of 4 elements makes sense { public: // PX_SERIALIZATION NpArticulationAttachmentArray(const PxEMPTY) : PxInlineArray<NpArticulationAttachment*, 4>(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationAttachmentArray() : PxInlineArray<NpArticulationAttachment*, 4>("NpArticulationAttachmentArray") {} }; class NpArticulationTendonJointArray : public PxInlineArray<NpArticulationTendonJoint*, 4> //!!!AL TODO: check if default of 4 elements makes sense { public: // PX_SERIALIZATION NpArticulationTendonJointArray(const PxEMPTY) : PxInlineArray<NpArticulationTendonJoint*, 4>(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationTendonJointArray() : PxInlineArray<NpArticulationTendonJoint*, 4>("NpArticulationTendonJointArray") {} }; class NpArticulationAttachment : public PxArticulationAttachment, public NpBase { public: // PX_SERIALIZATION NpArticulationAttachment(PxBaseFlags baseFlags) : PxArticulationAttachment(baseFlags), NpBase(PxEmpty), mHandle(PxEmpty), mChildren(PxEmpty), mCore(PxEmpty) {} void preExportDataReset() { mCore.preExportDataReset(); } virtual void exportExtraData(PxSerializationContext& ); void importExtraData(PxDeserializationContext& ); void resolveReferences(PxDeserializationContext& ); virtual void requiresObjects(PxProcessPxBaseCallback&); virtual bool isSubordinate() const { return true; } static NpArticulationAttachment* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link); virtual ~NpArticulationAttachment(); virtual void setRestLength(const PxReal restLength); virtual PxReal getRestLength() const; virtual void setLimitParameters(const PxArticulationTendonLimit& paramters); virtual PxArticulationTendonLimit getLimitParameters() const; virtual void setRelativeOffset(const PxVec3& offset); virtual PxVec3 getRelativeOffset() const; virtual void setCoefficient(const PxReal coefficient); virtual PxReal getCoefficient() const; virtual PxArticulationLink* getLink() const { return mLink; } virtual PxArticulationAttachment* getParent() const { return mParent; } virtual PxArticulationSpatialTendon* getTendon() const; virtual bool isLeaf() const { return mChildren.empty(); } virtual void release(); PX_FORCE_INLINE NpArticulationAttachment** getChildren() { return mChildren.begin(); } PX_FORCE_INLINE PxU32 getNumChildren() { return mChildren.size(); } PX_FORCE_INLINE void setTendon(NpArticulationSpatialTendon* tendon) { mTendon = tendon; } PX_FORCE_INLINE NpArticulationSpatialTendon& getTendon() { return *mTendon; } PX_FORCE_INLINE Sc::ArticulationAttachmentCore& getCore() { return mCore; } void removeChild(NpArticulationAttachment* child); PxArticulationLink* mLink; //the link this attachment attach to PxArticulationAttachment* mParent; ArticulationAttachmentHandle mHandle; NpArticulationAttachmentArray mChildren; NpArticulationSpatialTendon* mTendon; Sc::ArticulationAttachmentCore mCore; }; class NpArticulationSpatialTendon : public PxArticulationSpatialTendon, public NpBase { public: // PX_SERIALIZATION NpArticulationSpatialTendon(PxBaseFlags baseFlags) : PxArticulationSpatialTendon(baseFlags), NpBase(PxEmpty), mAttachments(PxEmpty), mCore(PxEmpty) {} void preExportDataReset() { mCore.preExportDataReset(); } virtual void exportExtraData(PxSerializationContext& ); void importExtraData(PxDeserializationContext& ); void resolveReferences(PxDeserializationContext& ); virtual void requiresObjects(PxProcessPxBaseCallback&); virtual bool isSubordinate() const { return true; } static NpArticulationSpatialTendon* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationSpatialTendon(NpArticulationReducedCoordinate* articulation); virtual ~NpArticulationSpatialTendon(); virtual PxArticulationAttachment* createAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link); NpArticulationAttachment* getAttachment(const PxU32 index); virtual PxU32 getAttachments(PxArticulationAttachment** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; PxU32 getNbAttachments() const; virtual void setStiffness(const PxReal stiffness); virtual PxReal getStiffness() const; virtual void setDamping(const PxReal damping); virtual PxReal getDamping() const; virtual void setLimitStiffness(const PxReal stiffness); virtual PxReal getLimitStiffness() const; virtual void setOffset(const PxReal offset, bool autowake = true); virtual PxReal getOffset() const; virtual PxArticulationReducedCoordinate* getArticulation() const; virtual void release(); PX_FORCE_INLINE Sc::ArticulationSpatialTendonCore& getTendonCore() { return mCore; } PX_FORCE_INLINE ArticulationTendonHandle getHandle() { return mHandle; } PX_FORCE_INLINE void setHandle(ArticulationTendonHandle handle) { mHandle = handle; } PX_FORCE_INLINE NpArticulationAttachmentArray& getAttachments() { return mAttachments; } private: NpArticulationAttachmentArray mAttachments; NpArticulationReducedCoordinate* mArticulation; PxU32 mLLIndex; Sc::ArticulationSpatialTendonCore mCore; ArticulationTendonHandle mHandle; }; class NpArticulationTendonJoint : public PxArticulationTendonJoint, public NpBase { public: // PX_SERIALIZATION NpArticulationTendonJoint(PxBaseFlags baseFlags) : PxArticulationTendonJoint(baseFlags), NpBase(PxEmpty), mChildren(PxEmpty), mCore(PxEmpty), mHandle(PxEmpty) {} void preExportDataReset() { mCore.preExportDataReset(); } virtual void exportExtraData(PxSerializationContext& ); void importExtraData(PxDeserializationContext& ); void resolveReferences(PxDeserializationContext& ); virtual void requiresObjects(PxProcessPxBaseCallback&); virtual bool isSubordinate() const { return true; } static NpArticulationTendonJoint* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link); virtual ~NpArticulationTendonJoint(){} virtual PxArticulationLink* getLink() const { return mLink; } virtual PxArticulationTendonJoint* getParent() const { return mParent; } virtual PxArticulationFixedTendon* getTendon() const; virtual void setCoefficient(const PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient); virtual void getCoefficient(PxArticulationAxis::Enum& axis, PxReal& coefficient, PxReal& recipCoefficient) const; virtual void release(); PX_FORCE_INLINE NpArticulationTendonJoint** getChildren() { return mChildren.begin(); } PX_FORCE_INLINE PxU32 getNumChildren() { return mChildren.size(); } PX_FORCE_INLINE void setTendon(NpArticulationFixedTendon* tendon) { mTendon = tendon; } PX_FORCE_INLINE NpArticulationFixedTendon& getTendon() { return *mTendon; } PX_FORCE_INLINE Sc::ArticulationTendonJointCore& getCore() { return mCore; } void removeChild(NpArticulationTendonJoint* child); PxArticulationLink* mLink; //the link this joint associated with PxArticulationTendonJoint* mParent; NpArticulationTendonJointArray mChildren; NpArticulationFixedTendon* mTendon; Sc::ArticulationTendonJointCore mCore; PxU32 mHandle; }; class NpArticulationFixedTendon : public PxArticulationFixedTendon, public NpBase { public: // PX_SERIALIZATION NpArticulationFixedTendon(PxBaseFlags baseFlags): PxArticulationFixedTendon(baseFlags), NpBase(PxEmpty), mTendonJoints(PxEmpty), mCore(PxEmpty), mHandle(PxEmpty) {} void preExportDataReset() {} virtual void exportExtraData(PxSerializationContext& ); void importExtraData(PxDeserializationContext& ); void resolveReferences(PxDeserializationContext& ); virtual void requiresObjects(PxProcessPxBaseCallback&); virtual bool isSubordinate() const { return true; } static NpArticulationFixedTendon* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationFixedTendon(NpArticulationReducedCoordinate* articulation); virtual ~NpArticulationFixedTendon(); virtual PxArticulationTendonJoint* createTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal scale, const PxReal recipScale, PxArticulationLink* link); NpArticulationTendonJoint* getTendonJoint(const PxU32 index); virtual PxU32 getTendonJoints(PxArticulationTendonJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbTendonJoints(void) const; virtual void setStiffness(const PxReal stiffness); virtual PxReal getStiffness() const; virtual void setDamping(const PxReal damping); virtual PxReal getDamping() const; virtual void setLimitStiffness(const PxReal damping); virtual PxReal getLimitStiffness() const; virtual void setRestLength(const PxReal restLength); virtual PxReal getRestLength() const; virtual void setLimitParameters(const PxArticulationTendonLimit& paramters); virtual PxArticulationTendonLimit getLimitParameters() const; virtual void setOffset(const PxReal offset, bool autowake = true); virtual PxReal getOffset() const; virtual PxArticulationReducedCoordinate* getArticulation() const; virtual void release(); PX_FORCE_INLINE ArticulationTendonHandle getHandle() { return mHandle; } PX_FORCE_INLINE void setHandle(ArticulationTendonHandle handle) { mHandle = handle; } PX_FORCE_INLINE Sc::ArticulationFixedTendonCore& getTendonCore() { return mCore; } PX_FORCE_INLINE NpArticulationTendonJointArray& getTendonJoints() { return mTendonJoints; } private: NpArticulationTendonJointArray mTendonJoints; NpArticulationReducedCoordinate* mArticulation; PxU32 mLLIndex; Sc::ArticulationFixedTendonCore mCore; ArticulationTendonHandle mHandle; }; } #endif
13,267
C
41.8
193
0.772292
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdMetaDataPvdBinding.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. // suppress LNK4221 #include "foundation/PxPreprocessor.h" PX_DUMMY_SYMBOL #if PX_SUPPORT_PVD #include "foundation/PxSimpleTypes.h" #include "foundation/Px.h" #include "PxMetaDataObjects.h" #include "PxPvdDataStream.h" #include "PxScene.h" #include "ScBodyCore.h" #include "PvdMetaDataExtensions.h" #include "PvdMetaDataPropertyVisitor.h" #include "PvdMetaDataDefineProperties.h" #include "PvdMetaDataBindingData.h" #include "PxRigidDynamic.h" #include "PxArticulationReducedCoordinate.h" #include "PxArticulationLink.h" #include "NpScene.h" #include "NpPhysics.h" #include "PvdTypeNames.h" #include "PvdMetaDataPvdBinding.h" using namespace physx; using namespace Sc; using namespace Vd; using namespace Sq; namespace physx { namespace Vd { struct NameValuePair { const char* mName; PxU32 mValue; }; #if PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-identifier" #endif static const NameValuePair g_physx_Sq_SceneQueryID__EnumConversion[] = { { "QUERY_RAYCAST_ANY_OBJECT", PxU32(QueryID::QUERY_RAYCAST_ANY_OBJECT) }, { "QUERY_RAYCAST_CLOSEST_OBJECT", PxU32(QueryID::QUERY_RAYCAST_CLOSEST_OBJECT) }, { "QUERY_RAYCAST_ALL_OBJECTS", PxU32(QueryID::QUERY_RAYCAST_ALL_OBJECTS) }, { "QUERY_OVERLAP_SPHERE_ALL_OBJECTS", PxU32(QueryID::QUERY_OVERLAP_SPHERE_ALL_OBJECTS) }, { "QUERY_OVERLAP_AABB_ALL_OBJECTS", PxU32(QueryID::QUERY_OVERLAP_AABB_ALL_OBJECTS) }, { "QUERY_OVERLAP_OBB_ALL_OBJECTS", PxU32(QueryID::QUERY_OVERLAP_OBB_ALL_OBJECTS) }, { "QUERY_OVERLAP_CAPSULE_ALL_OBJECTS", PxU32(QueryID::QUERY_OVERLAP_CAPSULE_ALL_OBJECTS) }, { "QUERY_OVERLAP_CONVEX_ALL_OBJECTS", PxU32(QueryID::QUERY_OVERLAP_CONVEX_ALL_OBJECTS) }, { "QUERY_LINEAR_OBB_SWEEP_CLOSEST_OBJECT", PxU32(QueryID::QUERY_LINEAR_OBB_SWEEP_CLOSEST_OBJECT) }, { "QUERY_LINEAR_CAPSULE_SWEEP_CLOSEST_OBJECT", PxU32(QueryID::QUERY_LINEAR_CAPSULE_SWEEP_CLOSEST_OBJECT) }, { "QUERY_LINEAR_CONVEX_SWEEP_CLOSEST_OBJECT", PxU32(QueryID::QUERY_LINEAR_CONVEX_SWEEP_CLOSEST_OBJECT) }, { NULL, 0 } }; #if PX_LINUX && PX_CLANG #pragma clang diagnostic pop #endif struct SceneQueryIDConvertor { const NameValuePair* NameConversion; SceneQueryIDConvertor() : NameConversion(g_physx_Sq_SceneQueryID__EnumConversion) { } }; PvdMetaDataBinding::PvdMetaDataBinding() : mBindingData(PX_NEW(PvdMetaDataBindingData)()) { } PvdMetaDataBinding::~PvdMetaDataBinding() { for(OwnerActorsMap::Iterator iter = mBindingData->mOwnerActorsMap.getIterator(); !iter.done(); iter++) { iter->second->~OwnerActorsValueType(); PX_FREE(iter->second); } PX_DELETE(mBindingData); } template <typename TDataType, typename TValueType, typename TClassType> static inline void definePropertyStruct(PvdDataStream& inStream, const char* pushName = NULL) { PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); PvdClassInfoValueStructDefine definitionObj(helper); bool doPush = pushName && *pushName; if(doPush) definitionObj.pushName(pushName); visitAllPvdProperties<TDataType>(definitionObj); if(doPush) definitionObj.popName(); helper.addPropertyMessage(getPvdNamespacedNameForType<TClassType>(), getPvdNamespacedNameForType<TValueType>(), sizeof(TValueType)); } template <typename TDataType> static inline void createClassAndDefineProperties(PvdDataStream& inStream) { inStream.createClass<TDataType>(); PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); PvdClassInfoDefine definitionObj(helper, getPvdNamespacedNameForType<TDataType>()); visitAllPvdProperties<TDataType>(definitionObj); } template <typename TDataType, typename TParentType> static inline void createClassDeriveAndDefineProperties(PvdDataStream& inStream) { inStream.createClass<TDataType>(); inStream.deriveClass<TParentType, TDataType>(); PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); PvdClassInfoDefine definitionObj(helper, getPvdNamespacedNameForType<TDataType>()); visitInstancePvdProperties<TDataType>(definitionObj); } template <typename TDataType, typename TConvertSrc, typename TConvertData> static inline void defineProperty(PvdDataStream& inStream, const char* inPropertyName, const char* semantic) { PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); // PxEnumTraits< TValueType > filterFlagsEnum; TConvertSrc filterFlagsEnum; const TConvertData* convertor = filterFlagsEnum.NameConversion; for(; convertor->mName != NULL; ++convertor) helper.addNamedValue(convertor->mName, convertor->mValue); inStream.createProperty<TDataType, PxU32>(inPropertyName, semantic, PropertyType::Scalar, helper.getNamedValues()); helper.clearNamedValues(); } template <typename TDataType, typename TConvertSrc, typename TConvertData> static inline void definePropertyFlags(PvdDataStream& inStream, const char* inPropertyName) { defineProperty<TDataType, TConvertSrc, TConvertData>(inStream, inPropertyName, "Bitflag"); } template <typename TDataType, typename TConvertSrc, typename TConvertData> static inline void definePropertyEnums(PvdDataStream& inStream, const char* inPropertyName) { defineProperty<TDataType, TConvertSrc, TConvertData>(inStream, inPropertyName, "Enumeration Value"); } static PX_FORCE_INLINE void registerPvdRaycast(PvdDataStream& inStream) { inStream.createClass<PvdRaycast>(); definePropertyEnums<PvdRaycast, SceneQueryIDConvertor, NameValuePair>(inStream, "type"); inStream.createProperty<PvdRaycast, PxFilterData>("filterData"); definePropertyFlags<PvdRaycast, PxEnumTraits<physx::PxQueryFlag::Enum>, PxU32ToName>(inStream, "filterFlags"); inStream.createProperty<PvdRaycast, PxVec3>("origin"); inStream.createProperty<PvdRaycast, PxVec3>("unitDir"); inStream.createProperty<PvdRaycast, PxF32>("distance"); inStream.createProperty<PvdRaycast, String>("hits_arrayName"); inStream.createProperty<PvdRaycast, PxU32>("hits_baseIndex"); inStream.createProperty<PvdRaycast, PxU32>("hits_count"); } static PX_FORCE_INLINE void registerPvdSweep(PvdDataStream& inStream) { inStream.createClass<PvdSweep>(); definePropertyEnums<PvdSweep, SceneQueryIDConvertor, NameValuePair>(inStream, "type"); definePropertyFlags<PvdSweep, PxEnumTraits<physx::PxQueryFlag::Enum>, PxU32ToName>(inStream, "filterFlags"); inStream.createProperty<PvdSweep, PxVec3>("unitDir"); inStream.createProperty<PvdSweep, PxF32>("distance"); inStream.createProperty<PvdSweep, String>("geom_arrayName"); inStream.createProperty<PvdSweep, PxU32>("geom_baseIndex"); inStream.createProperty<PvdSweep, PxU32>("geom_count"); inStream.createProperty<PvdSweep, String>("pose_arrayName"); inStream.createProperty<PvdSweep, PxU32>("pose_baseIndex"); inStream.createProperty<PvdSweep, PxU32>("pose_count"); inStream.createProperty<PvdSweep, String>("filterData_arrayName"); inStream.createProperty<PvdSweep, PxU32>("filterData_baseIndex"); inStream.createProperty<PvdSweep, PxU32>("filterData_count"); inStream.createProperty<PvdSweep, String>("hits_arrayName"); inStream.createProperty<PvdSweep, PxU32>("hits_baseIndex"); inStream.createProperty<PvdSweep, PxU32>("hits_count"); } static PX_FORCE_INLINE void registerPvdOverlap(PvdDataStream& inStream) { inStream.createClass<PvdOverlap>(); definePropertyEnums<PvdOverlap, SceneQueryIDConvertor, NameValuePair>(inStream, "type"); inStream.createProperty<PvdOverlap, PxFilterData>("filterData"); definePropertyFlags<PvdOverlap, PxEnumTraits<physx::PxQueryFlag::Enum>, PxU32ToName>(inStream, "filterFlags"); inStream.createProperty<PvdOverlap, PxTransform>("pose"); inStream.createProperty<PvdOverlap, String>("geom_arrayName"); inStream.createProperty<PvdOverlap, PxU32>("geom_baseIndex"); inStream.createProperty<PvdOverlap, PxU32>("geom_count"); inStream.createProperty<PvdOverlap, String>("hits_arrayName"); inStream.createProperty<PvdOverlap, PxU32>("hits_baseIndex"); inStream.createProperty<PvdOverlap, PxU32>("hits_count"); } static PX_FORCE_INLINE void registerPvdSqHit(PvdDataStream& inStream) { inStream.createClass<PvdSqHit>(); inStream.createProperty<PvdSqHit, ObjectRef>("Shape"); inStream.createProperty<PvdSqHit, ObjectRef>("Actor"); inStream.createProperty<PvdSqHit, PxU32>("FaceIndex"); definePropertyFlags<PvdSqHit, PxEnumTraits<physx::PxHitFlag::Enum>, PxU32ToName>(inStream, "Flags"); inStream.createProperty<PvdSqHit, PxVec3>("Impact"); inStream.createProperty<PvdSqHit, PxVec3>("Normal"); inStream.createProperty<PvdSqHit, PxF32>("Distance"); inStream.createProperty<PvdSqHit, PxF32>("U"); inStream.createProperty<PvdSqHit, PxF32>("V"); } void PvdMetaDataBinding::registerSDKProperties(PvdDataStream& inStream) { if (inStream.isClassExist<PxPhysics>()) return; // PxPhysics { inStream.createClass<PxPhysics>(); PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); PvdClassInfoDefine definitionObj(helper, getPvdNamespacedNameForType<PxPhysics>()); helper.pushName("TolerancesScale"); visitAllPvdProperties<PxTolerancesScale>(definitionObj); helper.popName(); inStream.createProperty<PxPhysics, ObjectRef>("Scenes", "children", PropertyType::Array); inStream.createProperty<PxPhysics, ObjectRef>("SharedShapes", "children", PropertyType::Array); inStream.createProperty<PxPhysics, ObjectRef>("Materials", "children", PropertyType::Array); inStream.createProperty<PxPhysics, ObjectRef>("HeightFields", "children", PropertyType::Array); inStream.createProperty<PxPhysics, ObjectRef>("ConvexMeshes", "children", PropertyType::Array); inStream.createProperty<PxPhysics, ObjectRef>("TriangleMeshes", "children", PropertyType::Array); inStream.createProperty<PxPhysics, PxU32>("Version.Major"); inStream.createProperty<PxPhysics, PxU32>("Version.Minor"); inStream.createProperty<PxPhysics, PxU32>("Version.Bugfix"); inStream.createProperty<PxPhysics, String>("Version.Build"); definePropertyStruct<PxTolerancesScale, PxTolerancesScaleGeneratedValues, PxPhysics>(inStream, "TolerancesScale"); } { // PxGeometry inStream.createClass<PxGeometry>(); inStream.createProperty<PxGeometry, ObjectRef>("Shape", "parents", PropertyType::Scalar); } { // PxBoxGeometry createClassDeriveAndDefineProperties<PxBoxGeometry, PxGeometry>(inStream); definePropertyStruct<PxBoxGeometry, PxBoxGeometryGeneratedValues, PxBoxGeometry>(inStream); } { // PxSphereGeometry createClassDeriveAndDefineProperties<PxSphereGeometry, PxGeometry>(inStream); definePropertyStruct<PxSphereGeometry, PxSphereGeometryGeneratedValues, PxSphereGeometry>(inStream); } { // PxCapsuleGeometry createClassDeriveAndDefineProperties<PxCapsuleGeometry, PxGeometry>(inStream); definePropertyStruct<PxCapsuleGeometry, PxCapsuleGeometryGeneratedValues, PxCapsuleGeometry>(inStream); } { // PxPlaneGeometry createClassDeriveAndDefineProperties<PxPlaneGeometry, PxGeometry>(inStream); } { // PxConvexMeshGeometry createClassDeriveAndDefineProperties<PxConvexMeshGeometry, PxGeometry>(inStream); definePropertyStruct<PxConvexMeshGeometry, PxConvexMeshGeometryGeneratedValues, PxConvexMeshGeometry>(inStream); } { // PxTetrahedronMeshGeometry createClassDeriveAndDefineProperties<PxTetrahedronMeshGeometry, PxGeometry>(inStream); definePropertyStruct<PxTetrahedronMeshGeometry, PxTetrahedronMeshGeometryGeneratedValues, PxTetrahedronMeshGeometry>(inStream); } { // PxTriangleMeshGeometry createClassDeriveAndDefineProperties<PxTriangleMeshGeometry, PxGeometry>(inStream); definePropertyStruct<PxTriangleMeshGeometry, PxTriangleMeshGeometryGeneratedValues, PxTriangleMeshGeometry>(inStream); } { // PxHeightFieldGeometry createClassDeriveAndDefineProperties<PxHeightFieldGeometry, PxGeometry>(inStream); definePropertyStruct<PxHeightFieldGeometry, PxHeightFieldGeometryGeneratedValues, PxHeightFieldGeometry>(inStream); } { // PxCustomGeometry createClassDeriveAndDefineProperties<PxCustomGeometry, PxGeometry>(inStream); definePropertyStruct<PxCustomGeometry, PxCustomGeometryGeneratedValues, PxCustomGeometry>(inStream); } // PxScene { // PT: TODO: why inline this for PvdContact but do PvdRaycast/etc in separate functions? { // contact information inStream.createClass<PvdContact>(); inStream.createProperty<PvdContact, PxVec3>("Point"); inStream.createProperty<PvdContact, PxVec3>("Axis"); inStream.createProperty<PvdContact, ObjectRef>("Shapes[0]"); inStream.createProperty<PvdContact, ObjectRef>("Shapes[1]"); inStream.createProperty<PvdContact, PxF32>("Separation"); inStream.createProperty<PvdContact, PxF32>("NormalForce"); inStream.createProperty<PvdContact, PxU32>("InternalFaceIndex[0]"); inStream.createProperty<PvdContact, PxU32>("InternalFaceIndex[1]"); inStream.createProperty<PvdContact, bool>("NormalForceValid"); } registerPvdSqHit(inStream); registerPvdRaycast(inStream); registerPvdSweep(inStream); registerPvdOverlap(inStream); inStream.createClass<PxScene>(); PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); PvdClassInfoDefine definitionObj(helper, getPvdNamespacedNameForType<PxScene>()); visitAllPvdProperties<PxSceneDesc>(definitionObj); helper.pushName("SimulationStatistics"); visitAllPvdProperties<PxSimulationStatistics>(definitionObj); helper.popName(); inStream.createProperty<PxScene, ObjectRef>("Physics", "parents", PropertyType::Scalar); inStream.createProperty<PxScene, PxU32>("Timestamp"); inStream.createProperty<PxScene, PxReal>("SimulateElapsedTime"); definePropertyStruct<PxSceneDesc, PxSceneDescGeneratedValues, PxScene>(inStream); definePropertyStruct<PxSimulationStatistics, PxSimulationStatisticsGeneratedValues, PxScene>(inStream, "SimulationStatistics"); inStream.createProperty<PxScene, PvdContact>("Contacts", "", PropertyType::Array); inStream.createProperty<PxScene, PvdOverlap>("SceneQueries.Overlaps", "", PropertyType::Array); inStream.createProperty<PxScene, PvdSweep>("SceneQueries.Sweeps", "", PropertyType::Array); inStream.createProperty<PxScene, PvdSqHit>("SceneQueries.Hits", "", PropertyType::Array); inStream.createProperty<PxScene, PvdRaycast>("SceneQueries.Raycasts", "", PropertyType::Array); inStream.createProperty<PxScene, PxTransform>("SceneQueries.PoseList", "", PropertyType::Array); inStream.createProperty<PxScene, PxFilterData>("SceneQueries.FilterDataList", "", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("SceneQueries.GeometryList", "", PropertyType::Array); inStream.createProperty<PxScene, PvdOverlap>("BatchedQueries.Overlaps", "", PropertyType::Array); inStream.createProperty<PxScene, PvdSweep>("BatchedQueries.Sweeps", "", PropertyType::Array); inStream.createProperty<PxScene, PvdSqHit>("BatchedQueries.Hits", "", PropertyType::Array); inStream.createProperty<PxScene, PvdRaycast>("BatchedQueries.Raycasts", "", PropertyType::Array); inStream.createProperty<PxScene, PxTransform>("BatchedQueries.PoseList", "", PropertyType::Array); inStream.createProperty<PxScene, PxFilterData>("BatchedQueries.FilterDataList", "", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("BatchedQueries.GeometryList", "", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("RigidStatics", "children", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("RigidDynamics", "children", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("Articulations", "children", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("Joints", "children", PropertyType::Array); inStream.createProperty<PxScene, ObjectRef>("Aggregates", "children", PropertyType::Array); } // PxMaterial { createClassAndDefineProperties<PxMaterial>(inStream); definePropertyStruct<PxMaterial, PxMaterialGeneratedValues, PxMaterial>(inStream); inStream.createProperty<PxMaterial, ObjectRef>("Physics", "parents", PropertyType::Scalar); } // PxHeightField { { inStream.createClass<PxHeightFieldSample>(); inStream.createProperty<PxHeightFieldSample, PxU16>("Height"); inStream.createProperty<PxHeightFieldSample, PxU8>("MaterialIndex[0]"); inStream.createProperty<PxHeightFieldSample, PxU8>("MaterialIndex[1]"); } inStream.createClass<PxHeightField>(); // It is important the PVD fields match the RepX fields, so this has // to be hand coded. PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); PvdClassInfoDefine definitionObj(helper, getPvdNamespacedNameForType<PxHeightField>()); visitAllPvdProperties<PxHeightFieldDesc>(definitionObj); inStream.createProperty<PxHeightField, PxHeightFieldSample>("Samples", "", PropertyType::Array); inStream.createProperty<PxHeightField, ObjectRef>("Physics", "parents", PropertyType::Scalar); definePropertyStruct<PxHeightFieldDesc, PxHeightFieldDescGeneratedValues, PxHeightField>(inStream); } // PxConvexMesh { { // hull polygon data. inStream.createClass<PvdHullPolygonData>(); inStream.createProperty<PvdHullPolygonData, PxU16>("NumVertices"); inStream.createProperty<PvdHullPolygonData, PxU16>("IndexBase"); } inStream.createClass<PxConvexMesh>(); inStream.createProperty<PxConvexMesh, PxF32>("Mass"); inStream.createProperty<PxConvexMesh, PxMat33>("LocalInertia"); inStream.createProperty<PxConvexMesh, PxVec3>("LocalCenterOfMass"); inStream.createProperty<PxConvexMesh, PxVec3>("Points", "", PropertyType::Array); inStream.createProperty<PxConvexMesh, PvdHullPolygonData>("HullPolygons", "", PropertyType::Array); inStream.createProperty<PxConvexMesh, PxU8>("PolygonIndexes", "", PropertyType::Array); inStream.createProperty<PxConvexMesh, ObjectRef>("Physics", "parents", PropertyType::Scalar); } // PxTriangleMesh { inStream.createClass<PxTriangleMesh>(); inStream.createProperty<PxTriangleMesh, PxVec3>("Points", "", PropertyType::Array); inStream.createProperty<PxTriangleMesh, PxU32>("NbTriangles", "", PropertyType::Scalar); inStream.createProperty<PxTriangleMesh, PxU32>("Triangles", "", PropertyType::Array); inStream.createProperty<PxTriangleMesh, PxU16>("MaterialIndices", "", PropertyType::Array); inStream.createProperty<PxTriangleMesh, ObjectRef>("Physics", "parents", PropertyType::Scalar); } // PxTetrahedronMesh { inStream.createClass<PxTetrahedronMesh>(); inStream.createProperty<PxTetrahedronMesh, PxVec3>("Points", "", PropertyType::Array); inStream.createProperty<PxTetrahedronMesh, PxU32>("NbTriangles", "", PropertyType::Scalar); inStream.createProperty<PxTetrahedronMesh, PxU32>("Triangles", "", PropertyType::Array); inStream.createProperty<PxTetrahedronMesh, ObjectRef>("Physics", "parents", PropertyType::Scalar); } // PxFEMSoftBodyMaterial { createClassAndDefineProperties<PxFEMSoftBodyMaterial>(inStream); definePropertyStruct<PxFEMSoftBodyMaterial, PxFEMSoftBodyMaterialGeneratedValues, PxFEMSoftBodyMaterial>(inStream); inStream.createProperty<PxFEMSoftBodyMaterial, ObjectRef>("Physics", "parents", PropertyType::Scalar); } // PxFEMClothMaterial // jcarius: Commented-out until FEMCloth is not under construction anymore // { // createClassAndDefineProperties<PxFEMClothMaterial>(inStream); // definePropertyStruct<PxFEMClothMaterial, PxFEMClothMaterialGeneratedValues, PxFEMClothMaterial>(inStream); // inStream.createProperty<PxFEMClothMaterial, ObjectRef>("Physics", "parents", PropertyType::Scalar); // } { // PxShape createClassAndDefineProperties<PxShape>(inStream); definePropertyStruct<PxShape, PxShapeGeneratedValues, PxShape>(inStream); inStream.createProperty<PxShape, ObjectRef>("Geometry", "children"); inStream.createProperty<PxShape, ObjectRef>("Materials", "children", PropertyType::Array); inStream.createProperty<PxShape, ObjectRef>("Actor", "parents"); } // PxActor { createClassAndDefineProperties<PxActor>(inStream); inStream.createProperty<PxActor, ObjectRef>("Scene", "parents"); } // PxRigidActor { createClassDeriveAndDefineProperties<PxRigidActor, PxActor>(inStream); inStream.createProperty<PxRigidActor, ObjectRef>("Shapes", "children", PropertyType::Array); inStream.createProperty<PxRigidActor, ObjectRef>("Joints", "children", PropertyType::Array); } // PxRigidStatic { createClassDeriveAndDefineProperties<PxRigidStatic, PxRigidActor>(inStream); definePropertyStruct<PxRigidStatic, PxRigidStaticGeneratedValues, PxRigidStatic>(inStream); } { // PxRigidBody createClassDeriveAndDefineProperties<PxRigidBody, PxRigidActor>(inStream); } // PxRigidDynamic { createClassDeriveAndDefineProperties<PxRigidDynamic, PxRigidBody>(inStream); // If anyone adds a 'getKinematicTarget' to PxRigidDynamic you can remove the line // below (after the code generator has run). inStream.createProperty<PxRigidDynamic, PxTransform>("KinematicTarget"); definePropertyStruct<PxRigidDynamic, PxRigidDynamicGeneratedValues, PxRigidDynamic>(inStream); // Manually define the update struct. PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); /*struct PxRigidDynamicUpdateBlock { Transform GlobalPose; Float3 LinearVelocity; Float3 AngularVelocity; PxU8 IsSleeping; PxU8 padding[3]; }; */ helper.pushName("GlobalPose"); helper.addPropertyMessageArg<PxTransform>(PX_OFFSET_OF_RT(PxRigidDynamicUpdateBlock, GlobalPose)); helper.popName(); helper.pushName("LinearVelocity"); helper.addPropertyMessageArg<PxVec3>(PX_OFFSET_OF_RT(PxRigidDynamicUpdateBlock, LinearVelocity)); helper.popName(); helper.pushName("AngularVelocity"); helper.addPropertyMessageArg<PxVec3>(PX_OFFSET_OF_RT(PxRigidDynamicUpdateBlock, AngularVelocity)); helper.popName(); helper.pushName("IsSleeping"); helper.addPropertyMessageArg<bool>(PX_OFFSET_OF_RT(PxRigidDynamicUpdateBlock, IsSleeping)); helper.popName(); helper.addPropertyMessage<PxRigidDynamic, PxRigidDynamicUpdateBlock>(); } // PxArticulationReducedCoordinate { createClassAndDefineProperties<PxArticulationReducedCoordinate>(inStream); inStream.createProperty<PxArticulationReducedCoordinate, ObjectRef>("Scene", "parents"); inStream.createProperty<PxArticulationReducedCoordinate, ObjectRef>("Links", "children", PropertyType::Array); definePropertyStruct<PxArticulationReducedCoordinate, PxArticulationReducedCoordinateGeneratedValues, PxArticulationReducedCoordinate>(inStream); } { // PxArticulationLink createClassDeriveAndDefineProperties<PxArticulationLink, PxRigidBody>(inStream); inStream.createProperty<PxArticulationLink, ObjectRef>("Parent", "parents"); inStream.createProperty<PxArticulationLink, ObjectRef>("Links", "children", PropertyType::Array); inStream.createProperty<PxArticulationLink, ObjectRef>("InboundJoint", "children"); definePropertyStruct<PxArticulationLink, PxArticulationLinkGeneratedValues, PxArticulationLink>(inStream); PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); /*struct PxArticulationLinkUpdateBlock { Transform GlobalPose; Float3 LinearVelocity; Float3 AngularVelocity; };*/ helper.pushName("GlobalPose"); helper.addPropertyMessageArg<PxTransform>(PX_OFFSET_OF(PxArticulationLinkUpdateBlock, GlobalPose)); helper.popName(); helper.pushName("LinearVelocity"); helper.addPropertyMessageArg<PxVec3>(PX_OFFSET_OF(PxArticulationLinkUpdateBlock, LinearVelocity)); helper.popName(); helper.pushName("AngularVelocity"); helper.addPropertyMessageArg<PxVec3>(PX_OFFSET_OF(PxArticulationLinkUpdateBlock, AngularVelocity)); helper.popName(); helper.addPropertyMessage<PxArticulationLink, PxArticulationLinkUpdateBlock>(); } { // PxArticulationJoint createClassAndDefineProperties<PxArticulationJointReducedCoordinate>(inStream); inStream.createProperty<PxArticulationJointReducedCoordinate, ObjectRef>("Link", "parents"); definePropertyStruct<PxArticulationJointReducedCoordinate, PxArticulationJointReducedCoordinateGeneratedValues, PxArticulationJointReducedCoordinate>(inStream); PvdPropertyDefinitionHelper& helper(inStream.getPropertyDefinitionHelper()); helper.pushName("JointPosition[eX]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointPosition_eX)); helper.popName(); helper.pushName("JointPosition[eY]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointPosition_eY)); helper.popName(); helper.pushName("JointPosition[eZ]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointPosition_eZ)); helper.popName(); helper.pushName("JointPosition[eTWIST]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointPosition_eTwist)); helper.popName(); helper.pushName("JointPosition[eSWING1]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointPosition_eSwing1)); helper.popName(); helper.pushName("JointPosition[eSWING2]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointPosition_eSwing2)); helper.popName(); helper.pushName("JointVelocity[eX]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointVelocity_eX)); helper.popName(); helper.pushName("JointVelocity[eY]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointVelocity_eY)); helper.popName(); helper.pushName("JointVelocity[eZ]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointVelocity_eZ)); helper.popName(); helper.pushName("JointVelocity[eTWIST]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointVelocity_eTwist)); helper.popName(); helper.pushName("JointVelocity[eSWING1]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointVelocity_eSwing1)); helper.popName(); helper.pushName("JointVelocity[eSWING2]"); helper.addPropertyMessageArg<PxReal>(PX_OFFSET_OF(PxArticulationJointUpdateBlock, JointVelocity_eSwing2)); helper.popName(); helper.addPropertyMessage<PxArticulationJointReducedCoordinate, PxArticulationJointUpdateBlock>(); } { // PxConstraint createClassAndDefineProperties<PxConstraint>(inStream); definePropertyStruct<PxConstraint, PxConstraintGeneratedValues, PxConstraint>(inStream); } { // PxAggregate createClassAndDefineProperties<PxAggregate>(inStream); inStream.createProperty<PxAggregate, ObjectRef>("Scene", "parents"); definePropertyStruct<PxAggregate, PxAggregateGeneratedValues, PxAggregate>(inStream); inStream.createProperty<PxAggregate, ObjectRef>("Actors", "children", PropertyType::Array); inStream.createProperty<PxAggregate, ObjectRef>("Articulations", "children", PropertyType::Array); } } template <typename TClassType, typename TValueType, typename TDataType> static void doSendAllProperties(PvdDataStream& inStream, const TDataType* inDatatype, const void* instanceId) { TValueType theValues(inDatatype); inStream.setPropertyMessage(instanceId, theValues); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxPhysics& inPhysics) { PxTolerancesScale theScale(inPhysics.getTolerancesScale()); doSendAllProperties<PxPhysics, PxTolerancesScaleGeneratedValues>(inStream, &theScale, &inPhysics); inStream.setPropertyValue(&inPhysics, "Version.Major", PxU32(PX_PHYSICS_VERSION_MAJOR)); inStream.setPropertyValue(&inPhysics, "Version.Minor", PxU32(PX_PHYSICS_VERSION_MINOR)); inStream.setPropertyValue(&inPhysics, "Version.Bugfix", PxU32(PX_PHYSICS_VERSION_BUGFIX)); #if PX_DEBUG String buildType = "Debug"; #elif PX_CHECKED String buildType = "Checked"; #elif PX_PROFILE String buildType = "Profile"; #else String buildType = "Release"; #endif inStream.setPropertyValue(&inPhysics, "Version.Build", buildType); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxScene& inScene) { const PxPhysics& physics(const_cast<PxScene&>(inScene).getPhysics()); PxTolerancesScale theScale; PxSceneDesc theDesc(theScale); { // setDominanceGroupPair ? theDesc.gravity = inScene.getGravity(); theDesc.simulationEventCallback = inScene.getSimulationEventCallback(); theDesc.contactModifyCallback = inScene.getContactModifyCallback(); theDesc.ccdContactModifyCallback = inScene.getCCDContactModifyCallback(); theDesc.filterShaderData = inScene.getFilterShaderData(); theDesc.filterShaderDataSize = inScene.getFilterShaderDataSize(); theDesc.filterShader = inScene.getFilterShader(); theDesc.filterCallback = inScene.getFilterCallback(); // PxPairFilteringMode::Enum KineKineFilteringMode; // PxPairFilteringMode::Enum StaticKineFilteringMode; theDesc.broadPhaseType = inScene.getBroadPhaseType(); theDesc.broadPhaseCallback = inScene.getBroadPhaseCallback(); theDesc.limits = inScene.getLimits(); theDesc.frictionType = inScene.getFrictionType(); // PxSolverType::Enum SolverType; theDesc.bounceThresholdVelocity = inScene.getBounceThresholdVelocity(); theDesc.frictionOffsetThreshold = inScene.getFrictionOffsetThreshold(); theDesc.frictionCorrelationDistance = inScene.getFrictionCorrelationDistance(); theDesc.flags = inScene.getFlags(); theDesc.cpuDispatcher = inScene.getCpuDispatcher(); theDesc.cudaContextManager = inScene.getCudaContextManager(); theDesc.staticStructure = inScene.getStaticStructure(); theDesc.dynamicStructure = inScene.getDynamicStructure(); theDesc.dynamicTreeRebuildRateHint = inScene.getDynamicTreeRebuildRateHint(); theDesc.sceneQueryUpdateMode = inScene.getSceneQueryUpdateMode(); theDesc.userData = inScene.userData; theDesc.solverBatchSize = inScene.getSolverBatchSize(); theDesc.solverArticulationBatchSize = inScene.getSolverArticulationBatchSize(); // PxU32 NbContactDataBlocks; // PxU32 MaxNbContactDataBlocks; // theDesc.nbContactDataBlocks = inScene.getNbContactDataBlocksUsed(); // theDesc.maxNbContactDataBlocks = inScene.getMaxNbContactDataBlocksUsed(); theDesc.maxBiasCoefficient = inScene.getMaxBiasCoefficient(); theDesc.contactReportStreamBufferSize = inScene.getContactReportStreamBufferSize(); theDesc.ccdMaxPasses = inScene.getCCDMaxPasses(); theDesc.ccdThreshold = inScene.getCCDThreshold(); theDesc.ccdMaxSeparation = inScene.getCCDMaxSeparation(); // theDesc.simulationOrder = inScene.getSimulationOrder(); theDesc.wakeCounterResetValue = inScene.getWakeCounterResetValue(); theDesc.gpuDynamicsConfig = inScene.getGpuDynamicsConfig(); // PxBounds3 SanityBounds; // PxgDynamicsMemoryConfig GpuDynamicsConfig; // PxU32 GpuMaxNumPartitions; // PxU32 GpuComputeVersion; // PxReal BroadPhaseInflation; // PxU32 ContactPairSlabSize; } PxSceneDescGeneratedValues theValues(&theDesc); inStream.setPropertyMessage(&inScene, theValues); // Create parent/child relationship. inStream.setPropertyValue(&inScene, "Physics", reinterpret_cast<const void*>(&physics)); inStream.pushBackObjectRef(&physics, "Scenes", &inScene); } void PvdMetaDataBinding::sendBeginFrame(PvdDataStream& inStream, const PxScene* inScene, PxReal simulateElapsedTime) { inStream.beginSection(inScene, "frame"); inStream.setPropertyValue(inScene, "Timestamp", inScene->getTimestamp()); inStream.setPropertyValue(inScene, "SimulateElapsedTime", simulateElapsedTime); } template <typename TDataType> struct NullConverter { void operator()(TDataType& data, const TDataType& src) { data = src; } }; template <typename TTargetType, PxU32 T_NUM_ITEMS, typename TSourceType = TTargetType, typename Converter = NullConverter<TTargetType> > class ScopedPropertyValueSender { TTargetType mStack[T_NUM_ITEMS]; TTargetType* mCur; const TTargetType* mEnd; PvdDataStream& mStream; public: ScopedPropertyValueSender(PvdDataStream& inStream, const void* inObj, String name) : mCur(mStack), mEnd(&mStack[T_NUM_ITEMS]), mStream(inStream) { mStream.beginSetPropertyValue(inObj, name, getPvdNamespacedNameForType<TTargetType>()); } ~ScopedPropertyValueSender() { if(mStack != mCur) { PxU32 size = sizeof(TTargetType) * PxU32(mCur - mStack); mStream.appendPropertyValueData(DataRef<const PxU8>(reinterpret_cast<PxU8*>(mStack), size)); } mStream.endSetPropertyValue(); } void append(const TSourceType& data) { Converter()(*mCur, data); if(mCur < mEnd - 1) ++mCur; else { mStream.appendPropertyValueData(DataRef<const PxU8>(reinterpret_cast<PxU8*>(mStack), sizeof mStack)); mCur = mStack; } } private: ScopedPropertyValueSender& operator=(const ScopedPropertyValueSender&); }; void PvdMetaDataBinding::sendContacts(PvdDataStream& inStream, const PxScene& inScene) { inStream.setPropertyValue(&inScene, "Contacts", DataRef<const PxU8>(), getPvdNamespacedNameForType<PvdContact>()); } void PvdMetaDataBinding::sendStats(PvdDataStream& inStream, const PxScene* inScene) { PxSimulationStatistics theStats; inScene->getSimulationStatistics(theStats); PxSimulationStatisticsGeneratedValues values(&theStats); inStream.setPropertyMessage(inScene, values); } struct PvdContactConverter { void operator()(PvdContact& data, const Sc::Contact& src) { data.point = src.point; data.axis = src.normal; data.shape0 = src.shape0; data.shape1 = src.shape1; data.separation = src.separation; data.normalForce = src.normalForce; data.internalFaceIndex0 = src.faceIndex0; data.internalFaceIndex1 = src.faceIndex1; data.normalForceAvailable = src.normalForceAvailable; } }; void PvdMetaDataBinding::sendContacts(PvdDataStream& inStream, const PxScene& inScene, PxArray<Contact>& inContacts) { ScopedPropertyValueSender<PvdContact, 32, Sc::Contact, PvdContactConverter> sender(inStream, &inScene, "Contacts"); for(PxU32 i = 0; i < inContacts.size(); i++) { sender.append(inContacts[i]); } } void PvdMetaDataBinding::sendEndFrame(PvdDataStream& inStream, const PxScene* inScene) { //flush other client inStream.endSection(inScene, "frame"); } template <typename TDataType> static void addPhysicsGroupProperty(PvdDataStream& inStream, const char* groupName, const TDataType& inData, const PxPhysics& ownerPhysics) { inStream.setPropertyValue(&inData, "Physics", reinterpret_cast<const void*>(&ownerPhysics)); inStream.pushBackObjectRef(&ownerPhysics, groupName, &inData); // Buffer type objects *have* to be flushed directly out once created else scene creation doesn't work. } template <typename TDataType> static void removePhysicsGroupProperty(PvdDataStream& inStream, const char* groupName, const TDataType& inData, const PxPhysics& ownerPhysics) { inStream.removeObjectRef(&ownerPhysics, groupName, &inData); inStream.destroyInstance(&inData); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxMaterial& inMaterial, const PxPhysics& ownerPhysics) { inStream.createInstance(&inMaterial); sendAllProperties(inStream, inMaterial); addPhysicsGroupProperty(inStream, "Materials", inMaterial, ownerPhysics); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxMaterial& inMaterial) { PxMaterialGeneratedValues values(&inMaterial); inStream.setPropertyMessage(&inMaterial, values); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxMaterial& inMaterial, const PxPhysics& ownerPhysics) { removePhysicsGroupProperty(inStream, "Materials", inMaterial, ownerPhysics); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial, const PxPhysics& ownerPhysics) { inStream.createInstance(&inMaterial); sendAllProperties(inStream, inMaterial); addPhysicsGroupProperty(inStream, "FEMMaterials", inMaterial, ownerPhysics); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& /*inStream*/, const PxFEMSoftBodyMaterial& /*inMaterial*/) { /*PxMaterialGeneratedValues values(&inMaterial); inStream.setPropertyMessage(&inMaterial, values);*/ } void PvdMetaDataBinding::destroyInstance(PvdDataStream& /*inStream*/, const PxFEMSoftBodyMaterial& /*inMaterial*/, const PxPhysics& /*ownerPhysics*/) { //removePhysicsGroupProperty(inStream, "Materials", inMaterial, ownerPhysics); } // jcarius: Commented-out until FEMCloth is not under construction anymore // void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial, const PxPhysics& ownerPhysics) // { // inStream.createInstance(&inMaterial); // sendAllProperties(inStream, inMaterial); // addPhysicsGroupProperty(inStream, "FEMMaterials", inMaterial, ownerPhysics); // } // void PvdMetaDataBinding::sendAllProperties(PvdDataStream& /*inStream*/, const PxFEMClothMaterial& /*inMaterial*/) // { // /*PxMaterialGeneratedValues values(&inMaterial); // inStream.setPropertyMessage(&inMaterial, values);*/ // } // void PvdMetaDataBinding::destroyInstance(PvdDataStream& /*inStream*/, const PxFEMClothMaterial& /*inMaterial*/, const PxPhysics& /*ownerPhysics*/) // { // //removePhysicsGroupProperty(inStream, "Materials", inMaterial, ownerPhysics); // } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxPBDMaterial& inMaterial, const PxPhysics& ownerPhysics) { inStream.createInstance(&inMaterial); sendAllProperties(inStream, inMaterial); addPhysicsGroupProperty(inStream, "PBDMaterials", inMaterial, ownerPhysics); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& /*inStream*/, const PxPBDMaterial& /*inMaterial*/) { /*PxMaterialGeneratedValues values(&inMaterial); inStream.setPropertyMessage(&inMaterial, values);*/ } void PvdMetaDataBinding::destroyInstance(PvdDataStream& /*inStream*/, const PxPBDMaterial& /*inMaterial*/, const PxPhysics& /*ownerPhysics*/) { //removePhysicsGroupProperty(inStream, "Materials", inMaterial, ownerPhysics); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxHeightField& inData) { PxHeightFieldDesc theDesc; // Save the height field to desc. theDesc.nbRows = inData.getNbRows(); theDesc.nbColumns = inData.getNbColumns(); theDesc.format = inData.getFormat(); theDesc.samples.stride = inData.getSampleStride(); theDesc.samples.data = NULL; theDesc.convexEdgeThreshold = inData.getConvexEdgeThreshold(); theDesc.flags = inData.getFlags(); PxU32 theCellCount = inData.getNbRows() * inData.getNbColumns(); PxU32 theSampleStride = sizeof(PxHeightFieldSample); PxU32 theSampleBufSize = theCellCount * theSampleStride; mBindingData->mTempU8Array.resize(theSampleBufSize); PxHeightFieldSample* theSamples = reinterpret_cast<PxHeightFieldSample*>(mBindingData->mTempU8Array.begin()); inData.saveCells(theSamples, theSampleBufSize); theDesc.samples.data = theSamples; PxHeightFieldDescGeneratedValues values(&theDesc); inStream.setPropertyMessage(&inData, values); PxHeightFieldSample* theSampleData = reinterpret_cast<PxHeightFieldSample*>(mBindingData->mTempU8Array.begin()); inStream.setPropertyValue(&inData, "Samples", theSampleData, theCellCount); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxHeightField& inData, const PxPhysics& ownerPhysics) { inStream.createInstance(&inData); sendAllProperties(inStream, inData); addPhysicsGroupProperty(inStream, "HeightFields", inData, ownerPhysics); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxHeightField& inData, const PxPhysics& ownerPhysics) { removePhysicsGroupProperty(inStream, "HeightFields", inData, ownerPhysics); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxConvexMesh& inData, const PxPhysics& ownerPhysics) { inStream.createInstance(&inData); PxReal mass; PxMat33 localInertia; PxVec3 localCom; inData.getMassInformation(mass, localInertia, localCom); inStream.setPropertyValue(&inData, "Mass", mass); inStream.setPropertyValue(&inData, "LocalInertia", localInertia); inStream.setPropertyValue(&inData, "LocalCenterOfMass", localCom); // update arrays: // vertex Array: { const PxVec3* vertexPtr = inData.getVertices(); const PxU32 numVertices = inData.getNbVertices(); inStream.setPropertyValue(&inData, "Points", vertexPtr, numVertices); } // HullPolyArray: PxU16 maxIndices = 0; { PxU32 numPolygons = inData.getNbPolygons(); PvdHullPolygonData* tempData = mBindingData->allocateTemp<PvdHullPolygonData>(numPolygons); // Get the polygon data stripping the plane equations for(PxU32 index = 0; index < numPolygons; index++) { PxHullPolygon curOut; inData.getPolygonData(index, curOut); maxIndices = PxMax(maxIndices, PxU16(curOut.mIndexBase + curOut.mNbVerts)); tempData[index].mIndexBase = curOut.mIndexBase; tempData[index].mNumVertices = curOut.mNbVerts; } inStream.setPropertyValue(&inData, "HullPolygons", tempData, numPolygons); } // poly index Array: { const PxU8* indices = inData.getIndexBuffer(); inStream.setPropertyValue(&inData, "PolygonIndexes", indices, maxIndices); } addPhysicsGroupProperty(inStream, "ConvexMeshes", inData, ownerPhysics); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxConvexMesh& inData, const PxPhysics& ownerPhysics) { removePhysicsGroupProperty(inStream, "ConvexMeshes", inData, ownerPhysics); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxTetrahedronMesh& inData, const PxPhysics& ownerPhysics) { inStream.createInstance(&inData); // vertex Array: { const PxVec3* vertexPtr = inData.getVertices(); const PxU32 numVertices = inData.getNbVertices(); inStream.setPropertyValue(&inData, "Vertices", vertexPtr, numVertices); } ////invert mass array //{ // const float* invMassPtr = inData.getVertInvMasses(); // const PxU32 numVertices = inData.getCollisionMesh().getNbVertices(); // inStream.setPropertyValue(&inData, "invert mass", invMassPtr, numVertices); //} // index Array: { const bool has16BitIndices = inData.getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES ? true : false; const PxU32 numTetrahedrons= inData.getNbTetrahedrons(); inStream.setPropertyValue(&inData, "NbTetrahedron", numTetrahedrons); const PxU32 numIndexes = numTetrahedrons * 4; const PxU8* tetrahedronsPtr = reinterpret_cast<const PxU8*>(inData.getTetrahedrons()); // We declared this type as a 32 bit integer above. // PVD will automatically unsigned-extend data that is smaller than the target type. if (has16BitIndices) inStream.setPropertyValue(&inData, "Tetrahedrons", reinterpret_cast<const PxU16*>(tetrahedronsPtr), numIndexes); else inStream.setPropertyValue(&inData, "Tetrahedrons", reinterpret_cast<const PxU32*>(tetrahedronsPtr), numIndexes); } addPhysicsGroupProperty(inStream, "TetrahedronMeshes", inData, ownerPhysics); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxTetrahedronMesh& inData, const PxPhysics& ownerPhysics) { removePhysicsGroupProperty(inStream, "TetrahedronMeshes", inData, ownerPhysics); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxTriangleMesh& inData, const PxPhysics& ownerPhysics) { inStream.createInstance(&inData); bool hasMatIndex = inData.getTriangleMaterialIndex(0) != 0xffff; // update arrays: // vertex Array: { const PxVec3* vertexPtr = inData.getVertices(); const PxU32 numVertices = inData.getNbVertices(); inStream.setPropertyValue(&inData, "Points", vertexPtr, numVertices); } // index Array: { const bool has16BitIndices = inData.getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES ? true : false; const PxU32 numTriangles = inData.getNbTriangles(); inStream.setPropertyValue(&inData, "NbTriangles", numTriangles); const PxU32 numIndexes = numTriangles * 3; const PxU8* trianglePtr = reinterpret_cast<const PxU8*>(inData.getTriangles()); // We declared this type as a 32 bit integer above. // PVD will automatically unsigned-extend data that is smaller than the target type. if(has16BitIndices) inStream.setPropertyValue(&inData, "Triangles", reinterpret_cast<const PxU16*>(trianglePtr), numIndexes); else inStream.setPropertyValue(&inData, "Triangles", reinterpret_cast<const PxU32*>(trianglePtr), numIndexes); } // material Array: if(hasMatIndex) { PxU32 numMaterials = inData.getNbTriangles(); PxU16* matIndexData = mBindingData->allocateTemp<PxU16>(numMaterials); for(PxU32 m = 0; m < numMaterials; m++) matIndexData[m] = inData.getTriangleMaterialIndex(m); inStream.setPropertyValue(&inData, "MaterialIndices", matIndexData, numMaterials); } addPhysicsGroupProperty(inStream, "TriangleMeshes", inData, ownerPhysics); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxTriangleMesh& inData, const PxPhysics& ownerPhysics) { removePhysicsGroupProperty(inStream, "TriangleMeshes", inData, ownerPhysics); } template <typename TDataType> void PvdMetaDataBinding::registrarPhysicsObject(PvdDataStream&, const TDataType&, PsPvd*) { } template <> void PvdMetaDataBinding::registrarPhysicsObject<PxConvexMeshGeometry>(PvdDataStream& inStream, const PxConvexMeshGeometry& geom, PsPvd* pvd) { if(pvd->registerObject(geom.convexMesh)) createInstance(inStream, *geom.convexMesh, PxGetPhysics()); } template <> void PvdMetaDataBinding::registrarPhysicsObject<PxTetrahedronMeshGeometry>(PvdDataStream& inStream, const PxTetrahedronMeshGeometry& geom, PsPvd* pvd) { if (pvd->registerObject(geom.tetrahedronMesh)) createInstance(inStream, *geom.tetrahedronMesh, PxGetPhysics()); } template <> void PvdMetaDataBinding::registrarPhysicsObject<PxTriangleMeshGeometry>(PvdDataStream& inStream, const PxTriangleMeshGeometry& geom, PsPvd* pvd) { if(pvd->registerObject(geom.triangleMesh)) createInstance(inStream, *geom.triangleMesh, PxGetPhysics()); } template <> void PvdMetaDataBinding::registrarPhysicsObject<PxHeightFieldGeometry>(PvdDataStream& inStream, const PxHeightFieldGeometry& geom, PsPvd* pvd) { if(pvd->registerObject(geom.heightField)) createInstance(inStream, *geom.heightField, PxGetPhysics()); } template <typename TGeneratedValuesType, typename TGeomType> static void sendGeometry(PvdMetaDataBinding& metaBind, PvdDataStream& inStream, const PxShape& inShape, const TGeomType& geom, PsPvd* pvd) { const void* geomInst = (reinterpret_cast<const PxU8*>(&inShape)) + 4; inStream.createInstance(getPvdNamespacedNameForType<TGeomType>(), geomInst); metaBind.registrarPhysicsObject<TGeomType>(inStream, geom, pvd); TGeneratedValuesType values(&geom); inStream.setPropertyMessage(geomInst, values); inStream.setPropertyValue(&inShape, "Geometry", geomInst); inStream.setPropertyValue(geomInst, "Shape", reinterpret_cast<const void*>(&inShape)); } static void setGeometry(PvdMetaDataBinding& metaBind, PvdDataStream& inStream, const PxShape& inObj, PsPvd* pvd) { const PxGeometry& geom = inObj.getGeometry(); switch(geom.getType()) { #define SEND_PVD_GEOM_TYPE(enumType, geomType, valueType) \ case PxGeometryType::enumType: \ { \ Px##geomType geomT = static_cast<const Px##geomType&>(geom); \ sendGeometry<valueType>(metaBind, inStream, inObj, geomT, pvd); \ } \ break; SEND_PVD_GEOM_TYPE(eSPHERE, SphereGeometry, PxSphereGeometryGeneratedValues); // Plane geometries don't have any properties, so this avoids using a property // struct for them. case PxGeometryType::ePLANE: { const void* geomInst = (reinterpret_cast<const PxU8*>(&inObj)) + 4; inStream.createInstance(getPvdNamespacedNameForType<PxPlaneGeometry>(), geomInst); inStream.setPropertyValue(&inObj, "Geometry", geomInst); inStream.setPropertyValue(geomInst, "Shape", reinterpret_cast<const void*>(&inObj)); } break; SEND_PVD_GEOM_TYPE(eCAPSULE, CapsuleGeometry, PxCapsuleGeometryGeneratedValues); SEND_PVD_GEOM_TYPE(eBOX, BoxGeometry, PxBoxGeometryGeneratedValues); SEND_PVD_GEOM_TYPE(eCONVEXMESH, ConvexMeshGeometry, PxConvexMeshGeometryGeneratedValues); SEND_PVD_GEOM_TYPE(eTETRAHEDRONMESH, TetrahedronMeshGeometry, PxTetrahedronMeshGeometryGeneratedValues); SEND_PVD_GEOM_TYPE(eTRIANGLEMESH, TriangleMeshGeometry, PxTriangleMeshGeometryGeneratedValues); SEND_PVD_GEOM_TYPE(eHEIGHTFIELD, HeightFieldGeometry, PxHeightFieldGeometryGeneratedValues); SEND_PVD_GEOM_TYPE(eCUSTOM, CustomGeometry, PxCustomGeometryGeneratedValues); #undef SEND_PVD_GEOM_TYPE case PxGeometryType::ePARTICLESYSTEM: // A.B. implement later break; case PxGeometryType::eHAIRSYSTEM: break; case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: PX_ASSERT(false); break; } } static void setMaterials(PvdMetaDataBinding& metaBing, PvdDataStream& inStream, const PxShape& inObj, PsPvd* pvd, PvdMetaDataBindingData* mBindingData) { PxU32 numMaterials = inObj.getNbMaterials(); PxMaterial** materialPtr = mBindingData->allocateTemp<PxMaterial*>(numMaterials); inObj.getMaterials(materialPtr, numMaterials); for(PxU32 idx = 0; idx < numMaterials; ++idx) { if(pvd->registerObject(materialPtr[idx])) metaBing.createInstance(inStream, *materialPtr[idx], PxGetPhysics()); inStream.pushBackObjectRef(&inObj, "Materials", materialPtr[idx]); } } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxShape& inObj, const PxRigidActor& owner, const PxPhysics& ownerPhysics, PsPvd* pvd) { if(!inStream.isInstanceValid(&owner)) return; const OwnerActorsMap::Entry* entry = mBindingData->mOwnerActorsMap.find(&inObj); if(entry != NULL) { if(!mBindingData->mOwnerActorsMap[&inObj]->contains(&owner)) mBindingData->mOwnerActorsMap[&inObj]->insert(&owner); } else { OwnerActorsValueType* data = reinterpret_cast<OwnerActorsValueType*>( PX_ALLOC(sizeof(OwnerActorsValueType), "mOwnerActorsMapValue")); //( 1 ); OwnerActorsValueType* actors = PX_PLACEMENT_NEW(data, OwnerActorsValueType); actors->insert(&owner); mBindingData->mOwnerActorsMap.insert(&inObj, actors); } if(inStream.isInstanceValid(&inObj)) { inStream.pushBackObjectRef(&owner, "Shapes", &inObj); return; } inStream.createInstance(&inObj); inStream.pushBackObjectRef(&owner, "Shapes", &inObj); inStream.setPropertyValue(&inObj, "Actor", reinterpret_cast<const void*>(&owner)); sendAllProperties(inStream, inObj); setGeometry(*this, inStream, inObj, pvd); setMaterials(*this, inStream, inObj, pvd, mBindingData); if(!inObj.isExclusive()) inStream.pushBackObjectRef(&ownerPhysics, "SharedShapes", &inObj); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxShape& inObj) { PxShapeGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::releaseAndRecreateGeometry(PvdDataStream& inStream, const PxShape& inObj, PxPhysics& /*ownerPhysics*/, PsPvd* pvd) { const void* geomInst = (reinterpret_cast<const PxU8*>(&inObj)) + 4; inStream.destroyInstance(geomInst); const PxGeometry& geom = inObj.getGeometry(); // Quick fix for HF modify, PxConvexMesh and PxTriangleMesh need recook, they should always be new if modified if(geom.getType() == PxGeometryType::eHEIGHTFIELD) { const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom); if(inStream.isInstanceValid(hfGeom.heightField)) sendAllProperties(inStream, *hfGeom.heightField); } setGeometry(*this, inStream, inObj, pvd); // Need update actor cause PVD takes actor-shape as a pair. { PxRigidActor* actor = inObj.getActor(); if(actor != NULL) { if(const PxRigidStatic* rgS = actor->is<PxRigidStatic>()) sendAllProperties(inStream, *rgS); else if(const PxRigidDynamic* rgD = actor->is<PxRigidDynamic>()) sendAllProperties(inStream, *rgD); } } } void PvdMetaDataBinding::updateMaterials(PvdDataStream& inStream, const PxShape& inObj, PsPvd* pvd) { // Clear the shape's materials array. inStream.setPropertyValue(&inObj, "Materials", DataRef<const PxU8>(), getPvdNamespacedNameForType<ObjectRef>()); setMaterials(*this, inStream, inObj, pvd, mBindingData); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxShape& inObj, const PxRigidActor& owner) { if(inStream.isInstanceValid(&inObj)) { inStream.removeObjectRef(&owner, "Shapes", &inObj); bool bDestroy = true; const OwnerActorsMap::Entry* entry0 = mBindingData->mOwnerActorsMap.find(&inObj); if(entry0 != NULL) { entry0->second->erase(&owner); if(entry0->second->size() > 0) bDestroy = false; else { mBindingData->mOwnerActorsMap[&inObj]->~OwnerActorsValueType(); PX_FREE(mBindingData->mOwnerActorsMap[&inObj]); mBindingData->mOwnerActorsMap.erase(&inObj); } } if(bDestroy) { if(!inObj.isExclusive()) inStream.removeObjectRef(&PxGetPhysics(), "SharedShapes", &inObj); const void* geomInst = (reinterpret_cast<const PxU8*>(&inObj)) + 4; inStream.destroyInstance(geomInst); inStream.destroyInstance(&inObj); const OwnerActorsMap::Entry* entry = mBindingData->mOwnerActorsMap.find(&inObj); if(entry != NULL) { entry->second->~OwnerActorsValueType(); OwnerActorsValueType* ptr = entry->second; PX_FREE(ptr); mBindingData->mOwnerActorsMap.erase(&inObj); } } } } template <typename TDataType> static void addSceneGroupProperty(PvdDataStream& inStream, const char* groupName, const TDataType& inObj, const PxScene& inScene) { inStream.createInstance(&inObj); inStream.pushBackObjectRef(&inScene, groupName, &inObj); inStream.setPropertyValue(&inObj, "Scene", reinterpret_cast<const void*>(&inScene)); } template <typename TDataType> static void removeSceneGroupProperty(PvdDataStream& inStream, const char* groupName, const TDataType& inObj, const PxScene& inScene) { inStream.removeObjectRef(&inScene, groupName, &inObj); inStream.destroyInstance(&inObj); } static void sendShapes(PvdMetaDataBinding& binding, PvdDataStream& inStream, const PxRigidActor& inObj, const PxPhysics& ownerPhysics, PsPvd* pvd) { PxInlineArray<PxShape*, 5> shapeData; PxU32 nbShapes = inObj.getNbShapes(); shapeData.resize(nbShapes); inObj.getShapes(shapeData.begin(), nbShapes); for(PxU32 idx = 0; idx < nbShapes; ++idx) binding.createInstance(inStream, *shapeData[idx], inObj, ownerPhysics, pvd); } static void releaseShapes(PvdMetaDataBinding& binding, PvdDataStream& inStream, const PxRigidActor& inObj) { PxInlineArray<PxShape*, 5> shapeData; PxU32 nbShapes = inObj.getNbShapes(); shapeData.resize(nbShapes); inObj.getShapes(shapeData.begin(), nbShapes); for(PxU32 idx = 0; idx < nbShapes; ++idx) binding.destroyInstance(inStream, *shapeData[idx], inObj); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxRigidStatic& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { addSceneGroupProperty(inStream, "RigidStatics", inObj, ownerScene); sendAllProperties(inStream, inObj); sendShapes(*this, inStream, inObj, ownerPhysics, pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxRigidStatic& inObj) { PxRigidStaticGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxRigidStatic& inObj, const PxScene& ownerScene) { releaseShapes(*this, inStream, inObj); removeSceneGroupProperty(inStream, "RigidStatics", inObj, ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxRigidDynamic& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { addSceneGroupProperty(inStream, "RigidDynamics", inObj, ownerScene); sendAllProperties(inStream, inObj); sendShapes(*this, inStream, inObj, ownerPhysics, pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxRigidDynamic& inObj) { PxRigidDynamicGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxRigidDynamic& inObj, const PxScene& ownerScene) { releaseShapes(*this, inStream, inObj); removeSceneGroupProperty(inStream, "RigidDynamics", inObj, ownerScene); } static void addChild(PvdDataStream& inStream, const void* inParent, const PxArticulationLink& inChild) { inStream.pushBackObjectRef(inParent, "Links", &inChild); inStream.setPropertyValue(&inChild, "Parent", inParent); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { addSceneGroupProperty(inStream, "Articulations", inObj, ownerScene); sendAllProperties(inStream, inObj); PxU32 numLinks = inObj.getNbLinks(); mBindingData->mArticulationLinks.resize(numLinks); inObj.getLinks(mBindingData->mArticulationLinks.begin(), numLinks); // From Dilip Sequiera: /* No, there can only be one root, and in all the code I wrote (which is not 100% of the HL code for articulations), the index of a child is always > the index of the parent. */ // Create all the links for(PxU32 idx = 0; idx < numLinks; ++idx) { if(!inStream.isInstanceValid(mBindingData->mArticulationLinks[idx])) createInstance(inStream, *mBindingData->mArticulationLinks[idx], ownerPhysics, pvd); } // Setup the link graph for(PxU32 idx = 0; idx < numLinks; ++idx) { PxArticulationLink* link = mBindingData->mArticulationLinks[idx]; if(idx == 0) addChild(inStream, &inObj, *link); PxU32 numChildren = link->getNbChildren(); PxArticulationLink** children = mBindingData->allocateTemp<PxArticulationLink*>(numChildren); link->getChildren(children, numChildren); for(PxU32 i = 0; i < numChildren; ++i) addChild(inStream, link, *children[i]); } } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj) { PxArticulationReducedCoordinateGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj, const PxScene& ownerScene) { removeSceneGroupProperty(inStream, "Articulations", inObj, ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxArticulationLink& inObj, const PxPhysics& ownerPhysics, PsPvd* pvd) { inStream.createInstance(&inObj); PxArticulationJointReducedCoordinate* joint(inObj.getInboundJoint()); if(joint) { inStream.createInstance(joint); inStream.setPropertyValue(&inObj, "InboundJoint", reinterpret_cast<const void*>(joint)); inStream.setPropertyValue(joint, "Link", reinterpret_cast<const void*>(&inObj)); sendAllProperties(inStream, *joint); } sendAllProperties(inStream, inObj); sendShapes(*this, inStream, inObj, ownerPhysics, pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxArticulationLink& inObj) { PxArticulationLinkGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxArticulationLink& inObj) { PxArticulationJointReducedCoordinate* joint(inObj.getInboundJoint()); if(joint) inStream.destroyInstance(joint); releaseShapes(*this, inStream, inObj); inStream.destroyInstance(&inObj); } // These are created as part of the articulation link's creation process, so outside entities don't need to // create them. void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxArticulationJointReducedCoordinate& inObj) { PxArticulationJointReducedCoordinateGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxSoftBody& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); PX_UNUSED(ownerPhysics); PX_UNUSED(pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxSoftBody& inObj) { PX_UNUSED(inStream); PX_UNUSED(inObj); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxSoftBody& inObj, const PxScene& ownerScene) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxFEMCloth& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); PX_UNUSED(ownerPhysics); PX_UNUSED(pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxFEMCloth& inObj) { PX_UNUSED(inStream); PX_UNUSED(inObj); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxFEMCloth& inObj, const PxScene& ownerScene) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxPBDParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); PX_UNUSED(ownerPhysics); PX_UNUSED(pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxPBDParticleSystem& inObj) { PX_UNUSED(inStream); PX_UNUSED(inObj); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxPBDParticleSystem& inObj, const PxScene& ownerScene) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); PX_UNUSED(ownerPhysics); PX_UNUSED(pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj) { PX_UNUSED(inStream); PX_UNUSED(inObj); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj, const PxScene& ownerScene) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxMPMParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); PX_UNUSED(ownerPhysics); PX_UNUSED(pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxMPMParticleSystem& inObj) { PX_UNUSED(inStream); PX_UNUSED(inObj); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxMPMParticleSystem& inObj, const PxScene& ownerScene) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); } void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxHairSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); PX_UNUSED(ownerPhysics); PX_UNUSED(pvd); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxHairSystem& inObj) { PX_UNUSED(inStream); PX_UNUSED(inObj); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxHairSystem& inObj, const PxScene& ownerScene) { PX_UNUSED(inStream); PX_UNUSED(inObj); PX_UNUSED(ownerScene); } void PvdMetaDataBinding::originShift(PvdDataStream& inStream, const PxScene* inScene, PxVec3 shift) { inStream.originShift(inScene, shift); } template <typename TBlockType, typename TActorType, typename TOperator> static void updateActor(PvdDataStream& inStream, TActorType** actorGroup, PxU32 numActors, TOperator sleepingOp, PvdMetaDataBindingData& bindingData) { TBlockType theBlock; if(numActors == 0) return; for(PxU32 idx = 0; idx < numActors; ++idx) { TActorType* theActor(actorGroup[idx]); bool sleeping = sleepingOp(theActor, theBlock); bool wasSleeping = bindingData.mSleepingActors.contains(theActor); if(sleeping == false || sleeping != wasSleeping) { theBlock.GlobalPose = theActor->getGlobalPose(); theBlock.AngularVelocity = theActor->getAngularVelocity(); theBlock.LinearVelocity = theActor->getLinearVelocity(); inStream.sendPropertyMessageFromGroup(theActor, theBlock); if(sleeping != wasSleeping) { if(sleeping) bindingData.mSleepingActors.insert(theActor); else bindingData.mSleepingActors.erase(theActor); } } } } struct RigidDynamicUpdateOp { bool operator()(PxRigidDynamic* actor, PxRigidDynamicUpdateBlock& block) { bool sleeping = actor->isSleeping(); block.IsSleeping = sleeping; return sleeping; } }; struct ArticulationLinkUpdateOp { bool sleeping; ArticulationLinkUpdateOp(bool s) : sleeping(s) { } bool operator()(PxArticulationLink*, PxArticulationLinkUpdateBlock&) { return sleeping; } }; void PvdMetaDataBinding::updateDynamicActorsAndArticulations(PvdDataStream& inStream, const PxScene* inScene, PvdVisualizer* linkJointViz) { PX_COMPILE_TIME_ASSERT(sizeof(PxRigidDynamicUpdateBlock) == 14 * 4); { PxU32 actorCount = inScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC); if(actorCount) { inStream.beginPropertyMessageGroup<PxRigidDynamicUpdateBlock>(); mBindingData->mActors.resize(actorCount); PxActor** theActors = mBindingData->mActors.begin(); inScene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC, theActors, actorCount); updateActor<PxRigidDynamicUpdateBlock>(inStream, reinterpret_cast<PxRigidDynamic**>(theActors), actorCount, RigidDynamicUpdateOp(), *mBindingData); inStream.endPropertyMessageGroup(); } } { PxU32 articulationCount = inScene->getNbArticulations(); if(articulationCount) { mBindingData->mArticulations.resize(articulationCount); PxArticulationReducedCoordinate** firstArticulation = mBindingData->mArticulations.begin(); PxArticulationReducedCoordinate** lastArticulation = firstArticulation + articulationCount; inScene->getArticulations(firstArticulation, articulationCount); inStream.beginPropertyMessageGroup<PxArticulationLinkUpdateBlock>(); for(; firstArticulation < lastArticulation; ++firstArticulation) { PxU32 linkCount = (*firstArticulation)->getNbLinks(); bool sleeping = (*firstArticulation)->isSleeping(); if(linkCount) { mBindingData->mArticulationLinks.resize(linkCount); PxArticulationLink** theLink = mBindingData->mArticulationLinks.begin(); (*firstArticulation)->getLinks(theLink, linkCount); updateActor<PxArticulationLinkUpdateBlock>(inStream, theLink, linkCount, ArticulationLinkUpdateOp(sleeping), *mBindingData); if(linkJointViz) { for(PxU32 idx = 0; idx < linkCount; ++idx) linkJointViz->visualize(*theLink[idx]); } } } inStream.endPropertyMessageGroup(); firstArticulation = mBindingData->mArticulations.begin(); for (; firstArticulation < lastArticulation; ++firstArticulation) { inStream.setPropertyValue(*firstArticulation, "IsSleeping", (*firstArticulation)->isSleeping()); inStream.setPropertyValue(*firstArticulation, "RootGlobalPose", (*firstArticulation)->getRootGlobalPose()); inStream.setPropertyValue(*firstArticulation, "RootLinearVelocity", (*firstArticulation)->getRootLinearVelocity()); inStream.setPropertyValue(*firstArticulation, "RootAngularVelocity", (*firstArticulation)->getRootAngularVelocity()); } inStream.beginPropertyMessageGroup<PxArticulationJointUpdateBlock>(); firstArticulation = mBindingData->mArticulations.begin(); for (; firstArticulation < lastArticulation; ++firstArticulation) { PxU32 linkCount = (*firstArticulation)->getNbLinks(); bool sleeping = (*firstArticulation)->isSleeping(); if (!sleeping) { for (PxU32 idx = 1; idx < linkCount; ++idx) { mBindingData->mArticulationLinks.resize(linkCount); PxArticulationLink** theLink = mBindingData->mArticulationLinks.begin(); (*firstArticulation)->getLinks(theLink, linkCount); PxArticulationJointUpdateBlock jointBlock; PxArticulationJointReducedCoordinate* joint = theLink[idx]->getInboundJoint(); jointBlock.JointPosition_eX = joint->getJointPosition(PxArticulationAxis::eX); jointBlock.JointPosition_eY = joint->getJointPosition(PxArticulationAxis::eY); jointBlock.JointPosition_eZ = joint->getJointPosition(PxArticulationAxis::eZ); jointBlock.JointPosition_eTwist = joint->getJointPosition(PxArticulationAxis::eTWIST); jointBlock.JointPosition_eSwing1 = joint->getJointPosition(PxArticulationAxis::eSWING1); jointBlock.JointPosition_eSwing2 = joint->getJointPosition(PxArticulationAxis::eSWING2); jointBlock.JointVelocity_eX = joint->getJointVelocity(PxArticulationAxis::eX); jointBlock.JointVelocity_eY = joint->getJointVelocity(PxArticulationAxis::eY); jointBlock.JointVelocity_eZ = joint->getJointVelocity(PxArticulationAxis::eZ); jointBlock.JointVelocity_eTwist = joint->getJointVelocity(PxArticulationAxis::eTWIST); jointBlock.JointVelocity_eSwing1 = joint->getJointVelocity(PxArticulationAxis::eSWING1); jointBlock.JointVelocity_eSwing2 = joint->getJointVelocity(PxArticulationAxis::eSWING2); inStream.sendPropertyMessageFromGroup(joint, jointBlock); } } } inStream.endPropertyMessageGroup(); } } } template <typename TObjType> struct CollectionOperator { PxArray<PxU8>& mTempArray; const TObjType& mObject; PvdDataStream& mStream; CollectionOperator(PxArray<PxU8>& ary, const TObjType& obj, PvdDataStream& stream) : mTempArray(ary), mObject(obj), mStream(stream) { } void pushName(const char*) { } void popName() { } template <typename TAccessor> void simpleProperty(PxU32 /*key*/, const TAccessor&) { } template <typename TAccessor> void flagsProperty(PxU32 /*key*/, const TAccessor&, const PxU32ToName*) { } template <typename TColType, typename TDataType, typename TCollectionProp> void handleCollection(const TCollectionProp& prop, NamespacedName dtype, PxU32 countMultiplier = 1) { PxU32 count = prop.size(&mObject); mTempArray.resize(count * sizeof(TDataType)); TColType* start = reinterpret_cast<TColType*>(mTempArray.begin()); prop.get(&mObject, start, count * countMultiplier); mStream.setPropertyValue(&mObject, prop.mName, DataRef<const PxU8>(mTempArray.begin(), mTempArray.size()), dtype); } template <PxU32 TKey, typename TObject, typename TColType> void handleCollection(const PxReadOnlyCollectionPropertyInfo<TKey, TObject, TColType>& prop) { handleCollection<TColType, TColType>(prop, getPvdNamespacedNameForType<TColType>()); } // Enumerations or bitflags. template <PxU32 TKey, typename TObject, typename TColType> void handleCollection(const PxReadOnlyCollectionPropertyInfo<TKey, TObject, TColType>& prop, const PxU32ToName*) { PX_COMPILE_TIME_ASSERT(sizeof(TColType) == sizeof(PxU32)); handleCollection<TColType, PxU32>(prop, getPvdNamespacedNameForType<PxU32>()); } private: CollectionOperator& operator=(const CollectionOperator&); }; // per frame update #define ENABLE_AGGREGATE_PVD_SUPPORT 1 #ifdef ENABLE_AGGREGATE_PVD_SUPPORT void PvdMetaDataBinding::createInstance(PvdDataStream& inStream, const PxAggregate& inObj, const PxScene& ownerScene) { addSceneGroupProperty(inStream, "Aggregates", inObj, ownerScene); sendAllProperties(inStream, inObj); } void PvdMetaDataBinding::sendAllProperties(PvdDataStream& inStream, const PxAggregate& inObj) { PxAggregateGeneratedValues values(&inObj); inStream.setPropertyMessage(&inObj, values); } void PvdMetaDataBinding::destroyInstance(PvdDataStream& inStream, const PxAggregate& inObj, const PxScene& ownerScene) { removeSceneGroupProperty(inStream, "Aggregates", inObj, ownerScene); } class ChangeOjectRefCmd : public PvdDataStream::PvdCommand { ChangeOjectRefCmd& operator=(const ChangeOjectRefCmd&) { PX_ASSERT(0); return *this; } // PX_NOCOPY doesn't work for local classes public: const void* mInstance; String mPropName; const void* mPropObj; const bool mPushBack; ChangeOjectRefCmd(const void* inInst, String inName, const void* inObj, bool pushBack) : mInstance(inInst), mPropName(inName), mPropObj(inObj), mPushBack(pushBack) { } // Assigned is needed for copying ChangeOjectRefCmd(const ChangeOjectRefCmd& other) : PvdDataStream::PvdCommand(other), mInstance(other.mInstance), mPropName(other.mPropName), mPropObj(other.mPropObj), mPushBack(other.mPushBack) { } virtual bool canRun(PvdInstanceDataStream& inStream) { PX_ASSERT(inStream.isInstanceValid(mInstance)); return inStream.isInstanceValid(mPropObj); } virtual void run(PvdInstanceDataStream& inStream) { if(!inStream.isInstanceValid(mInstance)) return; if(mPushBack) { if(inStream.isInstanceValid(mPropObj)) inStream.pushBackObjectRef(mInstance, mPropName, mPropObj); } else { // the called function will assert if propobj is already removed inStream.removeObjectRef(mInstance, mPropName, mPropObj); } } }; static void changeAggregateSubActors(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor, bool pushBack) { const PxArticulationLink* link = inActor.is<PxArticulationLink>(); String propName = NULL; const void* object = NULL; if(link == NULL) { propName = "Actors"; object = &inActor; } else if(link->getInboundJoint() == NULL) { propName = "Articulations"; object = &link->getArticulation(); } else return; ChangeOjectRefCmd* cmd = PX_PLACEMENT_NEW(inStream.allocateMemForCmd(sizeof(ChangeOjectRefCmd)), ChangeOjectRefCmd)(&inObj, propName, object, pushBack); if(cmd->canRun(inStream)) cmd->run(inStream); else inStream.pushPvdCommand(*cmd); } void PvdMetaDataBinding::detachAggregateActor(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor) { changeAggregateSubActors(inStream, inObj, inActor, false); } void PvdMetaDataBinding::attachAggregateActor(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor) { changeAggregateSubActors(inStream, inObj, inActor, true); } #else void PvdMetaDataBinding::createInstance(PvdDataStream&, const PxAggregate&, const PxScene&, ObjectRegistrar&) { } void PvdMetaDataBinding::sendAllProperties(PvdDataStream&, const PxAggregate&) { } void PvdMetaDataBinding::destroyInstance(PvdDataStream&, const PxAggregate&, const PxScene&) { } void PvdMetaDataBinding::detachAggregateActor(PvdDataStream&, const PxAggregate&, const PxActor&) { } void PvdMetaDataBinding::attachAggregateActor(PvdDataStream&, const PxAggregate&, const PxActor&) { } #endif template <typename TDataType> static void sendSceneArray(PvdDataStream& inStream, const PxScene& inScene, const PxArray<TDataType>& inArray, const char* propName) { if(0 == inArray.size()) inStream.setPropertyValue(&inScene, propName, DataRef<const PxU8>(), getPvdNamespacedNameForType<TDataType>()); else { ScopedPropertyValueSender<TDataType, 32> sender(inStream, &inScene, propName); for(PxU32 i = 0; i < inArray.size(); ++i) sender.append(inArray[i]); } } static void sendSceneArray(PvdDataStream& inStream, const PxScene& inScene, const PxArray<PvdSqHit>& inArray, const char* propName) { if(0 == inArray.size()) inStream.setPropertyValue(&inScene, propName, DataRef<const PxU8>(), getPvdNamespacedNameForType<PvdSqHit>()); else { ScopedPropertyValueSender<PvdSqHit, 32> sender(inStream, &inScene, propName); for(PxU32 i = 0; i < inArray.size(); ++i) { if(!inStream.isInstanceValid(inArray[i].mShape) || !inStream.isInstanceValid(inArray[i].mActor)) { PvdSqHit hit = inArray[i]; hit.mShape = NULL; hit.mActor = NULL; sender.append(hit); } else sender.append(inArray[i]); } } } void PvdMetaDataBinding::sendSceneQueries(PvdDataStream& inStream, const PxScene& inScene, PsPvd* pvd) { if(!inStream.isConnected()) return; const physx::NpScene& scene = static_cast<const NpScene&>(inScene); { PvdSceneQueryCollector& collector = scene.getNpSQ().getSingleSqCollector(); PxMutex::ScopedLock lock(collector.getLock()); String propName = collector.getArrayName(collector.mPvdSqHits); sendSceneArray(inStream, inScene, collector.mPvdSqHits, propName); propName = collector.getArrayName(collector.mPoses); sendSceneArray(inStream, inScene, collector.mPoses, propName); propName = collector.getArrayName(collector.mFilterData); sendSceneArray(inStream, inScene, collector.mFilterData, propName); const NamedArray<PxGeometryHolder>& geometriesToDestroy = collector.getPrevFrameGeometries(); propName = collector.getArrayName(geometriesToDestroy); for(PxU32 k = 0; k < geometriesToDestroy.size(); ++k) { const PxGeometryHolder& inObj = geometriesToDestroy[k]; inStream.removeObjectRef(&inScene, propName, &inObj); inStream.destroyInstance(&inObj); } const PxArray<PxGeometryHolder>& geometriesToCreate = collector.getCurrentFrameGeometries(); for(PxU32 k = 0; k < geometriesToCreate.size(); ++k) { const PxGeometry& geometry = geometriesToCreate[k].any(); switch(geometry.getType()) { #define SEND_PVD_GEOM_TYPE(enumType, TGeomType, TValueType) \ case enumType: \ { \ const TGeomType& inObj = static_cast<const TGeomType&>(geometry); \ inStream.createInstance(getPvdNamespacedNameForType<TGeomType>(), &inObj); \ registrarPhysicsObject<TGeomType>(inStream, inObj, pvd); \ TValueType values(&inObj); \ inStream.setPropertyMessage(&inObj, values); \ inStream.pushBackObjectRef(&inScene, propName, &inObj); \ } \ break; SEND_PVD_GEOM_TYPE(PxGeometryType::eBOX, PxBoxGeometry, PxBoxGeometryGeneratedValues) SEND_PVD_GEOM_TYPE(PxGeometryType::eSPHERE, PxSphereGeometry, PxSphereGeometryGeneratedValues) SEND_PVD_GEOM_TYPE(PxGeometryType::eCAPSULE, PxCapsuleGeometry, PxCapsuleGeometryGeneratedValues) SEND_PVD_GEOM_TYPE(PxGeometryType::eCONVEXMESH, PxConvexMeshGeometry, PxConvexMeshGeometryGeneratedValues) #undef SEND_PVD_GEOM_TYPE case PxGeometryType::ePLANE: case PxGeometryType::eTRIANGLEMESH: case PxGeometryType::eHEIGHTFIELD: case PxGeometryType::eTETRAHEDRONMESH: case PxGeometryType::ePARTICLESYSTEM: case PxGeometryType::eHAIRSYSTEM: case PxGeometryType::eCUSTOM: case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: PX_ALWAYS_ASSERT_MESSAGE("unsupported scene query geometry type"); break; } } collector.prepareNextFrameGeometries(); propName = collector.getArrayName(collector.mAccumulatedRaycastQueries); sendSceneArray(inStream, inScene, collector.mAccumulatedRaycastQueries, propName); propName = collector.getArrayName(collector.mAccumulatedOverlapQueries); sendSceneArray(inStream, inScene, collector.mAccumulatedOverlapQueries, propName); propName = collector.getArrayName(collector.mAccumulatedSweepQueries); sendSceneArray(inStream, inScene, collector.mAccumulatedSweepQueries, propName); } } } } #endif
81,227
C++
39.573427
180
0.77553
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSoftBody.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #include "NpCheck.h" #include "NpScene.h" #include "NpShape.h" #include "geometry/PxTetrahedronMesh.h" #include "geometry/PxTetrahedronMeshGeometry.h" #include "PxPhysXGpu.h" #include "PxvGlobals.h" #include "GuTetrahedronMesh.h" #include "NpRigidDynamic.h" #include "NpRigidStatic.h" #include "NpArticulationLink.h" #include "ScSoftBodySim.h" #include "NpFEMSoftBodyMaterial.h" #include "cudamanager/PxCudaContext.h" using namespace physx; namespace physx { NpSoftBody::NpSoftBody(PxCudaContextManager& cudaContextManager) : NpActorTemplate (PxConcreteType::eSOFT_BODY, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, NpType::eSOFTBODY), mShape (NULL), mCudaContextManager(&cudaContextManager) { } NpSoftBody::NpSoftBody(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager) : NpActorTemplate (baseFlags), mShape (NULL), mCudaContextManager(&cudaContextManager) { } PxBounds3 NpSoftBody::getWorldBounds(float inflation) const { NP_READ_CHECK(getNpScene()); if (!getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Querying bounds of a PxSoftBody which is not part of a PxScene is not supported."); return PxBounds3::empty(); } const Sc::SoftBodySim* sim = mCore.getSim(); PX_ASSERT(sim); PX_SIMD_GUARD; PxBounds3 bounds = sim->getBounds(); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } PxU32 NpSoftBody::getGpuSoftBodyIndex() { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene(), "PxSoftBody::getGpuSoftBodyIndex: Soft body must be in a scene.", 0xffffffff); return mCore.getGpuSoftBodyIndex(); } void NpSoftBody::setSoftBodyFlag(PxSoftBodyFlag::Enum flag, bool val) { PxSoftBodyFlags flags = mCore.getFlags(); if (val) flags.raise(flag); else flags.clear(flag); mCore.setFlags(flags); } void NpSoftBody::setSoftBodyFlags(PxSoftBodyFlags flags) { mCore.setFlags(flags); } PxSoftBodyFlags NpSoftBody::getSoftBodyFlag() const { return mCore.getFlags(); } void NpSoftBody::setParameter(PxFEMParameters paramters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxSoftBody::setInternalIterationCount() not allowed while simulation is running. Call will be ignored.") mCore.setParameter(paramters); UPDATE_PVD_PROPERTY } PxFEMParameters NpSoftBody::getParameter() const { NP_READ_CHECK(getNpScene()); return mCore.getParameter(); } PxVec4* NpSoftBody::getPositionInvMassBufferD() { PX_CHECK_AND_RETURN_NULL(mShape != NULL, "NpSoftBody::getPositionInvMassBufferD: Softbody does not have a shape, attach shape first."); Dy::SoftBodyCore& core = mCore.getCore(); return core.mPositionInvMass; } PxVec4* NpSoftBody::getRestPositionBufferD() { PX_CHECK_AND_RETURN_NULL(mShape != NULL, "NpSoftBody::getRestPositionBufferD: Softbody does not have a shape, attach shape first."); Dy::SoftBodyCore& core = mCore.getCore(); return core.mRestPosition; } PxVec4* NpSoftBody::getSimPositionInvMassBufferD() { PX_CHECK_AND_RETURN_NULL(mSimulationMesh != NULL, "NpSoftBody::getSimPositionInvMassBufferD: Softbody does not have a simulation mesh, attach simulation mesh first."); Dy::SoftBodyCore& core = mCore.getCore(); return core.mSimPositionInvMass; } PxVec4* NpSoftBody::getSimVelocityBufferD() { PX_CHECK_AND_RETURN_NULL(mSimulationMesh != NULL, "NpSoftBody::getSimVelocityBufferD: Softbody does not have a simulation mesh, attach simulation mesh first."); Dy::SoftBodyCore& core = mCore.getCore(); return core.mSimVelocity; } void NpSoftBody::markDirty(PxSoftBodyDataFlags flags) { NP_WRITE_CHECK(getNpScene()); Dy::SoftBodyCore& core = mCore.getCore(); core.mDirtyFlags |= flags; } void NpSoftBody::setKinematicTargetBufferD(const PxVec4* positions, PxSoftBodyFlags flags) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(!(positions == NULL && flags != PxSoftBodyFlags(0)), "NpSoftBody::setKinematicTargetBufferD: targets cannot be null if flags are set to be kinematic."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxSoftBody::setKinematicTargetBufferD() not allowed while simulation is running. Call will be ignored.") mCore.setKinematicTargets(positions, flags); } PxCudaContextManager* NpSoftBody::getCudaContextManager() const { return mCudaContextManager; } void NpSoftBody::setWakeCounter(PxReal wakeCounterValue) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxSoftBody::setWakeCounter() not allowed while simulation is running. Call will be ignored.") mCore.setWakeCounter(wakeCounterValue); //UPDATE_PVD_PROPERTIES_OBJECT() } PxReal NpSoftBody::getWakeCounter() const { NP_READ_CHECK(getNpScene()); return mCore.getWakeCounter(); } bool NpSoftBody::isSleeping() const { NP_READ_CHECK(getNpScene()); return mCore.isSleeping(); } void NpSoftBody::setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(positionIters > 0, "NpSoftBody::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(positionIters <= 255, "NpSoftBody::setSolverIterationCounts: positionIters must be no greater than 255!"); PX_CHECK_AND_RETURN(velocityIters <= 255, "NpSoftBody::setSolverIterationCounts: velocityIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxSoftBody::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") mCore.setSolverIterationCounts((velocityIters & 0xff) << 8 | (positionIters & 0xff)); } void NpSoftBody::getSolverIterationCounts(PxU32& positionIters, PxU32& velocityIters) const { NP_READ_CHECK(getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); velocityIters = PxU32(x >> 8); positionIters = PxU32(x & 0xff); } PxShape* NpSoftBody::getShape() { return mShape; } PxTetrahedronMesh* NpSoftBody::getCollisionMesh() { const PxTetrahedronMeshGeometry& tetMeshGeom = static_cast<const PxTetrahedronMeshGeometry&>(mShape->getGeometry()); return tetMeshGeom.tetrahedronMesh; } const PxTetrahedronMesh* NpSoftBody::getCollisionMesh() const { const PxTetrahedronMeshGeometry& tetMeshGeom = static_cast<const PxTetrahedronMeshGeometry&>(mShape->getGeometry()); return tetMeshGeom.tetrahedronMesh; } bool NpSoftBody::attachSimulationMesh(PxTetrahedronMesh& simulationMesh, PxSoftBodyAuxData& softBodyAuxData) { Dy::SoftBodyCore& core = mCore.getCore(); PX_CHECK_AND_RETURN_NULL(core.mSimPositionInvMass == NULL, "NpSoftBody::attachSimulationMesh: mSimPositionInvMass already exists, overwrite not allowed, call detachSimulationMesh first"); PX_CHECK_AND_RETURN_NULL(core.mSimVelocity == NULL, "NpSoftBody::attachSimulationMesh: mSimVelocity already exists, overwrite not allowed, call detachSimulationMesh first"); mSimulationMesh = static_cast<Gu::TetrahedronMesh*>(&simulationMesh); mSoftBodyAuxData = static_cast<Gu::SoftBodyAuxData*>(&softBodyAuxData); Gu::TetrahedronMesh* tetMesh = static_cast<Gu::TetrahedronMesh*>(&simulationMesh); const PxU32 numVertsGM = tetMesh->getNbVerticesFast(); core.mSimPositionInvMass = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVertsGM); core.mSimVelocity = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVertsGM); return true; } void NpSoftBody::updateMaterials() { Dy::SoftBodyCore& core = mCore.getCore(); core.clearMaterials(); for (PxU32 i = 0; i < mShape->getNbMaterials(); ++i) { PxFEMSoftBodyMaterial* material; mShape->getSoftBodyMaterials(&material, 1, i); core.setMaterial(static_cast<NpFEMSoftBodyMaterial*>(material)->mMaterial.mMaterialIndex); } } bool NpSoftBody::attachShape(PxShape& shape) { NpShape* npShape = static_cast<NpShape*>(&shape); PX_CHECK_AND_RETURN_NULL(npShape->getGeometryTypeFast() == PxGeometryType::eTETRAHEDRONMESH, "NpSoftBody::attachShape: Geometry type must be tetrahedron mesh geometry"); PX_CHECK_AND_RETURN_NULL(mShape == NULL, "NpSoftBody::attachShape: soft body can just have one shape"); PX_CHECK_AND_RETURN_NULL(shape.isExclusive(), "NpSoftBody::attachShape: shape must be exclusive"); PX_CHECK_AND_RETURN_NULL(npShape->getCore().getCore().mShapeCoreFlags & PxShapeCoreFlag::eSOFT_BODY_SHAPE, "NpSoftBody::attachShape: shape must be a soft body shape!"); Dy::SoftBodyCore& core = mCore.getCore(); PX_CHECK_AND_RETURN_NULL(core.mPositionInvMass == NULL, "NpSoftBody::attachShape: mPositionInvMass already exists, overwrite not allowed, call detachShape first"); mShape = npShape; PX_ASSERT(shape.getActor() == NULL); npShape->onActorAttach(*this); const PxGeometryHolder gh(mShape->getGeometry()); // PT: TODO: avoid that copy const PxTetrahedronMeshGeometry& tetGeometry = gh.tetMesh(); Gu::BVTetrahedronMesh* tetMesh = static_cast<Gu::BVTetrahedronMesh*>(tetGeometry.tetrahedronMesh); const PxU32 numVerts = tetMesh->getNbVerticesFast(); core.mPositionInvMass = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVerts); core.mRestPosition = PX_DEVICE_ALLOC_T(PxVec4, mCudaContextManager, numVerts); updateMaterials(); return true; } void NpSoftBody::detachShape() { PX_CHECK_MSG(getNpSceneFromActor(*this) == NULL, "Detaching a shape from a softbody is currenly only allowed as long as it is not part of a scene. Please remove the softbody from its scene first."); Dy::SoftBodyCore& core = mCore.getCore(); if (core.mRestPosition) { PX_DEVICE_FREE(mCudaContextManager, core.mRestPosition); core.mRestPosition = NULL; } if (core.mPositionInvMass) { PX_DEVICE_FREE(mCudaContextManager, core.mPositionInvMass); core.mPositionInvMass = NULL; } if (mShape) mShape->onActorDetach(); mShape = NULL; } void NpSoftBody::detachSimulationMesh() { Dy::SoftBodyCore& core = mCore.getCore(); if (core.mSimPositionInvMass) { PX_DEVICE_FREE(mCudaContextManager, core.mSimPositionInvMass); core.mSimPositionInvMass = NULL; } if (core.mSimVelocity) { PX_DEVICE_FREE(mCudaContextManager, core.mSimVelocity); core.mSimVelocity = NULL; } mSimulationMesh = NULL; mSoftBodyAuxData = NULL; } void NpSoftBody::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // AD why is this commented out? // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveSoftBody(*this); npScene->removeFromSoftBodyList(*this); } detachSimulationMesh(); detachShape(); PX_ASSERT(!isAPIWriteForbidden()); NpDestroySoftBody(this); } void NpSoftBody::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); mName = debugName; } const char* NpSoftBody::getName() const { NP_READ_CHECK(getNpScene()); return mName; } void NpSoftBody::addParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addParticleFilter: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((particlesystem == NULL || particlesystem->getScene() != NULL), "NpSoftBody::addParticleFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addParticleFilter: Illegal to call while simulation is running."); NpPBDParticleSystem* npParticleSystem = static_cast<NpPBDParticleSystem*>(particlesystem); Sc::ParticleSystemCore& core = npParticleSystem->getCore(); mCore.addParticleFilter(&core, particleId, buffer ? buffer->bufferUniqueId : 0, tetId); } void NpSoftBody::removeParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeParticleFilter: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((particlesystem == NULL || particlesystem->getScene() != NULL), "NpSoftBody::removeParticleFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeParticleFilter: Illegal to call while simulation is running."); NpPBDParticleSystem* npParticleSystem = static_cast<NpPBDParticleSystem*>(particlesystem); Sc::ParticleSystemCore& core = npParticleSystem->getCore(); mCore.removeParticleFilter(&core, particleId, buffer ? buffer->bufferUniqueId : 0, tetId); } PxU32 NpSoftBody::addParticleAttachment(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId, const PxVec4& barycentric) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpSoftBody::addParticleAttachment: Soft body must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL((particlesystem == NULL || particlesystem->getScene() != NULL), "NpSoftBody::addParticleAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpSoftBody::addParticleAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); NpPBDParticleSystem* npParticleSystem = static_cast<NpPBDParticleSystem*>(particlesystem); Sc::ParticleSystemCore& core = npParticleSystem->getCore(); return mCore.addParticleAttachment(&core, particleId, buffer ? buffer->bufferUniqueId : 0, tetId, barycentric); } void NpSoftBody::removeParticleAttachment(PxPBDParticleSystem* particlesystem, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addParticleAttachment: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((particlesystem == NULL || particlesystem->getScene() != NULL), "NpSoftBody::addParticleAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addParticleAttachment: Illegal to call while simulation is running."); NpPBDParticleSystem* npParticleSystem = static_cast<NpPBDParticleSystem*>(particlesystem); Sc::ParticleSystemCore& core = npParticleSystem->getCore(); mCore.removeParticleAttachment(&core, handle); } void NpSoftBody::addRigidFilter(PxRigidActor* actor, PxU32 vertId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addRigidFilter: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpSoftBody::addRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.addRigidFilter(core, vertId); } void NpSoftBody::removeRigidFilter(PxRigidActor* actor, PxU32 vertId) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeRigidFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpSoftBody::removeRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeRigidFilter(core, vertId); } PxU32 NpSoftBody::addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpSoftBody::addRigidAttachment: Soft body must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL((actor == NULL || actor->getScene() != NULL), "NpSoftBody::addRigidAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(constraint == NULL || constraint->isValid(), "NpSoftBody::addRigidAttachment: PxConeLimitedConstraint needs to be valid if specified.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpSoftBody::addRigidAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); Sc::BodyCore* core = getBodyCore(actor); PxVec3 aPose = actorSpacePose; if (actor && actor->getConcreteType()==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* stat = static_cast<NpRigidStatic*>(actor); aPose = stat->getGlobalPose().transform(aPose); } return mCore.addRigidAttachment(core, vertId, aPose, constraint); } void NpSoftBody::removeRigidAttachment(PxRigidActor* actor, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeRigidAttachment: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpSoftBody::removeRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeRigidAttachment: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeRigidAttachment(core, handle); } void NpSoftBody::addTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addTetRigidFilter: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpSoftBody::addTetRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addTetRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); return mCore.addTetRigidFilter(core, tetIdx); } void NpSoftBody::removeTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeTetRigidFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpSoftBody::removeTetRigidFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeTetRigidFilter: Illegal to call while simulation is running."); Sc::BodyCore* core = getBodyCore(actor); mCore.removeTetRigidFilter(core, tetIdx); } PxU32 NpSoftBody::addTetRigidAttachment(PxRigidActor* actor, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpSoftBody::addTetRigidAttachment: Soft body must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL((actor == NULL || actor->getScene() != NULL), "NpSoftBody::addTetRigidAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(constraint == NULL || constraint->isValid(), "NpSoftBody::addTetRigidAttachment: PxConeLimitedConstraint needs to be valid if specified.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpSoftBody::addTetRigidAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); Sc::BodyCore* core = getBodyCore(actor); PxVec3 aPose = actorSpacePose; if (actor && actor->getConcreteType()==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* stat = static_cast<NpRigidStatic*>(actor); aPose = stat->getGlobalPose().transform(aPose); } return mCore.addTetRigidAttachment(core, tetIdx, barycentric, aPose, constraint); } void NpSoftBody::addSoftBodyFilter(PxSoftBody* softbody0, PxU32 tetIdx0, PxU32 tetIdx1) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(softbody0 != NULL, "NpSoftBody::addSoftBodyFilter: soft body must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(softbody0->getScene() != NULL, "NpSoftBody::addSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addSoftBodyFilter: Illegal to call while simulation is running."); NpSoftBody* dyn = static_cast<NpSoftBody*>(softbody0); Sc::SoftBodyCore* core = &dyn->getCore(); mCore.addSoftBodyFilter(*core, tetIdx0, tetIdx1); } void NpSoftBody::removeSoftBodyFilter(PxSoftBody* softbody0, PxU32 tetIdx0, PxU32 tetIdx1) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(softbody0 != NULL, "NpSoftBody::removeSoftBodyFilter: soft body must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(softbody0->getScene() != NULL, "NpSoftBody::removeSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeSoftBodyFilter: Illegal to call while simulation is running."); NpSoftBody* dyn = static_cast<NpSoftBody*>(softbody0); Sc::SoftBodyCore* core = &dyn->getCore(); mCore.removeSoftBodyFilter(*core, tetIdx0, tetIdx1); } void NpSoftBody::addSoftBodyFilters(PxSoftBody* softbody0, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(softbody0 != NULL, "NpSoftBody::addSoftBodyFilter: soft body must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(softbody0->getScene() != NULL, "NpSoftBody::addSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addSoftBodyFilter: Illegal to call while simulation is running."); NpSoftBody* dyn = static_cast<NpSoftBody*>(softbody0); Sc::SoftBodyCore* core = &dyn->getCore(); mCore.addSoftBodyFilters(*core, tetIndices0, tetIndices1, tetIndicesSize); } void NpSoftBody::removeSoftBodyFilters(PxSoftBody* softbody0, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(softbody0 != NULL, "NpSoftBody::removeSoftBodyFilter: soft body must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(softbody0->getScene() != NULL, "NpSoftBody::removeSoftBodyFilter: soft body must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeSoftBodyFilter: Illegal to call while simulation is running."); NpSoftBody* dyn = static_cast<NpSoftBody*>(softbody0); Sc::SoftBodyCore* core = &dyn->getCore(); mCore.removeSoftBodyFilters(*core, tetIndices0, tetIndices1, tetIndicesSize); } PxU32 NpSoftBody::addSoftBodyAttachment(PxSoftBody* softbody0, PxU32 tetIdx0, const PxVec4& tetBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(softbody0 != NULL, "NpSoftBody::addSoftBodyAttachment: soft body must not be null", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpSoftBody::addSoftBodyAttachment: soft body must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(softbody0->getScene() != NULL, "NpSoftBody::addSoftBodyAttachment: soft body must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(constraint == NULL || constraint->isValid(), "NpSoftBody::addSoftBodyAttachment: PxConeLimitedConstraint needs to be valid if specified.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpSoftBody::addSoftBodyAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); NpSoftBody* dyn = static_cast<NpSoftBody*>(softbody0); Sc::SoftBodyCore* core = &dyn->getCore(); return mCore.addSoftBodyAttachment(*core, tetIdx0, tetBarycentric0, tetIdx1, tetBarycentric1, constraint, constraintOffset); } void NpSoftBody::removeSoftBodyAttachment(PxSoftBody* softbody0, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(softbody0 != NULL, "NpSoftBody::removeSoftBodyAttachment: soft body must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeSoftBodyAttachment: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(softbody0->getScene() != NULL, "NpSoftBody::removeSoftBodyAttachment: soft body must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeSoftBodyAttachment: Illegal to call while simulation is running."); NpSoftBody* dyn = static_cast<NpSoftBody*>(softbody0); Sc::SoftBodyCore* core = &dyn->getCore(); mCore.removeSoftBodyAttachment(*core, handle); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpSoftBody::addClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(cloth != NULL, "NpSoftBody::addClothFilter: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addClothFilter: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(cloth->getScene() != NULL, "NpSoftBody::addClothFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addClothFilter: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(cloth); Sc::FEMClothCore* core = &dyn->getCore(); return mCore.addClothFilter(*core, triIdx, tetIdx); } #else void NpSoftBody::addClothFilter(PxFEMCloth*, PxU32, PxU32) {} #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpSoftBody::removeClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(cloth != NULL, "NpSoftBody::removeClothFilter: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeClothFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(cloth->getScene() != NULL, "NpSoftBody::removeClothFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeClothFilter: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(cloth); Sc::FEMClothCore* core = &dyn->getCore(); mCore.removeClothFilter(*core, triIdx, tetIdx); } #else void NpSoftBody::removeClothFilter(PxFEMCloth*, PxU32, PxU32) {} #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpSoftBody::addVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(cloth != NULL, "NpSoftBody::addClothFilter: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::addClothFilter: Soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(cloth->getScene() != NULL, "NpSoftBody::addClothFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::addClothFilter: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(cloth); Sc::FEMClothCore* core = &dyn->getCore(); return mCore.addVertClothFilter(*core, vertIdx, tetIdx); } #else void NpSoftBody::addVertClothFilter(PxFEMCloth*, PxU32, PxU32) {} #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpSoftBody::removeVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(cloth != NULL, "NpSoftBody::removeClothFilter: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::removeClothFilter: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(cloth->getScene() != NULL, "NpSoftBody::removeClothFilter: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::removeClothFilter: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(cloth); Sc::FEMClothCore* core = &dyn->getCore(); mCore.removeVertClothFilter(*core, vertIdx, tetIdx); } #else void NpSoftBody::removeVertClothFilter(PxFEMCloth*, PxU32, PxU32) {} #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxU32 NpSoftBody::addClothAttachment(PxFEMCloth* cloth, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(cloth != NULL, "NpSoftBody::addClothAttachment: actor must not be null", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(getNpScene() != NULL, "NpSoftBody::addClothAttachment: Soft body must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(cloth->getScene() != NULL, "NpSoftBody::addClothAttachment: actor must be inserted into the scene.", 0xFFFFFFFF); PX_CHECK_AND_RETURN_VAL(constraint == NULL || constraint->isValid(), "NpSoftBody::addClothAttachment: PxConeLimitedConstraint needs to be valid if specified.", 0xFFFFFFFF); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "NpSoftBody::addClothAttachment: Illegal to call while simulation is running.", 0xFFFFFFFF); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(cloth); Sc::FEMClothCore* core = &dyn->getCore(); return mCore.addClothAttachment(*core, triIdx, triBarycentric, tetIdx, tetBarycentric, constraint, constraintOffset); } #else PxU32 NpSoftBody::addClothAttachment(PxFEMCloth*, PxU32, const PxVec4&, PxU32, const PxVec4&, PxConeLimitedConstraint*, PxReal) { return 0; } #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpSoftBody::removeClothAttachment(PxFEMCloth* cloth, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(cloth != NULL, "NpSoftBody::releaseClothAttachment: actor must not be null"); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpSoftBody::releaseClothAttachment: soft body must be inserted into the scene."); PX_CHECK_AND_RETURN(cloth->getScene() != NULL, "NpSoftBody::releaseClothAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpSoftBody::releaseClothAttachment: Illegal to call while simulation is running."); NpFEMCloth* dyn = static_cast<NpFEMCloth*>(cloth); Sc::FEMClothCore* core = &dyn->getCore(); mCore.removeClothAttachment(*core, handle); } #else void NpSoftBody::removeClothAttachment(PxFEMCloth*, PxU32) {} #endif } #endif //PX_SUPPORT_GPU_PHYSX
32,822
C++
42.53183
200
0.754768
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMClothMaterial.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_FEM_CLOTH_MATERIAL_H #define NP_FEM_CLOTH_MATERIAL_H #include "common/PxSerialFramework.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" #include "CmRefCountable.h" #include "PxsFEMClothMaterialCore.h" namespace physx { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION // Compared to other objects, materials are special since they belong to the SDK and not to scenes // (similar to meshes). That's why the NpFEMClothMaterial does have direct access to the core material instead // of having a buffered interface for it. Scenes will have copies of the SDK material table and there // the materials will be buffered. class NpFEMClothMaterial : public PxFEMClothMaterial, public PxUserAllocated { public: // PX_SERIALIZATION NpFEMClothMaterial(PxBaseFlags baseFlags) : PxFEMClothMaterial(baseFlags), mMaterial(PxEmpty) {} virtual void resolveReferences(PxDeserializationContext& context); static NpFEMClothMaterial* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&) {} //~PX_SERIALIZATION NpFEMClothMaterial(const PxsFEMClothMaterialCore& desc); virtual ~NpFEMClothMaterial(); // PxBase virtual void release() PX_OVERRIDE; //~PxBase // PxRefCounted virtual void acquireReference() PX_OVERRIDE; virtual PxU32 getReferenceCount() const PX_OVERRIDE; virtual void onRefCountZero() PX_OVERRIDE; //~PxRefCounted // PxFEMMaterial virtual void setYoungsModulus(PxReal young) PX_OVERRIDE; virtual PxReal getYoungsModulus() const PX_OVERRIDE; virtual void setPoissons(PxReal poisson) PX_OVERRIDE; virtual PxReal getPoissons() const PX_OVERRIDE; virtual void setDynamicFriction(PxReal threshold) PX_OVERRIDE; virtual PxReal getDynamicFriction() const PX_OVERRIDE; //~PxFEMMaterial // PxFEMClothMaterial virtual void setThickness(PxReal thickness) PX_OVERRIDE; virtual PxReal getThickness() const PX_OVERRIDE; //~PxFEMClothMaterial PX_FORCE_INLINE static void getMaterialIndices(PxFEMClothMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount); private: PX_INLINE void updateMaterial(); // PX_SERIALIZATION public: //~PX_SERIALIZATION PxsFEMClothMaterialCore mMaterial; }; PX_FORCE_INLINE void NpFEMClothMaterial::getMaterialIndices(PxFEMClothMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount) { for (PxU32 i = 0; i < materialCount; i++) materialIndices[i] = static_cast<NpFEMClothMaterial*>(materials[i])->mMaterial.mMaterialIndex; } #endif } #endif
4,630
C
42.280373
142
0.757235
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpBase.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_BASE_H #define NP_BASE_H #include "foundation/PxUserAllocated.h" #include "NpScene.h" #if PX_SUPPORT_PVD // PT: updatePvdProperties() is overloaded and the compiler needs to know 'this' type to do the right thing. // Thus we can't just move this as an inlined Base function. #define UPDATE_PVD_PROPERTY \ { \ NpScene* scene = getNpScene(); /* shared shapes also return zero here */ \ if(scene) \ scene->getScenePvdClientInternal().updatePvdProperties(this); \ } #else #define UPDATE_PVD_PROPERTY #endif /////////////////////////////////////////////////////////////////////////////// // PT: technically the following macros should all be "NP" macros (they're not exposed to the public API) // but I only renamed the local ones (used in NpBase.h) as "NP", while the other "PX" are used by clients // of these macros in other Np files. The PX_CHECK names are very misleading, since these checks seem to // stay in all builds, contrary to other macros like PX_CHECK_AND_RETURN. /////////////////////////////////////////////////////////////////////////////// #define NP_API_READ_WRITE_ERROR_MSG(text) PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, text) // some API read calls are not allowed while the simulation is running since the properties might get // written to during simulation. Some of those are allowed while collision is running though or in callbacks // like contact modification, contact reports etc. Furthermore, it is ok to read all of them between fetchCollide // and advance. #define NP_API_READ_FORBIDDEN(npScene) (npScene && npScene->isAPIReadForbidden()) #define NP_API_READ_FORBIDDEN_EXCEPT_COLLIDE(npScene) (npScene && npScene->isAPIReadForbidden() && (!npScene->isCollisionPhaseActive())) /////////////////////////////////////////////////////////////////////////////// #define PX_CHECK_SCENE_API_READ_FORBIDDEN(npScene, text) \ if(NP_API_READ_FORBIDDEN(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return; \ } #define PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(npScene, text, retValue) \ if(NP_API_READ_FORBIDDEN(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return retValue; \ } #define PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE(npScene, text) \ if(NP_API_READ_FORBIDDEN_EXCEPT_COLLIDE(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return; \ } #define PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(npScene, text, retValue) \ if(NP_API_READ_FORBIDDEN_EXCEPT_COLLIDE(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return retValue; \ } /////////////////////////////////////////////////////////////////////////////// #define NP_API_WRITE_FORBIDDEN(npScene) (npScene && npScene->isAPIWriteForbidden()) // some API write calls are allowed between fetchCollide and advance #define NP_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene) (npScene && npScene->isAPIWriteForbidden() && (npScene->getSimulationStage() != Sc::SimulationStage::eFETCHCOLLIDE)) /////////////////////////////////////////////////////////////////////////////// #define PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, text) \ if(NP_API_WRITE_FORBIDDEN(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return; \ } #define PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, text, retValue) \ if(NP_API_WRITE_FORBIDDEN(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return retValue; \ } #define PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, text) \ if(NP_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene)) \ { \ NP_API_READ_WRITE_ERROR_MSG(text); \ return; \ } /////////////////////////////////////////////////////////////////////////////// #define NP_UNUSED_BASE_INDEX 0x07ffffff #define NP_BASE_INDEX_MASK 0x07ffffff #define NP_BASE_INDEX_SHIFT 27 namespace physx { struct NpType { enum Enum { eUNDEFINED, eSHAPE, eBODY, eBODY_FROM_ARTICULATION_LINK, eRIGID_STATIC, eCONSTRAINT, eARTICULATION, eARTICULATION_JOINT, eARTICULATION_SENSOR, eARTICULATION_SPATIAL_TENDON, eARTICULATION_ATTACHMENT, eARTICULATION_FIXED_TENDON, eARTICULATION_TENDON_JOINT, eAGGREGATE, eSOFTBODY, eFEMCLOTH, ePBD_PARTICLESYSTEM, eFLIP_PARTICLESYSTEM, eMPM_PARTICLESYSTEM, eHAIRSYSTEM, eTYPE_COUNT, eFORCE_DWORD = 0x7fffffff }; }; // PT: we're going to store that type on 5 bits, leaving 27 bits for the base index. PX_COMPILE_TIME_ASSERT(NpType::eTYPE_COUNT<32); class NpBase : public PxUserAllocated { PX_NOCOPY(NpBase) public: // PX_SERIALIZATION NpBase(const PxEMPTY) : mScene (NULL), mFreeSlot (0) { // PT: preserve type, reset base index setBaseIndex(NP_UNUSED_BASE_INDEX); } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpBase(NpType::Enum type) : mScene (NULL), mFreeSlot (0) { mBaseIndexAndType = (PxU32(type)<<NP_BASE_INDEX_SHIFT)|NP_UNUSED_BASE_INDEX; } PX_INLINE bool isAPIWriteForbidden() const { return NP_API_WRITE_FORBIDDEN(mScene); } PX_INLINE bool isAPIWriteForbiddenExceptSplitSim() const { return NP_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(mScene); } PX_FORCE_INLINE NpType::Enum getNpType() const { return NpType::Enum(mBaseIndexAndType>>NP_BASE_INDEX_SHIFT); } PX_FORCE_INLINE void setNpScene(NpScene* scene) { mScene = scene; } PX_FORCE_INLINE NpScene* getNpScene() const { return mScene; } PX_FORCE_INLINE PxU32 getBaseIndex() const { return mBaseIndexAndType & NP_BASE_INDEX_MASK; } PX_FORCE_INLINE void setBaseIndex(PxU32 index) { PX_ASSERT(!(index & ~NP_BASE_INDEX_MASK)); const PxU32 type = mBaseIndexAndType & ~NP_BASE_INDEX_MASK; mBaseIndexAndType = index|type; } protected: ~NpBase(){} private: NpScene* mScene; PxU32 mBaseIndexAndType; protected: PxU32 mFreeSlot; }; } #endif
8,183
C
37.78673
173
0.633264
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidStatic.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 "NpRigidStatic.h" #include "NpRigidActorTemplateInternal.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; NpRigidStatic::NpRigidStatic(const PxTransform& pose) : NpRigidStaticT (PxConcreteType::eRIGID_STATIC, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, NpType::eRIGID_STATIC), mCore (pose) { } NpRigidStatic::~NpRigidStatic() { } // PX_SERIALIZATION void NpRigidStatic::requiresObjects(PxProcessPxBaseCallback& c) { NpRigidStaticT::requiresObjects(c); } NpRigidStatic* NpRigidStatic::createObject(PxU8*& address, PxDeserializationContext& context) { NpRigidStatic* obj = PX_PLACEMENT_NEW(address, NpRigidStatic(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpRigidStatic); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpRigidStatic::release() { if(releaseRigidActorT<PxRigidStatic>(*this)) { PX_ASSERT(!isAPIWriteForbidden()); // the code above should return false in that case NpDestroyRigidActor(this); } } void NpRigidStatic::setGlobalPose(const PxTransform& pose, bool /*wake*/) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidStatic::setGlobalPose: pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidStatic::setGlobalPose() not allowed while simulation is running. Call will be ignored.") #if PX_CHECKED if(npScene) npScene->checkPositionSanity(*this, pose, "PxRigidStatic::setGlobalPose"); #endif const PxTransform newPose = pose.getNormalized(); //AM: added to fix 1461 where users read and write orientations for no reason. mCore.setActor2World(newPose); UPDATE_PVD_PROPERTY OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, *static_cast<PxRigidActor*>(this), newPose.p); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, *static_cast<PxRigidActor*>(this), newPose.q); OMNI_PVD_WRITE_SCOPE_END if(npScene) mShapeManager.markActorForSQUpdate(npScene->getSQAPI(), *this); // invalidate the pruning structure if the actor bounds changed if(mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidStatic::setGlobalPose: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } updateShaderComs(); } PxTransform NpRigidStatic::getGlobalPose() const { NP_READ_CHECK(getNpScene()); return mCore.getActor2World(); } PxU32 physx::NpRigidStaticGetShapes(NpRigidStatic& rigid, NpShape* const *&shapes) { NpShapeManager& sm = rigid.getShapeManager(); shapes = sm.getShapes(); return sm.getNbShapes(); } void NpRigidStatic::switchToNoSim() { NpActor::scSwitchToNoSim(); } void NpRigidStatic::switchFromNoSim() { NpActor::scSwitchFromNoSim(); } #if PX_CHECKED bool NpRigidStatic::checkConstraintValidity() const { // Perhaps NpConnectorConstIterator would be worth it... NpConnectorIterator iter = (const_cast<NpRigidStatic*>(this))->getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); if(!c->NpConstraint::isValid()) return false; } return true; } #endif
5,070
C++
34.215278
171
0.765286
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidDynamic.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_RIGID_DYNAMIC_H #define NP_RIGID_DYNAMIC_H #include "common/PxMetaData.h" #include "PxRigidDynamic.h" #include "NpRigidBodyTemplate.h" namespace physx { typedef NpRigidBodyTemplate<PxRigidDynamic> NpRigidDynamicT; class NpRigidDynamic : public NpRigidDynamicT { public: // PX_SERIALIZATION NpRigidDynamic(PxBaseFlags baseFlags) : NpRigidDynamicT(baseFlags) {} void preExportDataReset(); virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpRigidDynamic* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION virtual ~NpRigidDynamic(); //--------------------------------------------------------------------------------- // PxActor implementation //--------------------------------------------------------------------------------- virtual void release() PX_OVERRIDE; //--------------------------------------------------------------------------------- // PxRigidDynamic implementation //--------------------------------------------------------------------------------- virtual PxActorType::Enum getType() const PX_OVERRIDE { return PxActorType::eRIGID_DYNAMIC; } // Pose virtual void setGlobalPose(const PxTransform& pose, bool autowake) PX_OVERRIDE; PX_FORCE_INLINE PxTransform getGlobalPoseFast() const { const Sc::BodyCore& body = getCore(); // PT:: tag: scalar transform*transform return body.getBody2World() * body.getBody2Actor().getInverse(); } virtual PxTransform getGlobalPose() const PX_OVERRIDE { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::getGlobalPose() not allowed while simulation is running (except during PxScene::collide()).", PxTransform(PxIdentity)); return getGlobalPoseFast(); } virtual void setKinematicTarget(const PxTransform& destination) PX_OVERRIDE; virtual bool getKinematicTarget(PxTransform& target) const PX_OVERRIDE; // Center of mass pose virtual void setCMassLocalPose(const PxTransform&) PX_OVERRIDE; // Velocity virtual void setLinearVelocity(const PxVec3&, bool autowake) PX_OVERRIDE; virtual void setAngularVelocity(const PxVec3&, bool autowake) PX_OVERRIDE; // Force/Torque modifiers virtual void addForce(const PxVec3&, PxForceMode::Enum mode, bool autowake) PX_OVERRIDE; virtual void clearForce(PxForceMode::Enum mode) PX_OVERRIDE; virtual void addTorque(const PxVec3&, PxForceMode::Enum mode, bool autowake) PX_OVERRIDE; virtual void clearTorque(PxForceMode::Enum mode) PX_OVERRIDE; virtual void setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE) PX_OVERRIDE; // Sleeping virtual bool isSleeping() const PX_OVERRIDE; virtual PxReal getSleepThreshold() const PX_OVERRIDE; virtual void setSleepThreshold(PxReal threshold) PX_OVERRIDE; virtual PxReal getStabilizationThreshold() const PX_OVERRIDE; virtual void setStabilizationThreshold(PxReal threshold) PX_OVERRIDE; virtual void setWakeCounter(PxReal wakeCounterValue) PX_OVERRIDE; virtual PxReal getWakeCounter() const PX_OVERRIDE; virtual void wakeUp() PX_OVERRIDE; virtual void putToSleep() PX_OVERRIDE; virtual void setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters) PX_OVERRIDE; virtual void getSolverIterationCounts(PxU32 & positionIters, PxU32 & velocityIters) const PX_OVERRIDE; virtual void setContactReportThreshold(PxReal threshold) PX_OVERRIDE; virtual PxReal getContactReportThreshold() const PX_OVERRIDE; virtual PxRigidDynamicLockFlags getRigidDynamicLockFlags() const PX_OVERRIDE; virtual void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) PX_OVERRIDE; virtual void setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) PX_OVERRIDE; //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpRigidDynamic(const PxTransform& bodyPose); virtual void switchToNoSim() PX_OVERRIDE; virtual void switchFromNoSim() PX_OVERRIDE; PX_FORCE_INLINE void wakeUpInternal(); void wakeUpInternalNoKinematicTest(bool forceWakeUp, bool autowake); static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpRigidDynamic, mCore); } static PX_FORCE_INLINE size_t getNpShapeManagerOffset() { return PX_OFFSET_OF_RT(NpRigidDynamic, mShapeManager); } #if PX_CHECKED PX_FORCE_INLINE bool checkConstraintValidity() const { return true; } #endif private: PX_FORCE_INLINE void setKinematicTargetInternal(const PxTransform& destination); #if PX_ENABLE_DEBUG_VISUALIZATION public: void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif }; PX_FORCE_INLINE void NpRigidDynamic::wakeUpInternal() { PX_ASSERT(getNpScene()); const Sc::BodyCore& body = getCore(); const PxRigidBodyFlags currentFlags = body.getFlags(); if (!(currentFlags & PxRigidBodyFlag::eKINEMATIC)) // kinematics are only awake when a target is set, else they are asleep wakeUpInternalNoKinematicTest(false, true); } } #endif
7,078
C
41.90303
216
0.709381
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpParticleSystem.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_PARTICLE_SYSTEM_H #define NP_PARTICLE_SYSTEM_H #include "foundation/PxBounds3.h" #include "foundation/PxErrors.h" #include "foundation/PxSimpleTypes.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxVec3.h" #include "common/PxBase.h" #include "common/PxRenderOutput.h" #include "PxActor.h" #include "PxFiltering.h" #include "PxParticleBuffer.h" //#include "PxParticlePhase.h" #include "PxParticleSolverType.h" #include "PxParticleSystem.h" #include "PxPBDParticleSystem.h" #include "PxPBDMaterial.h" #include "PxSceneDesc.h" #include "PxSparseGridParams.h" #include "DyParticleSystem.h" #include "NpActor.h" #include "NpActorTemplate.h" #include "NpBase.h" #include "NpMaterialManager.h" #include "NpPhysics.h" #include "ScParticleSystemSim.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxFLIPParticleSystem.h" #include "PxFLIPMaterial.h" #include "PxMPMParticleSystem.h" #include "PxMPMMaterial.h" #endif namespace physx { class NpScene; class PxCudaContextManager; class PxParticleMaterial; class PxRigidActor; class PxSerializationContext; namespace Sc { class ParticleSystemSim; } template<class APIClass> class NpParticleSystem : public NpActorTemplate<APIClass> { public: NpParticleSystem(PxCudaContextManager& contextManager, PxType concreteType, NpType::Enum npType, PxActorType::Enum actorType) : NpActorTemplate<APIClass>(concreteType, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, npType), mCore(actorType), mCudaContextManager(&contextManager), mNextPhaseGroupID(0) { } NpParticleSystem(PxBaseFlags baseFlags) : NpActorTemplate<APIClass>(baseFlags) {} virtual ~NpParticleSystem() { //TODO!!!!! Do this correctly //sParticleSystemIdPool.tryRemoveID(mID); } virtual void exportData(PxSerializationContext& /*context*/) const {} //external API virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const { NP_READ_CHECK(NpBase::getNpScene()); if (!NpBase::getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Querying bounds of a PxParticleSystem which is not part of a PxScene is not supported."); return PxBounds3::empty(); } const Sc::ParticleSystemSim* sim = mCore.getSim(); PX_ASSERT(sim); PX_SIMD_GUARD; PxBounds3 bounds = sim->getBounds(); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) { NpScene* npScene = NpBase::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(minPositionIters > 0, "NpParticleSystem::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(minPositionIters <= 255, "NpParticleSystem::setSolverIterationCounts: positionIters must be no greater than 255!"); PX_CHECK_AND_RETURN(minVelocityIters <= 255, "NpParticleSystem::setSolverIterationCounts: velocityIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxParticleSystem::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") mCore.setSolverIterationCounts((minVelocityIters & 0xff) << 8 | (minPositionIters & 0xff)); //UPDATE_PVD_PROPERTY } virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const { NP_READ_CHECK(NpBase::getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); minVelocityIters = PxU32(x >> 8); minPositionIters = PxU32(x & 0xff); } virtual PxCudaContextManager* getCudaContextManager() const { return mCudaContextManager; } virtual void setRestOffset(PxReal restOffset) { scSetRestOffset(restOffset); } virtual PxReal getRestOffset() const { return mCore.getRestOffset(); } virtual void setContactOffset(PxReal contactOffset) { scSetContactOffset(contactOffset); } virtual PxReal getContactOffset() const { return mCore.getContactOffset(); } virtual void setParticleContactOffset(PxReal particleContactOffset) { scSetParticleContactOffset(particleContactOffset); } virtual PxReal getParticleContactOffset() const { return mCore.getParticleContactOffset(); } virtual void setSolidRestOffset(PxReal solidRestOffset) { scSetSolidRestOffset(solidRestOffset); } virtual PxReal getSolidRestOffset() const { return mCore.getSolidRestOffset(); } virtual void setMaxDepenetrationVelocity(PxReal v) {scSetMaxDepenetrationVelocity(v); } virtual PxReal getMaxDepenetrationVelocity(){ return mCore.getMaxDepenetrationVelocity(); } virtual void setMaxVelocity(PxReal v) { scSetMaxVelocity(v); } virtual PxReal getMaxVelocity() { return mCore.getMaxVelocity(); } virtual void setParticleSystemCallback(PxParticleSystemCallback* callback) { mCore.setParticleSystemCallback(callback); } virtual PxParticleSystemCallback* getParticleSystemCallback() const { return mCore.getParticleSystemCallback(); } // TOFIX virtual void enableCCD(bool enable) { scSnableCCD(enable); } virtual PxU32 createPhase(PxParticleMaterial* material, PxParticlePhaseFlags flags) = 0; virtual PxFilterData getSimulationFilterData() const { return mCore.getShapeCore().getSimulationFilterData(); } virtual void setSimulationFilterData(const PxFilterData& data) { mCore.getShapeCore().setSimulationFilterData(data); } virtual void setParticleFlag(PxParticleFlag::Enum flag, bool val) { PxParticleFlags flags = mCore.getFlags(); if (val) flags.raise(flag); else flags.clear(flag); mCore.setFlags(flags); scSetDirtyFlag(); } virtual void setParticleFlags(PxParticleFlags flags) { mCore.setFlags(flags); scSetDirtyFlag(); } virtual PxParticleFlags getParticleFlags() const { return mCore.getFlags(); } void setSolverType(const PxParticleSolverType::Enum solverType) { scSetSolverType(solverType); } virtual PxParticleSolverType::Enum getSolverType() const { return mCore.getSolverType(); } virtual PxU32 getNbParticleMaterials() const { const Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); const Dy::ParticleSystemCore& core = shapeCore.getLLCore(); return core.mUniqueMaterialHandles.size(); } virtual PxU32 getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0; virtual void addParticleBuffer(PxParticleBuffer* userBuffer) = 0; virtual void removeParticleBuffer(PxParticleBuffer* userBuffer) = 0; virtual PxU32 getGpuParticleSystemIndex() { NP_READ_CHECK(NpBase::getNpScene()); PX_CHECK_AND_RETURN_VAL(NpBase::getNpScene(), "NpParticleSystem::getGpuParticleSystemIndex: particle system must be in a scene.", 0xffffffff); if (NpBase::getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) return mCore.getSim()->getLowLevelParticleSystem()->getGpuRemapId(); return 0xffffffff; } PX_FORCE_INLINE const Sc::ParticleSystemCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::ParticleSystemCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpParticleSystem, mCore); } PX_INLINE void scSetDirtyFlag() { NP_READ_CHECK(NpBase::getNpScene()); NpScene* scene = NpBase::getNpScene(); if (scene) { mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PARAMS; } } PX_INLINE void scSetSleepThreshold(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setSleepThreshold(v); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetRestOffset(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setRestOffset(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetContactOffset(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setContactOffset(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetParticleContactOffset(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setParticleContactOffset(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetSolidRestOffset(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setSolidRestOffset(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetFluidRestOffset(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setFluidRestOffset(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetGridSizeX(const PxU32 v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setGridSizeX(v); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetGridSizeY(const PxU32 v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setGridSizeY(v); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetGridSizeZ(const PxU32 v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setGridSizeZ(v); //UPDATE_PVD_PROPERTY } PX_INLINE void scSnableCCD(const bool enable) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.enableCCD(enable); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetWind(const PxVec3& v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setWind(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetMaxDepenetrationVelocity(const PxReal v) { PX_CHECK_AND_RETURN(v > 0.f, "PxParticleSystem::setMaxDepenetrationVelocity: Max Depenetration Velocity must be > 0!"); PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setMaxDepenetrationVelocity(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetMaxVelocity(const PxReal v) { PX_CHECK_AND_RETURN(v > 0.f, "PxParticleSystem::setMaxVelocity: Max Velocity must be > 0!"); PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setMaxVelocity(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } PX_INLINE void scSetSolverType(const PxParticleSolverType::Enum solverType) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setSolverType(solverType); //UPDATE_PVD_PROPERTY } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PX_INLINE void scSetSparseGridParams(const PxSparseGridParams& params) { PX_CHECK_AND_RETURN(params.subgridSizeX > 1 && params.subgridSizeX % 2 == 0, "PxParticleSystem::setSparseGridParams: Sparse grid subgridSizeX must be > 1 and even number!"); PX_CHECK_AND_RETURN(params.subgridSizeY > 1 && params.subgridSizeY % 2 == 0, "PxParticleSystem::setSparseGridParams: Sparse grid subgridSizeY must be > 1 and even number!"); PX_CHECK_AND_RETURN(params.subgridSizeZ > 1 && params.subgridSizeZ % 2 == 0, "PxParticleSystem::setSparseGridParams: Sparse grid subgridSizeZ must be > 1 and even number!"); PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setSparseGridParams(params); //UPDATE_PVD_PROPERTY } #endif #if PX_ENABLE_DEBUG_VISUALIZATION virtual void visualize(PxRenderOutput& out, NpScene& npScene) const = 0; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif // Debug name void setName(const char* debugName) { NP_WRITE_CHECK(NpBase::getNpScene()); NpActor::mName = debugName; } const char* getName() const { NP_READ_CHECK(NpBase::getNpScene()); return NpActor::mName; } virtual void setGridSizeX(PxU32 gridSizeX) { scSetGridSizeX(gridSizeX); } virtual void setGridSizeY(PxU32 gridSizeY) { scSetGridSizeY(gridSizeY); } virtual void setGridSizeZ(PxU32 gridSizeZ) { scSetGridSizeZ(gridSizeZ); } template<typename ParticleMaterialType> PxU32 getParticleMaterialsInternal(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const { const Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); const Dy::ParticleSystemCore& core = shapeCore.getLLCore(); NpMaterialManager<ParticleMaterialType>& matManager = NpMaterialAccessor<ParticleMaterialType>::getMaterialManager(NpPhysics::getInstance()); PxU32 size = core.mUniqueMaterialHandles.size(); const PxU32 remainder = PxU32(PxMax<PxI32>(PxI32(size - startIndex), 0)); const PxU32 writeCount = PxMin(remainder, bufferSize); for(PxU32 i = 0; i < writeCount; i++) { userBuffer[i] = matManager.getMaterial(core.mUniqueMaterialHandles[startIndex + i]); } return writeCount; } protected: Sc::ParticleSystemCore mCore; PxCudaContextManager* mCudaContextManager; PxU32 mNextPhaseGroupID; }; class NpParticleClothPreProcessor : public PxParticleClothPreProcessor, public PxUserAllocated { public: NpParticleClothPreProcessor(PxCudaContextManager* cudaContextManager) : mCudaContextManager(cudaContextManager), mNbPartitions(0){} virtual ~NpParticleClothPreProcessor() {} virtual void release(); virtual void partitionSprings(const PxParticleClothDesc& clothDesc, PxPartitionedParticleCloth& output) PX_OVERRIDE; private: PxU32 computeSpringPartition(const PxParticleSpring& springs, const PxU32 partitionStartIndex, PxU32* partitionProgresses); PxU32* partitions(const PxParticleSpring* springs, PxU32* orderedSpringIndices); PxU32 combinePartitions(const PxParticleSpring* springs, const PxU32* orderedSpringIndices, const PxU32* accumulatedSpringsPerPartition, PxU32* accumulatedSpringsPerCombinedPartitions, PxParticleSpring* orderedSprings, PxU32* accumulatedCopiesPerParticles, PxU32* remapOutput); void classifySprings(const PxParticleSpring* springs, PxU32* partitionProgresses, PxU32* tempSprings, physx::PxArray<PxU32>& springsPerPartition); void writeSprings(const PxParticleSpring* springs, PxU32* partitionProgresses, PxU32* tempSprings, PxU32* orderedSprings, PxU32* accumulatedSpringsPerPartition); PxCudaContextManager* mCudaContextManager; PxU32 mNumSprings; PxU32 mNbPartitions; PxU32 mNumParticles; PxU32 mMaxSpringsPerPartition; }; class NpPBDParticleSystem : public NpParticleSystem<PxPBDParticleSystem> { public: NpPBDParticleSystem(PxU32 maxNeighborhood, PxCudaContextManager& contextManager); virtual ~NpPBDParticleSystem(){} virtual PxU32 createPhase(PxParticleMaterial* material, PxParticlePhaseFlags flags) PX_OVERRIDE; virtual void release(); virtual void setWind(const PxVec3& wind) { scSetWind(wind); } virtual PxVec3 getWind() const { return mCore.getWind(); } virtual void setFluidBoundaryDensityScale(PxReal fluidBoundaryDensityScale) { scSetFluidBoundaryDensityScale(fluidBoundaryDensityScale); } virtual PxReal getFluidBoundaryDensityScale() const { return mCore.getFluidBoundaryDensityScale(); } virtual void setFluidRestOffset(PxReal fluidRestOffset) { scSetFluidRestOffset(fluidRestOffset); } virtual PxReal getFluidRestOffset() const { return mCore.getFluidRestOffset(); } #if PX_ENABLE_DEBUG_VISUALIZATION virtual void visualize(PxRenderOutput& out, NpScene& npScene) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif //external API virtual PxActorType::Enum getType() const { return PxActorType::ePBD_PARTICLESYSTEM; } virtual PxU32 getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE; virtual void addParticleBuffer(PxParticleBuffer* particleBuffer); virtual void removeParticleBuffer(PxParticleBuffer* particleBuffer); virtual void addRigidAttachment(PxRigidActor* actor); virtual void removeRigidAttachment(PxRigidActor* actor); private: PX_FORCE_INLINE void scSetFluidBoundaryDensityScale(const PxReal v) { PX_ASSERT(!NpBase::isAPIWriteForbidden()); mCore.setFluidBoundaryDensityScale(v); scSetDirtyFlag(); //UPDATE_PVD_PROPERTY } }; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION class NpFLIPParticleSystem : public NpParticleSystem<PxFLIPParticleSystem> { public: NpFLIPParticleSystem(PxCudaContextManager& contextManager); virtual ~NpFLIPParticleSystem() {} virtual PxU32 createPhase(PxParticleMaterial* material, PxParticlePhaseFlags flags) PX_OVERRIDE; virtual void release(); virtual void setSparseGridParams(const PxSparseGridParams& params) { scSetSparseGridParams(params); } virtual PxSparseGridParams getSparseGridParams() const { return mCore.getSparseGridParams(); } virtual void* getSparseGridDataPointer(PxSparseGridDataFlag::Enum flags); virtual void getSparseGridCoord(PxI32& x, PxI32& y, PxI32& z, PxU32 id); virtual void setFLIPParams(const PxFLIPParams& params) { scSetFLIPParams(params); } virtual PxFLIPParams getFLIPParams() const { return mCore.getFLIPParams(); } #if PX_ENABLE_DEBUG_VISUALIZATION virtual void visualize(PxRenderOutput& out, NpScene& npScene) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif virtual PxU32 getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE; virtual void addParticleBuffer(PxParticleBuffer* particleBuffer); virtual void removeParticleBuffer(PxParticleBuffer* particleBuffer); virtual void addRigidAttachment(PxRigidActor* /*actor*/) {} virtual void removeRigidAttachment(PxRigidActor* /*actor*/) {} //external API virtual PxActorType::Enum getType() const { return PxActorType::eFLIP_PARTICLESYSTEM; } private: PX_FORCE_INLINE void scSetFLIPParams(const PxFLIPParams& params) { PX_CHECK_AND_RETURN(params.blendingFactor >= 0.f && params.blendingFactor <= 1.f, "PxParticleSystem::setFLIPParams: FLIP blending factor must be >= 0 and <= 1!"); PX_ASSERT(!isAPIWriteForbidden()); mCore.setFLIPParams(params); //UPDATE_PVD_PROPERTY } }; class NpMPMParticleSystem :public NpParticleSystem<PxMPMParticleSystem> { public: NpMPMParticleSystem(PxCudaContextManager& contextManager); virtual ~NpMPMParticleSystem() {} virtual PxU32 createPhase(PxParticleMaterial* material, PxParticlePhaseFlags flags) PX_OVERRIDE; virtual void release(); virtual void setSparseGridParams(const PxSparseGridParams& params) { scSetSparseGridParams(params); } virtual PxSparseGridParams getSparseGridParams() const { return mCore.getSparseGridParams(); } virtual void* getSparseGridDataPointer(PxSparseGridDataFlag::Enum flags); virtual void getSparseGridCoord(PxI32& x, PxI32& y, PxI32& z, PxU32 id); virtual void setMPMParams(const PxMPMParams& params) { scSetMPMParams(params); } virtual PxMPMParams getMPMParams() const { return mCore.getMPMParams(); } virtual void* getMPMDataPointer(PxMPMParticleDataFlag::Enum flags); #if PX_ENABLE_DEBUG_VISUALIZATION virtual void visualize(PxRenderOutput& out, NpScene& npScene) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif virtual PxU32 getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE; virtual void addParticleBuffer(PxParticleBuffer* particleBuffer); virtual void removeParticleBuffer(PxParticleBuffer* particleBuffer); virtual void addRigidAttachment(PxRigidActor* actor); virtual void removeRigidAttachment(PxRigidActor* actor); //external API virtual PxActorType::Enum getType() const { return PxActorType::eMPM_PARTICLESYSTEM; } private: PX_INLINE void scSetMPMParams(const PxMPMParams& params) { mCore.setMPMParams(params); //UPDATE_PVD_PROPERTY } }; #endif } #endif
21,537
C
34.19281
176
0.750569
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpShape.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 "NpShape.h" #include "NpCheck.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "GuConvexMesh.h" #include "GuTriangleMesh.h" #include "GuTetrahedronMesh.h" #include "GuBounds.h" #include "NpFEMCloth.h" #include "NpSoftBody.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; using namespace Sq; using namespace Cm; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// // PT: we're using mFreeSlot as a replacement for previous mExclusiveAndActorCount static PX_FORCE_INLINE void increaseActorCount(PxU32* count) { volatile PxI32* val = reinterpret_cast<volatile PxI32*>(count); PxAtomicIncrement(val); } static PX_FORCE_INLINE void decreaseActorCount(PxU32* count) { volatile PxI32* val = reinterpret_cast<volatile PxI32*>(count); PxAtomicDecrement(val); } NpShape::NpShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, const PxU16* materialIndices, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum flag) : PxShape (PxConcreteType::eSHAPE, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), NpBase (NpType::eSHAPE), mExclusiveShapeActor (NULL), mCore (geometry, shapeFlags, materialIndices, materialCount, isExclusive, flag) { //actor count mFreeSlot = 0; PX_ASSERT(mCore.getPxShape() == static_cast<PxShape*>(this)); PX_ASSERT(!PxShape::userData); mCore.mName = NULL; incMeshRefCount(); } NpShape::~NpShape() { decMeshRefCount(); const PxU32 nbMaterials = scGetNbMaterials(); PxShapeCoreFlags flags = mCore.getCore().mShapeCoreFlags; if (flags & PxShapeCoreFlag::eCLOTH_SHAPE) { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX for (PxU32 i = 0; i < nbMaterials; i++) RefCountable_decRefCount(*scGetMaterial<NpFEMClothMaterial>(i)); #endif } else if(flags & PxShapeCoreFlag::eSOFT_BODY_SHAPE) { #if PX_SUPPORT_GPU_PHYSX for (PxU32 i = 0; i < nbMaterials; i++) RefCountable_decRefCount(*scGetMaterial<NpFEMSoftBodyMaterial>(i)); #endif } else { for (PxU32 i = 0; i < nbMaterials; i++) RefCountable_decRefCount(*scGetMaterial<NpMaterial>(i)); } } void NpShape::onRefCountZero() { NpFactory::getInstance().onShapeRelease(this); // see NpShape.h for ref counting semantics for shapes NpDestroyShape(this); } // PX_SERIALIZATION NpShape::NpShape(PxBaseFlags baseFlags) : PxShape(baseFlags), NpBase(PxEmpty), mCore(PxEmpty), mQueryFilterData(PxEmpty) { } void NpShape::preExportDataReset() { RefCountable_preExportDataReset(*this); mExclusiveShapeActor = NULL; mFreeSlot = 0; } void NpShape::exportExtraData(PxSerializationContext& context) { mCore.exportExtraData(context); context.writeName(mCore.mName); } void NpShape::importExtraData(PxDeserializationContext& context) { mCore.importExtraData(context); context.readName(mCore.mName); } void NpShape::requiresObjects(PxProcessPxBaseCallback& c) { //meshes PxBase* mesh = NULL; const PxGeometry& geometry = mCore.getGeometry(); switch(PxU32(mCore.getGeometryType())) { case PxGeometryType::eCONVEXMESH: mesh = static_cast<const PxConvexMeshGeometry&>(geometry).convexMesh; break; case PxGeometryType::eHEIGHTFIELD: mesh = static_cast<const PxHeightFieldGeometry&>(geometry).heightField; break; case PxGeometryType::eTRIANGLEMESH: mesh = static_cast<const PxTriangleMeshGeometry&>(geometry).triangleMesh; break; case PxGeometryType::eTETRAHEDRONMESH: mesh = static_cast<const PxTetrahedronMeshGeometry&>(geometry).tetrahedronMesh; break; } if(mesh) c.process(*mesh); //material const PxU32 nbMaterials = scGetNbMaterials(); for (PxU32 i=0; i < nbMaterials; i++) { NpMaterial* mat = scGetMaterial<NpMaterial>(i); c.process(*mat); } } void NpShape::resolveReferences(PxDeserializationContext& context) { // getMaterials() only works after material indices have been patched. // in order to get to the new material indices, we need access to the new materials. // this only leaves us with the option of acquiring the material through the context given an old material index (we do have the mapping) { PxU32 nbIndices = mCore.getNbMaterialIndices(); const PxU16* indices = mCore.getMaterialIndices(); for (PxU32 i=0; i < nbIndices; i++) { PxBase* base = context.resolveReference(PX_SERIAL_REF_KIND_MATERIAL_IDX, size_t(indices[i])); PX_ASSERT(base && base->is<PxMaterial>()); NpMaterial& material = *static_cast<NpMaterial*>(base); mCore.resolveMaterialReference(i, material.mMaterial.mMaterialIndex); } } //we don't resolve mExclusiveShapeActor because it's set to NULL on export. //it's recovered when the actors resolveReferences attaches to the shape mCore.resolveReferences(context); incMeshRefCount(); // Increment materials' refcounts in a second pass. Works better in case of failure above. const PxU32 nbMaterials = scGetNbMaterials(); for (PxU32 i=0; i < nbMaterials; i++) RefCountable_incRefCount(*scGetMaterial<NpMaterial>(i)); } NpShape* NpShape::createObject(PxU8*& address, PxDeserializationContext& context) { NpShape* obj = PX_PLACEMENT_NEW(address, NpShape(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpShape); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION PxU32 NpShape::getReferenceCount() const { return RefCountable_getRefCount(*this); } void NpShape::acquireReference() { RefCountable_incRefCount(*this); } void NpShape::release() { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(RefCountable_getRefCount(*this) > 1 || getActorCount() == 0, "PxShape::release: last reference to a shape released while still attached to an actor!"); releaseInternal(); } void NpShape::releaseInternal() { RefCountable_decRefCount(*this); } Sc::RigidCore& NpShape::getScRigidObjectExclusive() const { const PxType actorType = mExclusiveShapeActor->getConcreteType(); if (actorType == PxConcreteType::eRIGID_DYNAMIC) return static_cast<NpRigidDynamic&>(*mExclusiveShapeActor).getCore(); else if (actorType == PxConcreteType::eARTICULATION_LINK) return static_cast<NpArticulationLink&>(*mExclusiveShapeActor).getCore(); else return static_cast<NpRigidStatic&>(*mExclusiveShapeActor).getCore(); } void NpShape::updateSQ(const char* errorMessage) { PxRigidActor* actor = getActor(); if(actor && (mCore.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE)) { NpScene* scene = NpActor::getNpSceneFromActor(*actor); NpShapeManager* shapeManager = NpActor::getShapeManager_(*actor); if(scene) shapeManager->markShapeForSQUpdate(scene->getSQAPI(), *this, static_cast<const PxRigidActor&>(*actor)); // invalidate the pruning structure if the actor bounds changed if(shapeManager->getPruningStructure()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, errorMessage); shapeManager->getPruningStructure()->invalidate(mExclusiveShapeActor); } } } #if PX_CHECKED bool checkShape(const PxGeometry& g, const char* errorMsg); #endif void NpShape::setGeometry(const PxGeometry& g) { NpScene* ownerScene = getNpScene(); NP_WRITE_CHECK(ownerScene); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setGeometry: shared shapes attached to actors are not writable."); #if PX_CHECKED if(!checkShape(g, "PxShape::setGeometry(): Invalid geometry!")) return; #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN(ownerScene, "PxShape::setGeometry() not allowed while simulation is running. Call will be ignored.") // PT: fixes US2117 if(g.getType() != getGeometryTypeFast()) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxShape::setGeometry(): Invalid geometry type. Changing the type of the shape is not supported."); return; } PX_SIMD_GUARD; //Do not decrement ref count here, but instead cache the refcountable mesh pointer if we had one. //We instead decrement the ref counter after incrementing the ref counter on the new geometry. //This resolves a case where the user changed a property of a mesh geometry and set the same mesh geometry. If the user had //called release() on the mesh, the ref count could hit 0 and be destroyed and then crash when we call incMeshRefCount(). PxRefCounted* mesh = getMeshRefCountable(); { Sc::RigidCore* rigidCore = getScRigidObjectSLOW(); if(rigidCore) rigidCore->unregisterShapeFromNphase(mCore); mCore.setGeometry(g); if (rigidCore) { rigidCore->registerShapeInNphase(mCore); rigidCore->onShapeChange(mCore, Sc::ShapeChangeNotifyFlag::eGEOMETRY); } #if PX_SUPPORT_PVD NpScene* npScene = getNpScene(); if(npScene) npScene->getScenePvdClientInternal().releaseAndRecreateGeometry(this); #endif } incMeshRefCount(); if(mesh) RefCountable_decRefCount(*mesh); updateSQ("PxShape::setGeometry: Shape is a part of pruning structure, pruning structure is now invalid!"); } const PxGeometry& NpShape::getGeometry() const { NP_READ_CHECK(getNpScene()); return mCore.getGeometry(); } PxRigidActor* NpShape::getActor() const { NP_READ_CHECK(getNpScene()); return mExclusiveShapeActor ? mExclusiveShapeActor->is<PxRigidActor>() : NULL; } void NpShape::setLocalPose(const PxTransform& newShape2Actor) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(newShape2Actor.isSane(), "PxShape::setLocalPose: pose is not valid."); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setLocalPose: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setLocalPose() not allowed while simulation is running. Call will be ignored."); PxTransform normalizedTransform = newShape2Actor.getNormalized(); mCore.setShape2Actor(normalizedTransform); notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlag::eSHAPE2BODY); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, translation, static_cast<PxShape &>(*this), normalizedTransform.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, rotation, static_cast<PxShape &>(*this), normalizedTransform.q) OMNI_PVD_WRITE_SCOPE_END updateSQ("PxShape::setLocalPose: Shape is a part of pruning structure, pruning structure is now invalid!"); } PxTransform NpShape::getLocalPose() const { NP_READ_CHECK(getNpScene()); return mCore.getShape2Actor(); } /////////////////////////////////////////////////////////////////////////////// void NpShape::setSimulationFilterData(const PxFilterData& data) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setSimulationFilterData: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setSimulationFilterData() not allowed while simulation is running. Call will be ignored.") mCore.setSimulationFilterData(data); notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlag::eFILTERDATA); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, simulationFilterData, static_cast<PxShape&>(*this), data); } PxFilterData NpShape::getSimulationFilterData() const { NP_READ_CHECK(getNpScene()); return mCore.getSimulationFilterData(); } void NpShape::setQueryFilterData(const PxFilterData& data) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setQueryFilterData: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setQueryFilterData() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, queryFilterData, static_cast<PxShape&>(*this), data); mQueryFilterData = data; UPDATE_PVD_PROPERTY } PxFilterData NpShape::getQueryFilterData() const { NP_READ_CHECK(getNpScene()); return getQueryFilterDataFast(); } /////////////////////////////////////////////////////////////////////////////// template<typename PxMaterialType, typename NpMaterialType> void NpShape::setMaterialsInternal(PxMaterialType* const * materials, PxU16 materialCount) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setMaterials: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setMaterials() not allowed while simulation is running. Call will be ignored.") #if PX_CHECKED if (!NpShape::checkMaterialSetup(mCore.getGeometry(), "PxShape::setMaterials()", materials, materialCount)) return; #endif const PxU32 oldMaterialCount = scGetNbMaterials(); PX_ALLOCA(oldMaterials, PxMaterialType*, oldMaterialCount); PxU32 tmp = scGetMaterials<PxMaterialType, NpMaterialType>(oldMaterials, oldMaterialCount); PX_ASSERT(tmp == oldMaterialCount); PX_UNUSED(tmp); const bool ret = setMaterialsHelper<PxMaterialType, NpMaterialType>(materials, materialCount); #if PX_SUPPORT_PVD if (npScene) npScene->getScenePvdClientInternal().updateMaterials(this); #endif #if PX_SUPPORT_OMNI_PVD streamShapeMaterials(static_cast<PxShape&>(*this), materials, materialCount); #endif if (ret) { for (PxU32 i = 0; i < materialCount; i++) RefCountable_incRefCount(*materials[i]); for (PxU32 i = 0; i < oldMaterialCount; i++) RefCountable_decRefCount(*oldMaterials[i]); } } void NpShape::setMaterials(PxMaterial*const* materials, PxU16 materialCount) { PX_CHECK_AND_RETURN(!(mCore.getCore().mShapeCoreFlags & PxShapeCoreFlag::eSOFT_BODY_SHAPE), "NpShape::setMaterials: cannot set rigid body materials to a soft body shape!"); PX_CHECK_AND_RETURN(!(mCore.getCore().mShapeCoreFlags & PxShapeCoreFlag::eCLOTH_SHAPE), "NpShape::setMaterials: cannot set rigid body materials to a cloth shape!"); setMaterialsInternal<PxMaterial, NpMaterial>(materials, materialCount); } void NpShape::setSoftBodyMaterials(PxFEMSoftBodyMaterial*const* materials, PxU16 materialCount) { #if PX_SUPPORT_GPU_PHYSX PX_CHECK_AND_RETURN((mCore.getCore().mShapeCoreFlags & PxShapeCoreFlag::eSOFT_BODY_SHAPE), "NpShape::setMaterials: can only apply soft body materials to a soft body shape!"); setMaterialsInternal<PxFEMSoftBodyMaterial, NpFEMSoftBodyMaterial>(materials, materialCount); if (this->mExclusiveShapeActor) { static_cast<NpSoftBody*>(mExclusiveShapeActor)->updateMaterials(); } #else PX_UNUSED(materials); PX_UNUSED(materialCount); #endif } void NpShape::setClothMaterials(PxFEMClothMaterial*const* materials, PxU16 materialCount) { #if PX_SUPPORT_GPU_PHYSX && PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PX_CHECK_AND_RETURN((mCore.getCore().mShapeCoreFlags & PxShapeCoreFlag::eCLOTH_SHAPE), "NpShape::setMaterials: can only apply cloth materials to a cloth shape!"); setMaterialsInternal<PxFEMClothMaterial, NpFEMClothMaterial>(materials, materialCount); #else PX_UNUSED(materials); PX_UNUSED(materialCount); #endif } PxU16 NpShape::getNbMaterials() const { NP_READ_CHECK(getNpScene()); return scGetNbMaterials(); } PxU32 NpShape::getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return scGetMaterials<PxMaterial, NpMaterial>(userBuffer, bufferSize, startIndex); } #if PX_SUPPORT_GPU_PHYSX PxU32 NpShape::getSoftBodyMaterials(PxFEMSoftBodyMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return scGetMaterials<PxFEMSoftBodyMaterial, NpFEMSoftBodyMaterial>(userBuffer, bufferSize, startIndex); } #else PxU32 NpShape::getSoftBodyMaterials(PxFEMSoftBodyMaterial**, PxU32, PxU32) const { return 0; } #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX PxU32 NpShape::getClothMaterials(PxFEMClothMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return scGetMaterials<PxFEMClothMaterial, NpFEMClothMaterial>(userBuffer, bufferSize, startIndex); } #else PxU32 NpShape::getClothMaterials(PxFEMClothMaterial**, PxU32, PxU32) const { return 0; } #endif PxBaseMaterial* NpShape::getMaterialFromInternalFaceIndex(PxU32 faceIndex) const { NP_READ_CHECK(getNpScene()); const PxGeometry& geom = mCore.getGeometry(); const PxGeometryType::Enum geomType = geom.getType(); bool isHf = (geomType == PxGeometryType::eHEIGHTFIELD); bool isMesh = (geomType == PxGeometryType::eTRIANGLEMESH); // if SDF tri-mesh, where no multi-material setup is allowed, return zero-index material if (isMesh) { const PxTriangleMeshGeometry& triGeo = static_cast<const PxTriangleMeshGeometry&>(geom); if (triGeo.triangleMesh->getSDF()) { return getMaterial<PxMaterial, NpMaterial>(0); } } if( faceIndex == 0xFFFFffff && (isHf || isMesh) ) { outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxShape::getMaterialFromInternalFaceIndex received 0xFFFFffff as input - returning NULL."); return NULL; } PxMaterialTableIndex hitMatTableId = 0; if(isHf) { const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom); hitMatTableId = hfGeom.heightField->getTriangleMaterialIndex(faceIndex); } else if(isMesh) { const PxTriangleMeshGeometry& triGeo = static_cast<const PxTriangleMeshGeometry&>(geom); Gu::TriangleMesh* tm = static_cast<Gu::TriangleMesh*>(triGeo.triangleMesh); if(tm->hasPerTriangleMaterials()) hitMatTableId = triGeo.triangleMesh->getTriangleMaterialIndex(faceIndex); } // PT: TODO: what's going on here? return getMaterial<PxMaterial, NpMaterial>(hitMatTableId); } void NpShape::setContactOffset(PxReal contactOffset) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(contactOffset), "PxShape::setContactOffset: invalid float"); PX_CHECK_AND_RETURN((contactOffset >= 0.0f && contactOffset > mCore.getRestOffset()), "PxShape::setContactOffset: contactOffset should be positive, and greater than restOffset!"); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setContactOffset: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setContactOffset() not allowed while simulation is running. Call will be ignored.") mCore.setContactOffset(contactOffset); notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlag::eCONTACTOFFSET); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, contactOffset, static_cast<PxShape&>(*this), contactOffset) } PxReal NpShape::getContactOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getContactOffset(); } void NpShape::setRestOffset(PxReal restOffset) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(restOffset), "PxShape::setRestOffset: invalid float"); PX_CHECK_AND_RETURN((restOffset < mCore.getContactOffset()), "PxShape::setRestOffset: restOffset should be less than contactOffset!"); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setRestOffset: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setRestOffset() not allowed while simulation is running. Call will be ignored.") mCore.setRestOffset(restOffset); notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlag::eRESTOFFSET); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, restOffset, static_cast<PxShape&>(*this), restOffset) } PxReal NpShape::getRestOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getRestOffset(); } void NpShape::setDensityForFluid(PxReal densityForFluid) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(densityForFluid), "PxShape::setDensityForFluid: invalid float"); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setDensityForFluid: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setDensityForFluid() not allowed while simulation is running. Call will be ignored.") mCore.setDensityForFluid(densityForFluid); ///notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlag::eRESTOFFSET); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, densityForFluid, static_cast<PxShape &>(*this), densityForFluid); } PxReal NpShape::getDensityForFluid() const { NP_READ_CHECK(getNpScene()); return mCore.getDensityForFluid(); } void NpShape::setTorsionalPatchRadius(PxReal radius) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(radius), "PxShape::setTorsionalPatchRadius: invalid float"); PX_CHECK_AND_RETURN((radius >= 0.f), "PxShape::setTorsionalPatchRadius: must be >= 0.f"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setTorsionalPatchRadius() not allowed while simulation is running. Call will be ignored.") // const PxShapeFlags oldShapeFlags = mShape.getFlags(); mCore.setTorsionalPatchRadius(radius); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, torsionalPatchRadius, static_cast<PxShape &>(*this), radius); // shared shapes return NULL. But shared shapes aren't mutable when attached to an actor, so no notification needed. // Sc::RigidCore* rigidCore = NpShapeGetScRigidObjectFromScSLOW(); // if(rigidCore) // rigidCore->onShapeChange(mShape, Sc::ShapeChangeNotifyFlag::eFLAGS, oldShapeFlags); UPDATE_PVD_PROPERTY } PxReal NpShape::getTorsionalPatchRadius() const { NP_READ_CHECK(getNpScene()); return mCore.getTorsionalPatchRadius(); } void NpShape::setMinTorsionalPatchRadius(PxReal radius) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(radius), "PxShape::setMinTorsionalPatchRadius: invalid float"); PX_CHECK_AND_RETURN((radius >= 0.f), "PxShape::setMinTorsionalPatchRadius: must be >= 0.f"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setMinTorsionalPatchRadius() not allowed while simulation is running. Call will be ignored.") // const PxShapeFlags oldShapeFlags = mShape.getFlags(); mCore.setMinTorsionalPatchRadius(radius); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, minTorsionalPatchRadius, static_cast<PxShape &>(*this), radius); // Sc::RigidCore* rigidCore = NpShapeGetScRigidObjectFromSbSLOW(); // if(rigidCore) // rigidCore->onShapeChange(mShape, Sc::ShapeChangeNotifyFlag::eFLAGS, oldShapeFlags); UPDATE_PVD_PROPERTY } PxReal NpShape::getMinTorsionalPatchRadius() const { NP_READ_CHECK(getNpScene()); return mCore.getMinTorsionalPatchRadius(); } PxU32 NpShape::getInternalShapeIndex() const { NP_READ_CHECK(getNpScene()); if (getNpScene()) { PxsSimulationController* simulationController = getNpScene()->getSimulationController(); if (simulationController) return mCore.getInternalShapeIndex(*simulationController); } return PX_INVALID_NODE; } void NpShape::setFlagsInternal(PxShapeFlags inFlags) { const bool hasMeshTypeGeom = mCore.getGeometryType() == PxGeometryType::eTRIANGLEMESH || mCore.getGeometryType() == PxGeometryType::eHEIGHTFIELD; if(hasMeshTypeGeom && (inFlags & PxShapeFlag::eTRIGGER_SHAPE)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxShape::setFlag(s): triangle mesh and heightfield triggers are not supported!"); return; } if((inFlags & PxShapeFlag::eSIMULATION_SHAPE) && (inFlags & PxShapeFlag::eTRIGGER_SHAPE)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxShape::setFlag(s): shapes cannot simultaneously be trigger shapes and simulation shapes."); return; } const PxShapeFlags oldFlags = mCore.getFlags(); const bool oldIsSimShape = oldFlags & PxShapeFlag::eSIMULATION_SHAPE; const bool isSimShape = inFlags & PxShapeFlag::eSIMULATION_SHAPE; if(mExclusiveShapeActor) { const PxType type = mExclusiveShapeActor->getConcreteType(); // PT: US5732 - support kinematic meshes bool isKinematic = false; if(type==PxConcreteType::eRIGID_DYNAMIC) { PxRigidDynamic* rigidDynamic = static_cast<PxRigidDynamic*>(mExclusiveShapeActor); isKinematic = rigidDynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC; } if((type != PxConcreteType::eRIGID_STATIC) && !isKinematic && isSimShape && !oldIsSimShape && (hasMeshTypeGeom || mCore.getGeometryType() == PxGeometryType::ePLANE)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxShape::setFlag(s): triangle mesh, heightfield and plane shapes can only be simulation shapes if part of a PxRigidStatic!"); return; } } const bool oldHasSceneQuery = oldFlags & PxShapeFlag::eSCENE_QUERY_SHAPE; const bool hasSceneQuery = inFlags & PxShapeFlag::eSCENE_QUERY_SHAPE; { PX_ASSERT(!isAPIWriteForbidden()); const PxShapeFlags oldShapeFlags = mCore.getFlags(); mCore.setFlags(inFlags); notifyActorAndUpdatePVD(oldShapeFlags); } PxRigidActor* actor = getActor(); if(oldHasSceneQuery != hasSceneQuery && actor) { NpScene* npScene = getNpScene(); NpShapeManager* shapeManager = NpActor::getShapeManager_(*actor); if(npScene) { if(hasSceneQuery) { // PT: SQ_CODEPATH3 shapeManager->setupSceneQuery(npScene->getSQAPI(), NpActor::getFromPxActor(*actor), *actor, *this); } else { shapeManager->teardownSceneQuery(npScene->getSQAPI(), *actor, *this); } } // invalidate the pruning structure if the actor bounds changed if(shapeManager->getPruningStructure()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxShape::setFlag: Shape is a part of pruning structure, pruning structure is now invalid!"); shapeManager->getPruningStructure()->invalidate(mExclusiveShapeActor); } } } void NpShape::setFlag(PxShapeFlag::Enum flag, bool value) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setFlag: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setFlag() not allowed while simulation is running. Call will be ignored.") PX_SIMD_GUARD; PxShapeFlags shapeFlags = mCore.getFlags(); shapeFlags = value ? shapeFlags | flag : shapeFlags & ~flag; setFlagsInternal(shapeFlags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, shapeFlags, static_cast<PxShape&>(*this), shapeFlags); } void NpShape::setFlags(PxShapeFlags inFlags) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setFlags: shared shapes attached to actors are not writable."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxShape::setFlags() not allowed while simulation is running. Call will be ignored.") PX_SIMD_GUARD; setFlagsInternal(inFlags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxShape, shapeFlags, static_cast<PxShape&>(*this), inFlags); } PxShapeFlags NpShape::getFlags() const { NP_READ_CHECK(getNpScene()); return mCore.getFlags(); } bool NpShape::isExclusive() const { NP_READ_CHECK(getNpScene()); return isExclusiveFast(); } void NpShape::onActorAttach(PxActor& actor) { RefCountable_incRefCount(*this); if(isExclusiveFast()) mExclusiveShapeActor = &actor; increaseActorCount(&mFreeSlot); } void NpShape::onActorDetach() { PX_ASSERT(getActorCount() > 0); decreaseActorCount(&mFreeSlot); if(isExclusiveFast()) mExclusiveShapeActor = NULL; RefCountable_decRefCount(*this); } void NpShape::incActorCount() { RefCountable_incRefCount(*this); increaseActorCount(&mFreeSlot); } void NpShape::decActorCount() { PX_ASSERT(getActorCount() > 0); decreaseActorCount(&mFreeSlot); RefCountable_decRefCount(*this); } void NpShape::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(isWritable(), "PxShape::setName: shared shapes attached to actors are not writable."); mCore.mName = debugName; UPDATE_PVD_PROPERTY } const char* NpShape::getName() const { NP_READ_CHECK(getNpScene()); return mCore.mName; } /////////////////////////////////////////////////////////////////////////////// // see NpConvexMesh.h, NpHeightField.h, NpTriangleMesh.h for details on how ref counting works for meshes PxRefCounted* NpShape::getMeshRefCountable() { const PxGeometry& geometry = mCore.getGeometry(); switch(PxU32(mCore.getGeometryType())) { case PxGeometryType::eCONVEXMESH: return static_cast<const PxConvexMeshGeometry&>(geometry).convexMesh; case PxGeometryType::eHEIGHTFIELD: return static_cast<const PxHeightFieldGeometry&>(geometry).heightField; case PxGeometryType::eTRIANGLEMESH: return static_cast<const PxTriangleMeshGeometry&>(geometry).triangleMesh; case PxGeometryType::eTETRAHEDRONMESH: return static_cast<const PxTetrahedronMeshGeometry&>(geometry).tetrahedronMesh; default: break; } return NULL; } bool NpShape::isWritable() { // a shape is writable if it's exclusive, or it's not connected to any actors (which is true if the ref count is 1 and the user ref is not released.) return isExclusiveFast() || (RefCountable_getRefCount(*this)==1 && (mBaseFlags & PxBaseFlag::eIS_RELEASABLE)); } void NpShape::incMeshRefCount() { PxRefCounted* mesh = getMeshRefCountable(); if(mesh) RefCountable_incRefCount(*mesh); } void NpShape::decMeshRefCount() { PxRefCounted* mesh = getMeshRefCountable(); if(mesh) RefCountable_decRefCount(*mesh); } /////////////////////////////////////////////////////////////////////////////// template <typename PxMaterialType, typename NpMaterialType> bool NpShape::setMaterialsHelper(PxMaterialType* const* materials, PxU16 materialCount) { PX_ASSERT(!isAPIWriteForbidden()); if(materialCount == 1) { const PxU16 materialIndex = static_cast<NpMaterialType*>(materials[0])->mMaterial.mMaterialIndex; mCore.setMaterialIndices(&materialIndex, 1); } else { PX_ASSERT(materialCount > 1); PX_ALLOCA(materialIndices, PxU16, materialCount); if(materialIndices) { NpMaterialType::getMaterialIndices(materials, materialIndices, materialCount); mCore.setMaterialIndices(materialIndices, materialCount); } else return outputError<PxErrorCode::eOUT_OF_MEMORY>(__LINE__, "PxShape::setMaterials() failed. Out of memory. Call will be ignored."); } NpScene* npScene = getNpScene(); if(npScene) npScene->getScScene().notifyNphaseOnUpdateShapeMaterial(mCore); return true; } void NpShape::notifyActorAndUpdatePVD(Sc::ShapeChangeNotifyFlags notifyFlags) { // shared shapes return NULL. But shared shapes aren't mutable when attached to an actor, so no notification needed. if(mExclusiveShapeActor) { Sc::RigidCore* rigidCore = getScRigidObjectSLOW(); if(rigidCore) rigidCore->onShapeChange(mCore, notifyFlags); #if PX_SUPPORT_GPU_PHYSX const PxType type = mExclusiveShapeActor->getConcreteType(); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION if(type==PxConcreteType::eFEM_CLOTH) static_cast<NpFEMCloth*>(mExclusiveShapeActor)->getCore().onShapeChange(mCore, notifyFlags); #endif if(type==PxConcreteType::eSOFT_BODY) static_cast<NpSoftBody*>(mExclusiveShapeActor)->getCore().onShapeChange(mCore, notifyFlags); #endif } UPDATE_PVD_PROPERTY } void NpShape::notifyActorAndUpdatePVD(const PxShapeFlags oldShapeFlags) { // shared shapes return NULL. But shared shapes aren't mutable when attached to an actor, so no notification needed. Sc::RigidCore* rigidCore = getScRigidObjectSLOW(); if(rigidCore) rigidCore->onShapeFlagsChange(mCore, oldShapeFlags); UPDATE_PVD_PROPERTY }
32,794
C++
32.567042
184
0.751296
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSceneQueries.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_SCENE_QUERIES_H #define NP_SCENE_QUERIES_H #include "PxSceneQueryDesc.h" #include "SqQuery.h" #include "ScSqBoundsSync.h" #if PX_SUPPORT_PVD #include "NpPvdSceneQueryCollector.h" #include "NpPvdSceneClient.h" #endif #include "PxSceneQuerySystem.h" #include "NpBounds.h" // PT: for SQ_PRUNER_EPSILON namespace physx { class PxScene; class PxSceneDesc; namespace Vd { class PvdSceneClient; } class NpSceneQueries : public Sc::SqBoundsSync #if PX_SUPPORT_PVD , public Sq::PVDCapture #endif { PX_NOCOPY(NpSceneQueries) public: // PT: TODO: use PxSceneQueryDesc here, but we need some SQ-specific "scene limits" NpSceneQueries(const PxSceneDesc& desc, Vd::PvdSceneClient* pvd, PxU64 contextID); ~NpSceneQueries(); PX_FORCE_INLINE PxSceneQuerySystem& getSQAPI() { PX_ASSERT(mSQ); return *mSQ; } PX_FORCE_INLINE const PxSceneQuerySystem& getSQAPI() const { PX_ASSERT(mSQ); return *mSQ; } protected: // SqBoundsSync virtual void sync(PxU32 prunerIndex, const ScPrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) PX_OVERRIDE; //~SqBoundsSync public: PxSceneQuerySystem* mSQ; #if PX_SUPPORT_PVD Vd::PvdSceneClient* mPVDClient; //Scene query and hits for pvd, collected in current frame mutable Vd::PvdSceneQueryCollector mSingleSqCollector; PX_FORCE_INLINE Vd::PvdSceneQueryCollector& getSingleSqCollector() const { return mSingleSqCollector; } // PVDCapture virtual bool transmitSceneQueries(); virtual void raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits); virtual void sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits); virtual void overlap(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData); //~PVDCapture #endif // PX_SUPPORT_PVD }; } // namespace physx, sq #endif
3,958
C
39.814433
214
0.751642
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpConnector.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_CONNECTOR_H #define NP_CONNECTOR_H #include "common/PxSerialFramework.h" #include "foundation/PxInlineArray.h" #include "foundation/PxUtilities.h" #include "CmUtils.h" namespace physx { struct NpConnectorType { enum Enum { eConstraint, eAggregate, eObserver, eBvh, eInvalid }; }; class NpConnector { public: NpConnector() : mType(NpConnectorType::eInvalid), mObject(NULL) {} NpConnector(NpConnectorType::Enum type, PxBase* object) : mType(PxTo8(type)), mObject(object) {} // PX_SERIALIZATION NpConnector(const NpConnector& c) { //special copy constructor that initializes padding bytes for meta data verification (PX_CHECKED only) PxMarkSerializedMemory(this, sizeof(NpConnector)); mType = c.mType; mObject = c.mObject; } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION PxU8 mType; // Revisit whether the type is really necessary or whether the serializable type is enough. // Since joints might gonna inherit from observers to register for constraint release events, the type // is necessary because a joint has its own serializable type and could not be detected as observer anymore. PxU8 mPadding[3]; // PT: padding from prev byte PxBase* mObject; // So far the serialization framework only supports ptr resolve for PxBase objects. // However, so far the observers all are PxBase, hence this choice of type. }; class NpConnectorIterator { public: PX_FORCE_INLINE NpConnectorIterator(NpConnector* c, PxU32 size, NpConnectorType::Enum type) : mConnectors(c), mSize(size), mIndex(0), mType(type) {} PX_FORCE_INLINE PxBase* getNext() { PxBase* s = NULL; while(mIndex < mSize) { NpConnector& c = mConnectors[mIndex]; mIndex++; if (c.mType == mType) return c.mObject; } return s; } private: NpConnector* mConnectors; PxU32 mSize; PxU32 mIndex; NpConnectorType::Enum mType; }; class NpConnectorArray: public PxInlineArray<NpConnector, 4> { public: // PX_SERIALIZATION NpConnectorArray(const PxEMPTY) : PxInlineArray<NpConnector, 4> (PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpConnectorArray() : PxInlineArray<NpConnector, 4>("connectorArray") { //special default constructor that initializes padding bytes for meta data verification (PX_CHECKED only) PxMarkSerializedMemory(this->mData, 4*sizeof(NpConnector)); } }; } #endif
4,136
C
33.475
149
0.746857
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpBounds.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/PxTransform.h" #include "NpBounds.h" #include "CmTransformUtils.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "GuBounds.h" using namespace physx; using namespace Sq; static void computeStaticWorldAABB(PxBounds3& bounds, const NpShape& npShape, const NpActor& npActor) { const PxTransform& shape2Actor = npShape.getCore().getShape2Actor(); PX_ALIGN(16, PxTransform) globalPose; Cm::getStaticGlobalPoseAligned(static_cast<const NpRigidStatic&>(npActor).getCore().getActor2World(), shape2Actor, globalPose); Gu::computeBounds(bounds, npShape.getCore().getGeometry(), globalPose, 0.0f, SQ_PRUNER_INFLATION); } static void computeDynamicWorldAABB(PxBounds3& bounds, const NpShape& npShape, const NpActor& npActor) { const PxTransform& shape2Actor = npShape.getCore().getShape2Actor(); PX_ALIGN(16, PxTransform) globalPose; { PX_ALIGN(16, PxTransform) kinematicTarget; const PxU16 sqktFlags = PxRigidBodyFlag::eKINEMATIC | PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES; // PT: TODO: revisit this once the dust has settled PX_ASSERT(npActor.getNpType()==NpType::eBODY_FROM_ARTICULATION_LINK || npActor.getNpType()==NpType::eBODY); const Sc::BodyCore& core = npActor.getNpType()==NpType::eBODY_FROM_ARTICULATION_LINK ? static_cast<const NpArticulationLink&>(npActor).getCore() : static_cast<const NpRigidDynamic&>(npActor).getCore(); const bool useTarget = (PxU16(core.getFlags()) & sqktFlags) == sqktFlags; const PxTransform& body2World = (useTarget && core.getKinematicTarget(kinematicTarget)) ? kinematicTarget : core.getBody2World(); Cm::getDynamicGlobalPoseAligned(body2World, shape2Actor, core.getBody2Actor(), globalPose); } Gu::computeBounds(bounds, npShape.getCore().getGeometry(), globalPose, 0.0f, SQ_PRUNER_INFLATION); } const ComputeBoundsFunc Sq::gComputeBoundsTable[2] = { computeStaticWorldAABB, computeDynamicWorldAABB };
3,653
C++
47.719999
203
0.7706
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPhysics.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 "NpPhysics.h" // PX_SERIALIZATION #include "foundation/PxProfiler.h" #include "foundation/PxIO.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxString.h" #include "foundation/PxPhysicsVersion.h" #include "common/PxTolerancesScale.h" #include "CmCollection.h" #include "CmUtils.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #include "NpHairSystem.h" #endif #include "NpArticulationReducedCoordinate.h" #include "NpArticulationLink.h" #include "NpMaterial.h" #include "GuHeightFieldData.h" #include "GuHeightField.h" #include "GuConvexMesh.h" #include "GuTriangleMesh.h" #include "foundation/PxIntrinsics.h" #include "PxvGlobals.h" // dynamic registration of HFs & articulations in LL #include "GuOverlapTests.h" // dynamic registration of HFs in Gu #include "PxDeletionListener.h" #include "PxPhysicsSerialization.h" #include "PvdPhysicsClient.h" #include "omnipvd/NpOmniPvdSetData.h" #if PX_SUPPORT_OMNI_PVD #include "omnipvd/NpOmniPvd.h" #include "OmniPvdWriter.h" #endif #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXGpu.h" #endif //~PX_SERIALIZATION #include "NpFactory.h" #if PX_SWITCH #include "switch/NpMiddlewareInfo.h" #endif #if PX_SUPPORT_OMNI_PVD # define OMNI_PVD_NOTIFY_ADD(OBJECT) mOmniPvdListener.onObjectAdd(OBJECT) # define OMNI_PVD_NOTIFY_REMOVE(OBJECT) mOmniPvdListener.onObjectRemove(OBJECT) #else # define OMNI_PVD_NOTIFY_ADD(OBJECT) # define OMNI_PVD_NOTIFY_REMOVE(OBJECT) #endif using namespace physx; using namespace Cm; bool NpPhysics::apiReentryLock = false; NpPhysics* NpPhysics::mInstance = NULL; PxU32 NpPhysics::mRefCount = 0; NpPhysics::NpPhysics(const PxTolerancesScale& scale, const PxvOffsetTable& pxvOffsetTable, bool trackOutstandingAllocations, pvdsdk::PsPvd* pvd, PxFoundation& foundation, PxOmniPvd* omniPvd) : mSceneArray ("physicsSceneArray"), mPhysics (scale, pxvOffsetTable), mDeletionListenersExist (false), mFoundation (foundation) #if PX_SUPPORT_GPU_PHYSX , mNbRegisteredGpuClients (0) #endif { PX_UNUSED(trackOutstandingAllocations); //mMasterMaterialTable.reserve(10); #if PX_SUPPORT_PVD mPvd = pvd; if(pvd) { mPvdPhysicsClient = PX_NEW(Vd::PvdPhysicsClient)(mPvd); foundation.registerErrorCallback(*mPvdPhysicsClient); foundation.registerAllocationListener(*mPvd); } else { mPvdPhysicsClient = NULL; } #else PX_UNUSED(pvd); #endif // PT: please leave this commented-out block here. /* printf("sizeof(NpScene) = %d\n", sizeof(NpScene)); printf("sizeof(NpShape) = %d\n", sizeof(NpShape)); printf("sizeof(NpActor) = %d\n", sizeof(NpActor)); printf("sizeof(NpRigidStatic) = %d\n", sizeof(NpRigidStatic)); printf("sizeof(NpRigidDynamic) = %d\n", sizeof(NpRigidDynamic)); printf("sizeof(NpMaterial) = %d\n", sizeof(NpMaterial)); printf("sizeof(NpConstraint) = %d\n", sizeof(NpConstraint)); printf("sizeof(NpAggregate) = %d\n", sizeof(NpAggregate)); printf("sizeof(NpArticulationRC) = %d\n", sizeof(NpArticulationReducedCoordinate)); printf("sizeof(GeometryUnion) = %d\n", sizeof(GeometryUnion)); printf("sizeof(PxGeometry) = %d\n", sizeof(PxGeometry)); printf("sizeof(PxPlaneGeometry) = %d\n", sizeof(PxPlaneGeometry)); printf("sizeof(PxSphereGeometry) = %d\n", sizeof(PxSphereGeometry)); printf("sizeof(PxCapsuleGeometry) = %d\n", sizeof(PxCapsuleGeometry)); printf("sizeof(PxBoxGeometry) = %d\n", sizeof(PxBoxGeometry)); printf("sizeof(PxConvexMeshGeometry) = %d\n", sizeof(PxConvexMeshGeometry)); printf("sizeof(PxConvexMeshGeometryLL) = %d\n", sizeof(PxConvexMeshGeometryLL)); printf("sizeof(PxTriangleMeshGeometry) = %d\n", sizeof(PxTriangleMeshGeometry)); printf("sizeof(PxTriangleMeshGeometryLL) = %d\n", sizeof(PxTriangleMeshGeometryLL)); printf("sizeof(PxsShapeCore) = %d\n", sizeof(PxsShapeCore)); */ #if PX_SUPPORT_OMNI_PVD mOmniPvdSampler = NULL; mOmniPvd = NULL; if (omniPvd) { OmniPvdWriter* omniWriter = omniPvd->getWriter(); if (omniWriter && omniWriter->getWriteStream()) { mOmniPvdSampler = PX_NEW(::OmniPvdPxSampler)(); mOmniPvd = omniPvd; NpOmniPvd* npOmniPvd = static_cast<NpOmniPvd*>(mOmniPvd); NpOmniPvd::incRefCount(); npOmniPvd->mPhysXSampler = mOmniPvdSampler; // Dirty hack to do startSampling from PxOmniPvd mOmniPvdSampler->setOmniPvdInstance(npOmniPvd); } } #else PX_UNUSED(omniPvd); #endif } NpPhysics::~NpPhysics() { // Release all scenes in case the user didn't do it PxU32 nbScenes = mSceneArray.size(); NpScene** scenes = mSceneArray.begin(); for(PxU32 i=0;i<nbScenes;i++) PX_DELETE(scenes[i]); mSceneArray.clear(); //PxU32 matCount = mMasterMaterialTable.size(); //while (mMasterMaterialTable.size() > 0) //{ // // It's done this way since the material destructor removes the material from the table and adjusts indices // PX_ASSERT(mMasterMaterialTable[0]->getRefCount() == 1); // mMasterMaterialTable[0]->decRefCount(); //} //mMasterMaterialTable.clear(); mMasterMaterialManager.releaseMaterials(); #if PX_SUPPORT_GPU_PHYSX mMasterFEMSoftBodyMaterialManager.releaseMaterials(); mMasterPBDMaterialManager.releaseMaterials(); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION mMasterFEMClothMaterialManager.releaseMaterials(); mMasterFLIPMaterialManager.releaseMaterials(); mMasterMPMMaterialManager.releaseMaterials(); #endif #endif #if PX_SUPPORT_PVD if(mPvd) { mPvdPhysicsClient->destroyPvdInstance(this); mPvd->removeClient(mPvdPhysicsClient); mFoundation.deregisterErrorCallback(*mPvdPhysicsClient); PX_DELETE(mPvdPhysicsClient); mFoundation.deregisterAllocationListener(*mPvd); } #endif const DeletionListenerMap::Entry* delListenerEntries = mDeletionListenerMap.getEntries(); const PxU32 delListenerEntryCount = mDeletionListenerMap.size(); for(PxU32 i=0; i < delListenerEntryCount; i++) { NpDelListenerEntry* listener = delListenerEntries[i].second; PX_DELETE(listener); } mDeletionListenerMap.clear(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, static_cast<PxPhysics&>(*this)) PX_DELETE(mOmniPvdSampler); if (mOmniPvd) { NpOmniPvd::decRefCount(); } #endif #if PX_SUPPORT_GPU_PHYSX PxPhysXGpu* gpu = PxvGetPhysXGpu(false); if (gpu) PxvReleasePhysXGpu(gpu); #endif } PxOmniPvd* NpPhysics::getOmniPvd() { #if PX_SUPPORT_OMNI_PVD return mOmniPvd; #else return NULL; #endif } void NpPhysics::initOffsetTables(PxvOffsetTable& pxvOffsetTable) { // init offset tables for Pxs/Sc/Px conversions { Sc::OffsetTable& offsetTable = Sc::gOffsetTable; offsetTable.scRigidStatic2PxActor = -ptrdiff_t(NpRigidStatic::getCoreOffset()); offsetTable.scRigidDynamic2PxActor = -ptrdiff_t(NpRigidDynamic::getCoreOffset()); offsetTable.scArticulationLink2PxActor = -ptrdiff_t(NpArticulationLink::getCoreOffset()); #if PX_SUPPORT_GPU_PHYSX offsetTable.scSoftBody2PxActor = -ptrdiff_t(NpSoftBody::getCoreOffset()); offsetTable.scPBDParticleSystem2PxActor = -ptrdiff_t(NpPBDParticleSystem::getCoreOffset()); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION offsetTable.scFLIPParticleSystem2PxActor = -ptrdiff_t(NpFLIPParticleSystem::getCoreOffset()); offsetTable.scMPMParticleSystem2PxActor = -ptrdiff_t(NpMPMParticleSystem::getCoreOffset()); offsetTable.scHairSystem2PxActor = -ptrdiff_t(NpHairSystem::getCoreOffset()); #endif #endif offsetTable.scArticulationRC2Px = -ptrdiff_t(NpArticulationReducedCoordinate::getCoreOffset()); offsetTable.scArticulationJointRC2Px = -ptrdiff_t(NpArticulationJointReducedCoordinate::getCoreOffset()); offsetTable.scConstraint2Px = -ptrdiff_t(NpConstraint::getCoreOffset()); offsetTable.scShape2Px = -ptrdiff_t(NpShape::getCoreOffset()); for(PxU32 i=0;i<PxActorType::eACTOR_COUNT;i++) offsetTable.scCore2PxActor[i] = 0; offsetTable.scCore2PxActor[PxActorType::eRIGID_STATIC] = offsetTable.scRigidStatic2PxActor; offsetTable.scCore2PxActor[PxActorType::eRIGID_DYNAMIC] = offsetTable.scRigidDynamic2PxActor; offsetTable.scCore2PxActor[PxActorType::eARTICULATION_LINK] = offsetTable.scArticulationLink2PxActor; offsetTable.scCore2PxActor[PxActorType::eSOFTBODY] = offsetTable.scSoftBody2PxActor; offsetTable.scCore2PxActor[PxActorType::ePBD_PARTICLESYSTEM] = offsetTable.scPBDParticleSystem2PxActor; offsetTable.scCore2PxActor[PxActorType::eFLIP_PARTICLESYSTEM] = offsetTable.scFLIPParticleSystem2PxActor; offsetTable.scCore2PxActor[PxActorType::eMPM_PARTICLESYSTEM] = offsetTable.scMPMParticleSystem2PxActor; offsetTable.scCore2PxActor[PxActorType::eHAIRSYSTEM] = offsetTable.scHairSystem2PxActor; } { Sc::OffsetTable& scOffsetTable = Sc::gOffsetTable; pxvOffsetTable.pxsShapeCore2PxShape = scOffsetTable.scShape2Px - ptrdiff_t(Sc::ShapeCore::getCoreOffset()); pxvOffsetTable.pxsRigidCore2PxRigidBody = scOffsetTable.scRigidDynamic2PxActor - ptrdiff_t(Sc::BodyCore::getCoreOffset()); pxvOffsetTable.pxsRigidCore2PxRigidStatic = scOffsetTable.scRigidStatic2PxActor - ptrdiff_t(Sc::StaticCore::getCoreOffset()); } } NpPhysics* NpPhysics::createInstance(PxU32 version, PxFoundation& foundation, const PxTolerancesScale& scale, bool trackOutstandingAllocations, pvdsdk::PsPvd* pvd, PxOmniPvd* omniPvd) { #if PX_SWITCH NpSetMiddlewareInfo(); // register middleware info such that PhysX usage can be tracked #endif if (version!=PX_PHYSICS_VERSION) { char buffer[256]; Pxsnprintf(buffer, 256, "Wrong version: PhysX version is 0x%08x, tried to create 0x%08x", PX_PHYSICS_VERSION, version); foundation.getErrorCallback().reportError(PxErrorCode::eINVALID_PARAMETER, buffer, PX_FL); return NULL; } if (!scale.isValid()) { foundation.getErrorCallback().reportError(PxErrorCode::eINVALID_PARAMETER, "Scale invalid.\n", PX_FL); return NULL; } if(0 == mRefCount) { PX_ASSERT(&foundation == &PxGetFoundation()); PxIncFoundationRefCount(); // init offset tables for Pxs/Sc/Px conversions PxvOffsetTable pxvOffsetTable; initOffsetTables(pxvOffsetTable); //SerialFactory::createInstance(); mInstance = PX_NEW (NpPhysics)(scale, pxvOffsetTable, trackOutstandingAllocations, pvd, foundation, omniPvd); NpFactory::createInstance(); #if PX_SUPPORT_OMNI_PVD if (omniPvd) NpFactory::getInstance().addFactoryListener(mInstance->mOmniPvdListener); #endif #if PX_SUPPORT_PVD if(pvd) { NpFactory::getInstance().setNpFactoryListener( *mInstance->mPvdPhysicsClient ); pvd->addClient(mInstance->mPvdPhysicsClient); } #endif NpFactory::getInstance().addFactoryListener(mInstance->mDeletionMeshListener); } ++mRefCount; return mInstance; } PxU32 NpPhysics::releaseInstance() { PX_ASSERT(mRefCount > 0); if (--mRefCount) return mRefCount; #if PX_SUPPORT_PVD if(mInstance->mPvd) { NpFactory::getInstance().removeFactoryListener( *mInstance->mPvdPhysicsClient ); } #endif NpFactory::destroyInstance(); PX_ASSERT(mInstance); PX_DELETE(mInstance); PxDecFoundationRefCount(); return mRefCount; } void NpPhysics::release() { NpPhysics::releaseInstance(); } PxScene* NpPhysics::createScene(const PxSceneDesc& desc) { PX_CHECK_AND_RETURN_NULL(desc.isValid(), "Physics::createScene: desc.isValid() is false!"); const PxTolerancesScale& scale = mPhysics.getTolerancesScale(); const PxTolerancesScale& descScale = desc.getTolerancesScale(); PX_UNUSED(scale); PX_UNUSED(descScale); PX_CHECK_AND_RETURN_NULL((descScale.length == scale.length) && (descScale.speed == scale.speed), "Physics::createScene: PxTolerancesScale must be the same as used for creation of PxPhysics!"); PxMutex::ScopedLock lock(mSceneAndMaterialMutex); // done here because scene constructor accesses profiling manager of the SDK NpScene* npScene = PX_NEW (NpScene)(desc, *this); if(!npScene) { mFoundation.error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Unable to create scene."); return NULL; } if(!npScene->getTaskManagerFast()) { mFoundation.error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Unable to create scene. Task manager creation failed."); return NULL; } npScene->loadFromDesc(desc); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, scenes, static_cast<PxPhysics&>(*this), static_cast<PxScene&>(*npScene)) #if PX_SUPPORT_PVD if(mPvd) { npScene->getScenePvdClientInternal().setPsPvd(mPvd); mPvd->addClient(&npScene->getScenePvdClientInternal()); } #endif if (!sendMaterialTable(*npScene) || !npScene->getScScene().isValid()) { PX_DELETE(npScene); mFoundation.error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "Unable to create scene."); return NULL; } mSceneArray.pushBack(npScene); return npScene; } void NpPhysics::releaseSceneInternal(PxScene& scene) { NpScene* pScene = static_cast<NpScene*>(&scene); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, scenes, static_cast<PxPhysics&>(*this), scene) PxMutex::ScopedLock lock(mSceneAndMaterialMutex); for(PxU32 i=0;i<mSceneArray.size();i++) { if(mSceneArray[i]==pScene) { mSceneArray.replaceWithLast(i); PX_DELETE(pScene); return; } } } PxU32 NpPhysics::getNbScenes() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mSceneArray.size(); } PxU32 NpPhysics::getScenes(PxScene** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mSceneArray.begin(), mSceneArray.size()); } PxRigidStatic* NpPhysics::createRigidStatic(const PxTransform& globalPose) { PX_CHECK_AND_RETURN_NULL(globalPose.isSane(), "PxPhysics::createRigidStatic: invalid transform"); return NpFactory::getInstance().createRigidStatic(globalPose.getNormalized()); } PxShape* NpPhysics::createShape(const PxGeometry& geometry, PxMaterial*const * materials, PxU16 materialCount, bool isExclusive, PxShapeFlags shapeFlags) { PX_CHECK_AND_RETURN_NULL(materials, "createShape: material pointer is NULL"); PX_CHECK_AND_RETURN_NULL(materialCount>0, "createShape: material count is zero"); #if PX_CHECKED const bool isHeightfield = geometry.getType() == PxGeometryType::eHEIGHTFIELD; const bool hasMeshTypeGeom = isHeightfield || (geometry.getType() == PxGeometryType::eTRIANGLEMESH) || (geometry.getType() == PxGeometryType::eTETRAHEDRONMESH); PX_CHECK_AND_RETURN_NULL(!(hasMeshTypeGeom && (shapeFlags & PxShapeFlag::eTRIGGER_SHAPE)), "NpPhysics::createShape: triangle mesh/heightfield/tetrahedron mesh triggers are not supported!"); PX_CHECK_AND_RETURN_NULL(!((shapeFlags & PxShapeFlag::eSIMULATION_SHAPE) && (shapeFlags & PxShapeFlag::eTRIGGER_SHAPE)), "NpPhysics::createShape: shapes cannot simultaneously be trigger shapes and simulation shapes."); #endif return NpFactory::getInstance().createShape(geometry, shapeFlags, materials, materialCount, isExclusive); } PxShape* NpPhysics::createShape(const PxGeometry& geometry, PxFEMSoftBodyMaterial*const * materials, PxU16 materialCount, bool isExclusive, PxShapeFlags shapeFlags) { PX_CHECK_AND_RETURN_NULL(materials, "createShape: material pointer is NULL"); PX_CHECK_AND_RETURN_NULL(materialCount > 0, "createShape: material count is zero"); PX_CHECK_AND_RETURN_NULL(geometry.getType() == PxGeometryType::eTETRAHEDRONMESH, "createShape: soft bodies only accept PxTetrahedronMeshGeometry"); PX_CHECK_AND_RETURN_NULL(shapeFlags & PxShapeFlag::eSIMULATION_SHAPE, "createShape: soft body shapes must be simulation shapes"); return NpFactory::getInstance().createShape(geometry, shapeFlags, materials, materialCount, isExclusive); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX PxShape* NpPhysics::createShape(const PxGeometry& geometry, PxFEMClothMaterial*const * materials, PxU16 materialCount, bool isExclusive, PxShapeFlags shapeFlags) { PX_CHECK_AND_RETURN_NULL(materials, "createShape: material pointer is NULL"); PX_CHECK_AND_RETURN_NULL(materialCount > 0, "createShape: material count is zero"); PX_CHECK_AND_RETURN_NULL(geometry.getType() == PxGeometryType::eTRIANGLEMESH, "createShape: cloth only accept PxTriangleMeshGeometry"); PX_CHECK_AND_RETURN_NULL(shapeFlags & PxShapeFlag::eSIMULATION_SHAPE, "createShape: cloth shapes must be simulation shapes"); return NpFactory::getInstance().createShape(geometry, shapeFlags, materials, materialCount, isExclusive); } #else PxShape* NpPhysics::createShape(const PxGeometry&, PxFEMClothMaterial*const *, PxU16, bool, PxShapeFlags) { return NULL; } #endif PxU32 NpPhysics::getNbShapes() const { return NpFactory::getInstance().getNbShapes(); } PxU32 NpPhysics::getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return NpFactory::getInstance().getShapes(userBuffer, bufferSize, startIndex); } PxRigidDynamic* NpPhysics::createRigidDynamic(const PxTransform& globalPose) { PX_CHECK_AND_RETURN_NULL(globalPose.isSane(), "PxPhysics::createRigidDynamic: invalid transform"); return NpFactory::getInstance().createRigidDynamic(globalPose.getNormalized()); } PxConstraint* NpPhysics::createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) { return NpFactory::getInstance().createConstraint(actor0, actor1, connector, shaders, dataSize); } PxArticulationReducedCoordinate* NpPhysics::createArticulationReducedCoordinate() { return NpFactory::getInstance().createArticulationRC(); } PxSoftBody* NpPhysics::createSoftBody(PxCudaContextManager& cudaContextManager) { #if PX_SUPPORT_GPU_PHYSX return NpFactory::getInstance().createSoftBody(cudaContextManager); #else PX_UNUSED(cudaContextManager); return NULL; #endif } PxPBDParticleSystem* NpPhysics::createPBDParticleSystem(PxCudaContextManager& cudaContextManager, PxU32 maxNeighborhood) { #if PX_SUPPORT_GPU_PHYSX return NpFactory::getInstance().createPBDParticleSystem(maxNeighborhood, cudaContextManager); #else PX_UNUSED(cudaContextManager); PX_UNUSED(maxNeighborhood); return NULL; #endif } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX PxFLIPParticleSystem* NpPhysics::createFLIPParticleSystem(PxCudaContextManager& cudaContextManager) { return NpFactory::getInstance().createFLIPParticleSystem(cudaContextManager); } PxMPMParticleSystem* NpPhysics::createMPMParticleSystem(PxCudaContextManager& cudaContextManager) { return NpFactory::getInstance().createMPMParticleSystem( cudaContextManager); } PxFEMCloth* NpPhysics::createFEMCloth(PxCudaContextManager& cudaContextManager) { return NpFactory::getInstance().createFEMCloth(cudaContextManager); } PxHairSystem* NpPhysics::createHairSystem(PxCudaContextManager& cudaContextManager) { return NpFactory::getInstance().createHairSystem(cudaContextManager); } #else PxFLIPParticleSystem* NpPhysics::createFLIPParticleSystem(PxCudaContextManager&) { return NULL; } PxMPMParticleSystem* NpPhysics::createMPMParticleSystem(PxCudaContextManager&) { return NULL; } PxFEMCloth* NpPhysics::createFEMCloth(PxCudaContextManager&) { return NULL; } PxHairSystem* NpPhysics::createHairSystem(PxCudaContextManager&) { return NULL; } #endif PxAggregate* NpPhysics::createAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint) { PX_CHECK_AND_RETURN_VAL(!(PxGetAggregateSelfCollisionBit(filterHint) && PxGetAggregateType(filterHint)==PxAggregateType::eSTATIC), "PxPhysics::createAggregate: static aggregates with self-collisions are not allowed.", NULL); return NpFactory::getInstance().createAggregate(maxActors, maxShapes, filterHint); } /////////////////////////////////////////////////////////////////////////////// template<class NpMaterialT> static NpMaterialT* addMaterial( #if PX_SUPPORT_OMNI_PVD NpPhysics::OmniPvdListener& mOmniPvdListener, #endif NpMaterialT* m, NpMaterialManager<NpMaterialT>& materialManager, PxMutex& mutex, PxArray<NpScene*>& sceneArray, const char* error) { if(!m) return NULL; OMNI_PVD_NOTIFY_ADD(m); PxMutex::ScopedLock lock(mutex); //the handle is set inside the setMaterial method if(materialManager.setMaterial(*m)) { // Let all scenes know of the new material const PxU32 nbScenes = sceneArray.size(); for(PxU32 i=0; i<nbScenes; i++) sceneArray[i]->addMaterial(*m); return m; } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, error); m->release(); return NULL; } } template<class NpMaterialT, class PxMaterialT> static PxU32 getMaterials(const NpMaterialManager<NpMaterialT>& materialManager, const PxMutex& mutex, PxMaterialT** userBuffer, PxU32 bufferSize, PxU32 startIndex) { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mutex)); NpMaterialManagerIterator<NpMaterialT> iter(materialManager); PxU32 writeCount =0; PxU32 index = 0; NpMaterialT* mat; while(iter.getNextMaterial(mat)) { if(index++ < startIndex) continue; if(writeCount == bufferSize) break; userBuffer[writeCount++] = mat; } return writeCount; } template<class NpMaterialT> static void removeMaterialFromTable( #if PX_SUPPORT_OMNI_PVD NpPhysics::OmniPvdListener& mOmniPvdListener, #endif NpMaterialT& m, NpMaterialManager<NpMaterialT>& materialManager, PxMutex& mutex, PxArray<NpScene*>& sceneArray) { OMNI_PVD_NOTIFY_REMOVE(&m); PxMutex::ScopedLock lock(mutex); // Let all scenes know of the deleted material const PxU32 nbScenes = sceneArray.size(); for(PxU32 i=0; i<nbScenes; i++) sceneArray[i]->removeMaterial(m); materialManager.removeMaterial(m); } template<class NpMaterialT> static void updateMaterial(NpMaterialT& m, NpMaterialManager<NpMaterialT>& materialManager, PxMutex& mutex, PxArray<NpScene*>& sceneArray) { PxMutex::ScopedLock lock(mutex); // Let all scenes know of the updated material const PxU32 nbScenes = sceneArray.size(); for(PxU32 i=0; i<nbScenes; i++) sceneArray[i]->updateMaterial(m); materialManager.updateMaterial(m); } #if PX_SUPPORT_OMNI_PVD #define _addMaterial(p0, p1, p2, p3, p4) ::addMaterial(mOmniPvdListener, p0, p1, p2, p3, p4) #define _removeMaterialFromTable(p0, p1, p2, p3) ::removeMaterialFromTable(mOmniPvdListener, p0, p1, p2, p3) #else #define _addMaterial(p0, p1, p2, p3, p4) ::addMaterial(p0, p1, p2, p3, p4) #define _removeMaterialFromTable(p0, p1, p2, p3) ::removeMaterialFromTable(p0, p1, p2, p3) #endif #define IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpMaterialT, manager, errorMsg) \ NpMaterialT* NpPhysics::addMaterial(NpMaterialT* m) \ { \ return _addMaterial(m, manager, mSceneAndMaterialMutex, mSceneArray, errorMsg); \ } \ void NpPhysics::removeMaterialFromTable(NpMaterialT& m) \ { \ _removeMaterialFromTable(m, manager, mSceneAndMaterialMutex, mSceneArray); \ } \ void NpPhysics::updateMaterial(NpMaterialT& m) \ { \ ::updateMaterial(m, manager, mSceneAndMaterialMutex, mSceneArray); \ } /////////////////////////////////////////////////////////////////////////////// template<class NpMaterialT> static void sendMaterialTable(NpScene& scene, const NpMaterialManager<NpMaterialT>& materialManager) { NpMaterialManagerIterator<NpMaterialT> iter(materialManager); NpMaterialT* mat; while(iter.getNextMaterial(mat)) scene.addMaterial(*mat); } bool NpPhysics::sendMaterialTable(NpScene& scene) { // note: no lock here because this method gets only called at scene creation and there we do lock ::sendMaterialTable(scene, mMasterMaterialManager); #if PX_SUPPORT_GPU_PHYSX ::sendMaterialTable(scene, mMasterFEMSoftBodyMaterialManager); ::sendMaterialTable(scene, mMasterPBDMaterialManager); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION ::sendMaterialTable(scene, mMasterFEMClothMaterialManager); ::sendMaterialTable(scene, mMasterFLIPMaterialManager); ::sendMaterialTable(scene, mMasterMPMMaterialManager); #endif #endif return true; } /////////////////////////////////////////////////////////////////////////////// PxMaterial* NpPhysics::createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution) { PxMaterial* m = NpFactory::getInstance().createMaterial(staticFriction, dynamicFriction, restitution); return addMaterial(static_cast<NpMaterial*>(m)); } PxU32 NpPhysics::getNbMaterials() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mMasterMaterialManager.getNumMaterials(); } PxU32 NpPhysics::getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return ::getMaterials(mMasterMaterialManager, mSceneAndMaterialMutex, userBuffer, bufferSize, startIndex); } IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpMaterial, mMasterMaterialManager, "PxPhysics::createMaterial: limit of 64K materials reached.") /////////////////////////////////////////////////////////////////////////////// // PT: all the virtual functions that are unconditionally defined in the API / virtual interface cannot be compiled away entirely. // But the internal functions like addXXXX() can. #if PX_SUPPORT_GPU_PHYSX PxFEMSoftBodyMaterial* NpPhysics::createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction) { PxFEMSoftBodyMaterial* m = NpFactory::getInstance().createFEMSoftBodyMaterial(youngs, poissons, dynamicFriction); return addMaterial(static_cast<NpFEMSoftBodyMaterial*>(m)); } PxU32 NpPhysics::getNbFEMSoftBodyMaterials() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mMasterFEMSoftBodyMaterialManager.getNumMaterials(); } PxU32 NpPhysics::getFEMSoftBodyMaterials(PxFEMSoftBodyMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return ::getMaterials(mMasterFEMSoftBodyMaterialManager, mSceneAndMaterialMutex, userBuffer, bufferSize, startIndex); } IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpFEMSoftBodyMaterial, mMasterFEMSoftBodyMaterialManager, "PxPhysics::createFEMSoftBodyMaterial: limit of 64K materials reached.") #else PxFEMSoftBodyMaterial* NpPhysics::createFEMSoftBodyMaterial(PxReal, PxReal, PxReal) { return NULL; } PxU32 NpPhysics::getNbFEMSoftBodyMaterials() const { return 0; } PxU32 NpPhysics::getFEMSoftBodyMaterials(PxFEMSoftBodyMaterial**, PxU32, PxU32) const { return 0; } #endif /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX PxPBDMaterial* NpPhysics::createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient, PxReal gravityScale) { PxPBDMaterial* m = NpFactory::getInstance().createPBDMaterial(friction, damping, adhesion, viscosity, vorticityConfinement, surfaceTension, cohesion, lift, drag, cflCoefficient, gravityScale); return addMaterial(static_cast<NpPBDMaterial*>(m)); } PxU32 NpPhysics::getNbPBDMaterials() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mMasterPBDMaterialManager.getNumMaterials(); } PxU32 NpPhysics::getPBDMaterials(PxPBDMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return ::getMaterials(mMasterPBDMaterialManager, mSceneAndMaterialMutex, userBuffer, bufferSize, startIndex); } IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpPBDMaterial, mMasterPBDMaterialManager, "PxPhysics::createPBDMaterial: limit of 64K materials reached.") #else PxPBDMaterial* NpPhysics::createPBDMaterial(PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal) { return NULL; } PxU32 NpPhysics::getNbPBDMaterials() const { return 0; } PxU32 NpPhysics::getPBDMaterials(PxPBDMaterial**, PxU32, PxU32) const { return 0; } #endif /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX PxFEMClothMaterial* NpPhysics::createFEMClothMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal thickness) { PxFEMClothMaterial* m = NpFactory::getInstance().createFEMClothMaterial(youngs, poissons, dynamicFriction, thickness); return addMaterial(static_cast<NpFEMClothMaterial*>(m)); } PxU32 NpPhysics::getNbFEMClothMaterials() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mMasterFEMClothMaterialManager.getNumMaterials(); } PxU32 NpPhysics::getFEMClothMaterials(PxFEMClothMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return ::getMaterials(mMasterFEMClothMaterialManager, mSceneAndMaterialMutex, userBuffer, bufferSize, startIndex); } IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpFEMClothMaterial, mMasterFEMClothMaterialManager, "PxPhysics::createFEMClothMaterial: limit of 64K materials reached.") #else PxFEMClothMaterial* NpPhysics::createFEMClothMaterial(PxReal, PxReal, PxReal, PxReal) { return NULL; } PxU32 NpPhysics::getNbFEMClothMaterials() const { return 0; } PxU32 NpPhysics::getFEMClothMaterials(PxFEMClothMaterial**, PxU32, PxU32) const { return 0; } #endif /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX PxFLIPMaterial* NpPhysics::createFLIPMaterial(PxReal friction, PxReal damping, PxReal maxVelocity, PxReal viscosity, PxReal gravityScale) { PxFLIPMaterial* m = NpFactory::getInstance().createFLIPMaterial(friction, damping, maxVelocity, viscosity, gravityScale); return addMaterial(static_cast<NpFLIPMaterial*>(m)); } PxU32 NpPhysics::getNbFLIPMaterials() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mMasterFLIPMaterialManager.getNumMaterials(); } PxU32 NpPhysics::getFLIPMaterials(PxFLIPMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return ::getMaterials(mMasterFLIPMaterialManager, mSceneAndMaterialMutex, userBuffer, bufferSize, startIndex); } IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpFLIPMaterial, mMasterFLIPMaterialManager, "PxPhysics::createFLIPMaterial: limit of 64K materials reached.") #else PxFLIPMaterial* NpPhysics::createFLIPMaterial(PxReal, PxReal, PxReal, PxReal, PxReal) { return NULL; } PxU32 NpPhysics::getNbFLIPMaterials() const { return 0; } PxU32 NpPhysics::getFLIPMaterials(PxFLIPMaterial**, PxU32, PxU32) const { return 0; } #endif /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX PxMPMMaterial* NpPhysics::createMPMMaterial(PxReal friction, PxReal damping, PxReal maxVelocity, bool isPlastic, PxReal youngsModulus, PxReal poissons, PxReal hardening, PxReal criticalCompression, PxReal criticalStretch, PxReal tensileDamageSensitivity, PxReal compressiveDamageSensitivity, PxReal attractiveForceResidual, PxReal gravityScale) { PxMPMMaterial* m = NpFactory::getInstance().createMPMMaterial(friction, damping, maxVelocity, isPlastic, youngsModulus, poissons, hardening, criticalCompression, criticalStretch, tensileDamageSensitivity, compressiveDamageSensitivity, attractiveForceResidual, gravityScale); return addMaterial(static_cast<NpMPMMaterial*>(m)); } PxU32 NpPhysics::getNbMPMMaterials() const { PxMutex::ScopedLock lock(const_cast<PxMutex&>(mSceneAndMaterialMutex)); return mMasterMPMMaterialManager.getNumMaterials(); } PxU32 NpPhysics::getMPMMaterials(PxMPMMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return ::getMaterials(mMasterMPMMaterialManager, mSceneAndMaterialMutex, userBuffer, bufferSize, startIndex); } IMPLEMENT_INTERNAL_MATERIAL_FUNCTIONS(NpMPMMaterial, mMasterMPMMaterialManager, "PxPhysics::createMPMMaterial: limit of 64K materials reached.") #else PxMPMMaterial* NpPhysics::createMPMMaterial(PxReal, PxReal, PxReal, bool, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal, PxReal) { return NULL; } PxU32 NpPhysics::getNbMPMMaterials() const { return 0; } PxU32 NpPhysics::getMPMMaterials(PxMPMMaterial**, PxU32, PxU32) const { return 0; } #endif /////////////////////////////////////////////////////////////////////////////// PxTriangleMesh* NpPhysics::createTriangleMesh(PxInputStream& stream) { return NpFactory::getInstance().createTriangleMesh(stream); } PxU32 NpPhysics::getNbTriangleMeshes() const { return NpFactory::getInstance().getNbTriangleMeshes(); } PxU32 NpPhysics::getTriangleMeshes(PxTriangleMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return NpFactory::getInstance().getTriangleMeshes(userBuffer, bufferSize, startIndex); } /////////////////////////////////////////////////////////////////////////////// PxTetrahedronMesh* NpPhysics::createTetrahedronMesh(PxInputStream& stream) { return NpFactory::getInstance().createTetrahedronMesh(stream); } PxU32 NpPhysics::getNbTetrahedronMeshes() const { return NpFactory::getInstance().getNbTetrahedronMeshes(); } PxU32 NpPhysics::getTetrahedronMeshes(PxTetrahedronMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return NpFactory::getInstance().getTetrahedronMeshes(userBuffer, bufferSize, startIndex); } PxSoftBodyMesh* NpPhysics::createSoftBodyMesh(PxInputStream& stream) { return NpFactory::getInstance().createSoftBodyMesh(stream); } /////////////////////////////////////////////////////////////////////////////// PxHeightField* NpPhysics::createHeightField(PxInputStream& stream) { return NpFactory::getInstance().createHeightField(stream); } PxU32 NpPhysics::getNbHeightFields() const { return NpFactory::getInstance().getNbHeightFields(); } PxU32 NpPhysics::getHeightFields(PxHeightField** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return NpFactory::getInstance().getHeightFields(userBuffer, bufferSize, startIndex); } /////////////////////////////////////////////////////////////////////////////// PxConvexMesh* NpPhysics::createConvexMesh(PxInputStream& stream) { return NpFactory::getInstance().createConvexMesh(stream); } PxU32 NpPhysics::getNbConvexMeshes() const { return NpFactory::getInstance().getNbConvexMeshes(); } PxU32 NpPhysics::getConvexMeshes(PxConvexMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return NpFactory::getInstance().getConvexMeshes(userBuffer, bufferSize, startIndex); } /////////////////////////////////////////////////////////////////////////////// PxBVH* NpPhysics::createBVH(PxInputStream& stream) { return NpFactory::getInstance().createBVH(stream); } PxU32 NpPhysics::getNbBVHs() const { return NpFactory::getInstance().getNbBVHs(); } PxU32 NpPhysics::getBVHs(PxBVH** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return NpFactory::getInstance().getBVHs(userBuffer, bufferSize, startIndex); } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX PxParticleBuffer* NpPhysics::createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager) { return NpFactory::getInstance().createParticleBuffer(maxParticles, maxVolumes, cudaContextManager); } PxParticleAndDiffuseBuffer* NpPhysics::createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager) { return NpFactory::getInstance().createParticleAndDiffuseBuffer(maxParticles, maxVolumes, maxDiffuseParticles, cudaContextManager); } PxParticleClothBuffer* NpPhysics::createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager) { return NpFactory::getInstance().createParticleClothBuffer(maxParticles, maxNumVolumes, maxNumCloths, maxNumTriangles, maxNumSprings, cudaContextManager); } PxParticleRigidBuffer* NpPhysics::createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager) { return NpFactory::getInstance().createParticleRigidBuffer(maxParticles, maxNumVolumes, maxNumRigids, cudaContextManager); } #else PxParticleBuffer* NpPhysics::createParticleBuffer(PxU32, PxU32, PxCudaContextManager*) { return NULL; } PxParticleAndDiffuseBuffer* NpPhysics::createParticleAndDiffuseBuffer(PxU32, PxU32, PxU32, PxCudaContextManager*) { return NULL; } PxParticleClothBuffer* NpPhysics::createParticleClothBuffer(PxU32, PxU32, PxU32, PxU32, PxU32, PxCudaContextManager*) { return NULL; } PxParticleRigidBuffer* NpPhysics::createParticleRigidBuffer(PxU32, PxU32, PxU32, PxCudaContextManager*) { return NULL; } #endif /////////////////////////////////////////////////////////////////////////////// PxPruningStructure* NpPhysics::createPruningStructure(PxRigidActor*const* actors, PxU32 nbActors) { PX_SIMD_GUARD; PX_ASSERT(actors); PX_ASSERT(nbActors > 0); Sq::PruningStructure* ps = PX_NEW(Sq::PruningStructure)(); if(!ps->build(actors, nbActors)) { PX_DELETE(ps); } return ps; } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX void NpPhysics::registerPhysXIndicatorGpuClient() { PxMutex::ScopedLock lock(mPhysXIndicatorMutex); ++mNbRegisteredGpuClients; mPhysXIndicator.setIsGpu(mNbRegisteredGpuClients>0); } void NpPhysics::unregisterPhysXIndicatorGpuClient() { PxMutex::ScopedLock lock(mPhysXIndicatorMutex); if (mNbRegisteredGpuClients) --mNbRegisteredGpuClients; mPhysXIndicator.setIsGpu(mNbRegisteredGpuClients>0); } #endif /////////////////////////////////////////////////////////////////////////////// void NpPhysics::registerDeletionListener(PxDeletionListener& observer, const PxDeletionEventFlags& deletionEvents, bool restrictedObjectSet) { PxMutex::ScopedLock lock(mDeletionListenerMutex); const DeletionListenerMap::Entry* entry = mDeletionListenerMap.find(&observer); if(!entry) { NpDelListenerEntry* e = PX_NEW(NpDelListenerEntry)(deletionEvents, restrictedObjectSet); if (e) { if (mDeletionListenerMap.insert(&observer, e)) mDeletionListenersExist = true; else { PX_DELETE(e); PX_ALWAYS_ASSERT(); } } } else PX_ASSERT(mDeletionListenersExist); } void NpPhysics::unregisterDeletionListener(PxDeletionListener& observer) { PxMutex::ScopedLock lock(mDeletionListenerMutex); const DeletionListenerMap::Entry* entry = mDeletionListenerMap.find(&observer); if(entry) { NpDelListenerEntry* e = entry->second; mDeletionListenerMap.erase(&observer); PX_DELETE(e); } mDeletionListenersExist = mDeletionListenerMap.size()>0; } void NpPhysics::registerDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) { PxMutex::ScopedLock lock(mDeletionListenerMutex); const DeletionListenerMap::Entry* entry = mDeletionListenerMap.find(&observer); if(entry) { NpDelListenerEntry* e = entry->second; PX_CHECK_AND_RETURN(e->restrictedObjectSet, "PxPhysics::registerDeletionListenerObjects: deletion listener is not configured to receive events from specific objects."); e->registeredObjects.reserve(e->registeredObjects.size() + observableCount); for(PxU32 i=0; i < observableCount; i++) e->registeredObjects.insert(observables[i]); } else { PX_CHECK_AND_RETURN(false, "PxPhysics::registerDeletionListenerObjects: deletion listener has to be registered in PxPhysics first."); } } void NpPhysics::unregisterDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) { PxMutex::ScopedLock lock(mDeletionListenerMutex); const DeletionListenerMap::Entry* entry = mDeletionListenerMap.find(&observer); if(entry) { NpDelListenerEntry* e = entry->second; if (e->restrictedObjectSet) { for(PxU32 i=0; i < observableCount; i++) e->registeredObjects.erase(observables[i]); } else { PX_CHECK_AND_RETURN(false, "PxPhysics::unregisterDeletionListenerObjects: deletion listener is not configured to receive events from specific objects."); } } else { PX_CHECK_AND_RETURN(false, "PxPhysics::unregisterDeletionListenerObjects: deletion listener has to be registered in PxPhysics first."); } } void NpPhysics::notifyDeletionListeners(const PxBase* base, void* userData, PxDeletionEventFlag::Enum deletionEvent) { // we don't protect the check for whether there are any listeners, because we don't want to take a hit in the // common case where there are no listeners. Note the API comments here, that users should not register or // unregister deletion listeners while deletions are occurring if(mDeletionListenersExist) { PxMutex::ScopedLock lock(mDeletionListenerMutex); const DeletionListenerMap::Entry* delListenerEntries = mDeletionListenerMap.getEntries(); const PxU32 delListenerEntryCount = mDeletionListenerMap.size(); for(PxU32 i=0; i < delListenerEntryCount; i++) { const NpDelListenerEntry* entry = delListenerEntries[i].second; if (entry->flags & deletionEvent) { if (entry->restrictedObjectSet) { if (entry->registeredObjects.contains(base)) delListenerEntries[i].first->onRelease(base, userData, deletionEvent); } else delListenerEntries[i].first->onRelease(base, userData, deletionEvent); } } } } #if PX_SUPPORT_OMNI_PVD void NpPhysics::OmniPvdListener::onObjectAdd(const PxBase* object) { ::OmniPvdPxSampler::getInstance()->onObjectAdd(*object); } void NpPhysics::OmniPvdListener::onObjectRemove(const PxBase* object) { ::OmniPvdPxSampler::getInstance()->onObjectRemove(*object); } #endif /////////////////////////////////////////////////////////////////////////////// const PxTolerancesScale& NpPhysics::getTolerancesScale() const { return mPhysics.getTolerancesScale(); } PxFoundation& NpPhysics::getFoundation() { return mFoundation; } PxPhysics& PxGetPhysics() { return NpPhysics::getInstance(); } PxPhysics* PxCreatePhysics(PxU32 version, PxFoundation& foundation, const physx::PxTolerancesScale& scale, bool trackOutstandingAllocations, PxPvd* pvd, PxOmniPvd* omniPvd) { return NpPhysics::createInstance(version, foundation, scale, trackOutstandingAllocations, static_cast<pvdsdk::PsPvd*>(pvd), omniPvd); } void PxAddCollectionToPhysics(const PxCollection& collection) { NpFactory& factory = NpFactory::getInstance(); const Cm::Collection& c = static_cast<const Cm::Collection&>(collection); factory.addCollection(c); }
44,227
C++
35.918197
345
0.749384
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpCheck.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 "NpCheck.h" #include "NpScene.h" using namespace physx; NpReadCheck::NpReadCheck(const NpScene* scene, const char* functionName) : mScene(scene), mName(functionName), mErrorCount(0) { if(mScene) { if(!mScene->startRead()) { if(mScene->getScScene().getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "An API read call (%s) was made from thread %d but PxScene::lockRead() was not called first, note that " "when PxSceneFlag::eREQUIRE_RW_LOCK is enabled all API reads and writes must be " "wrapped in the appropriate locks.", mName, PxU32(PxThread::getId())); } else { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Overlapping API read and write call detected during %s from thread %d! Note that read operations to " "the SDK must not be overlapped with write calls, else the resulting behavior is undefined.", mName, PxU32(PxThread::getId())); } } // Record the NpScene read/write error counter which is // incremented any time a NpScene::startWrite/startRead fails // (see destructor for additional error checking based on this count) mErrorCount = mScene->getReadWriteErrorCount(); } } NpReadCheck::~NpReadCheck() { if(mScene) { // By checking if the NpScene::mConcurrentErrorCount has been incremented // we can detect if an erroneous read/write was performed during // this objects lifetime. In this case we also print this function's // details so that the user can see which two API calls overlapped if(mScene->getReadWriteErrorCount() != mErrorCount && !(mScene->getScScene().getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Leaving %s on thread %d, an API overlapping write on another thread was detected.", mName, PxU32(PxThread::getId())); } mScene->stopRead(); } } NpWriteCheck::NpWriteCheck(NpScene* scene, const char* functionName, bool allowReentry) : mScene(scene), mName(functionName), mAllowReentry(allowReentry), mErrorCount(0) { if(mScene) { switch(mScene->startWrite(mAllowReentry)) { case NpScene::StartWriteResult::eOK: break; case NpScene::StartWriteResult::eNO_LOCK: PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "An API write call (%s) was made from thread %d but PxScene::lockWrite() was not called first, note that " "when PxSceneFlag::eREQUIRE_RW_LOCK is enabled all API reads and writes must be " "wrapped in the appropriate locks.", mName, PxU32(PxThread::getId())); break; case NpScene::StartWriteResult::eRACE_DETECTED: PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Concurrent API write call or overlapping API read and write call detected during %s from thread %d! " "Note that write operations to the SDK must be sequential, i.e., no overlap with " "other write or read calls, else the resulting behavior is undefined. " "Also note that API writes during a callback function are not permitted.", mName, PxU32(PxThread::getId())); break; case NpScene::StartWriteResult::eIN_FETCHRESULTS: PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Illegal write call detected in %s from thread %d during split fetchResults! " "Note that write operations to the SDK are not permitted between the start of fetchResultsStart() and end of fetchResultsFinish(). " "Behavior will be undefined. ", mName, PxU32(PxThread::getId())); break; } // Record the NpScene read/write error counter which is // incremented any time a NpScene::startWrite/startRead fails // (see destructor for additional error checking based on this count) mErrorCount = mScene->getReadWriteErrorCount(); } } NpWriteCheck::~NpWriteCheck() { if(mScene) { // By checking if the NpScene::mConcurrentErrorCount has been incremented // we can detect if an erroneous read/write was performed during // this objects lifetime. In this case we also print this function's // details so that the user can see which two API calls overlapped if(mScene->getReadWriteErrorCount() != mErrorCount && !(mScene->getScScene().getFlags() & PxSceneFlag::eREQUIRE_RW_LOCK)) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Leaving %s on thread %d, an overlapping API read or write by another thread was detected.", mName, PxU32(PxThread::getId())); } mScene->stopWrite(mAllowReentry); } }
6,191
C++
45.208955
169
0.737684
NVIDIA-Omniverse/PhysX/physx/source/physx/src/windows/NpWindowsDelayLoadHook.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/windows/PxWindowsDelayLoadHook.h" #include "foundation/windows/PxWindowsInclude.h" #include "windows/CmWindowsLoadLibrary.h" namespace physx { static const PxDelayLoadHook* gPhysXDelayLoadHook = NULL; void PxSetPhysXDelayLoadHook(const PxDelayLoadHook* hook) { gPhysXDelayLoadHook = hook; } } // delay loading is enabled only for non static configuration #if !defined PX_PHYSX_STATIC_LIB // Prior to Visual Studio 2015 Update 3, these hooks were non-const. #define DELAYIMP_INSECURE_WRITABLE_HOOKS #include <delayimp.h> using namespace physx; #pragma comment(lib, "delayimp") FARPROC WINAPI physxDelayHook(unsigned dliNotify, PDelayLoadInfo pdli) { switch (dliNotify) { case dliStartProcessing : break; case dliNotePreLoadLibrary : { return Cm::physXCommonDliNotePreLoadLibrary(pdli->szDll,gPhysXDelayLoadHook); } break; case dliNotePreGetProcAddress : break; case dliFailLoadLib : break; case dliFailGetProc : break; case dliNoteEndProcessing : break; default : return NULL; } return NULL; } PfnDliHook __pfnDliNotifyHook2 = physxDelayHook; #endif
2,821
C++
30.355555
80
0.76604
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/NpOmniPvd.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 "NpOmniPvd.h" #if PX_SUPPORT_OMNI_PVD #include "OmniPvdPxSampler.h" #include "OmniPvdLoader.h" #include "OmniPvdFileWriteStream.h" #endif #include "foundation/PxUserAllocated.h" physx::PxU32 physx::NpOmniPvd::mRefCount = 0; physx::NpOmniPvd* physx::NpOmniPvd::mInstance = NULL; namespace physx { NpOmniPvd::NpOmniPvd() : mLoader (NULL), mFileWriteStream(NULL), mWriter (NULL), mPhysXSampler (NULL) { } NpOmniPvd::~NpOmniPvd() { #if PX_SUPPORT_OMNI_PVD if (mFileWriteStream) { mFileWriteStream->closeStream(); mLoader->mDestroyOmniPvdFileWriteStream(*mFileWriteStream); mFileWriteStream = NULL; } if (mWriter) { mLoader->mDestroyOmniPvdWriter(*mWriter); mWriter = NULL; } if (mLoader) { mLoader->~OmniPvdLoader(); PX_FREE(mLoader); mLoader = NULL; } #endif } void NpOmniPvd::destroyInstance() { PX_ASSERT(mInstance != NULL); if (mInstance->mRefCount == 1) { mInstance->~NpOmniPvd(); PX_FREE(mInstance); mInstance = NULL; } } // Called once by physx::PxOmniPvd* PxCreateOmniPvd(...) // Called once by NpPhysics::NpPhysics(...) void NpOmniPvd::incRefCount() { PX_ASSERT(mInstance != NULL); NpOmniPvd::mRefCount++; } // Called once by the Physics destructor in NpPhysics::~NpPhysics(...) void NpOmniPvd::decRefCount() { PX_ASSERT(mInstance != NULL); if (NpOmniPvd::mRefCount > 0) { NpOmniPvd::mRefCount--; } } void NpOmniPvd::release() { NpOmniPvd::destroyInstance(); } bool NpOmniPvd::initOmniPvd() { #if PX_SUPPORT_OMNI_PVD if (mLoader) { return true; } mLoader = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(OmniPvdLoader), "OmniPvdLoader"), OmniPvdLoader)(); if (!mLoader) { return false; } bool success; #if PX_WIN64 success = mLoader->loadOmniPvd("PVDRuntime_64.dll"); #else success = mLoader->loadOmniPvd("libPVDRuntime_64.so"); #endif return success; #else return true; #endif } OmniPvdWriter* NpOmniPvd::getWriter() { return blockingWriterLoad(); } OmniPvdWriter* NpOmniPvd::blockingWriterLoad() { #if PX_SUPPORT_OMNI_PVD PxMutex::ScopedLock lock(mWriterLoadMutex); if (mWriter) { return mWriter; } if (mLoader == NULL) { return NULL; } mWriter = mLoader->mCreateOmniPvdWriter(); return mWriter; #else return NULL; #endif } OmniPvdWriter* NpOmniPvd::acquireExclusiveWriterAccess() { #if PX_SUPPORT_OMNI_PVD mMutex.lock(); return blockingWriterLoad(); #else return NULL; #endif } void NpOmniPvd::releaseExclusiveWriterAccess() { #if PX_SUPPORT_OMNI_PVD mMutex.unlock(); #endif } OmniPvdFileWriteStream* NpOmniPvd::getFileWriteStream() { #if PX_SUPPORT_OMNI_PVD if (mFileWriteStream) { return mFileWriteStream; } if (mLoader == NULL) { return NULL; } mFileWriteStream = mLoader->mCreateOmniPvdFileWriteStream(); return mFileWriteStream; #else return NULL; #endif } bool NpOmniPvd::startSampling() { #if PX_SUPPORT_OMNI_PVD if (mPhysXSampler) { mPhysXSampler->startSampling(); return true; } return false; #else return false; #endif } } physx::PxOmniPvd* PxCreateOmniPvd(physx::PxFoundation& foundation) { PX_UNUSED(foundation); #if PX_SUPPORT_OMNI_PVD if (physx::NpOmniPvd::mInstance) { // No need to call this function again //foundation.getErrorCallback() return physx::NpOmniPvd::mInstance; } physx::NpOmniPvd::mInstance = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(physx::NpOmniPvd), "NpOmniPvd"), physx::NpOmniPvd)(); if (physx::NpOmniPvd::mInstance) { if (physx::NpOmniPvd::mInstance->initOmniPvd()) { physx::NpOmniPvd::mRefCount = 1; // Sets the reference counter to exactly 1 return physx::NpOmniPvd::mInstance; } else { physx::NpOmniPvd::mInstance->~NpOmniPvd(); PX_FREE(physx::NpOmniPvd::mInstance); physx::NpOmniPvd::mInstance = NULL; physx::NpOmniPvd::mRefCount = 0; return NULL; } } else { return NULL; } #else return NULL; #endif }
5,663
C++
21.83871
117
0.708105
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/NpOmniPvdRegistrationData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef NP_OMNI_PVD_REGISTRATION_DATA_H #define NP_OMNI_PVD_REGISTRATION_DATA_H #if PX_SUPPORT_OMNI_PVD #include "OmniPvdWriter.h" #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec3.h" #include "foundation/PxTransform.h" #include "foundation/PxBounds3.h" #include "PxSceneDesc.h" // for PxgDynamicsMemoryConfig #include "PxActor.h"// for PxDominanceGroup #include "PxClient.h" // for PxClientID #include "PxMaterial.h" // for PxMaterialFlags, PxCombineMode #include "PxRigidBody.h" // for PxRigidBodyFlags #include "PxRigidDynamic.h" // for PxRigidDynamicLockFlags #include "PxShape.h" // for PxShapeFlags #include "solver/PxSolverDefs.h" // for PxArticulationMotion #include "geometry/PxCustomGeometry.h" // for PxCustomGeometry::Callbacks namespace physx { class PxAggregate; class PxArticulationJointReducedCoordinate; class PxArticulationReducedCoordinate; class PxBaseMaterial; class PxBoxGeometry; class PxBVH; class PxCapsuleGeometry; class PxConvexMesh; class PxConvexMeshGeometry; class PxFEMClothMaterial; class PxFEMSoftBodyMaterial; class PxFLIPMaterial; class PxGeometry; class PxHeightField; class PxHeightFieldGeometry; class PxMPMMaterial; class PxPBDMaterial; class PxPhysics; class PxPlaneGeometry; class PxRigidActor; class PxRigidStatic; class PxScene; class PxSoftBodyMesh; class PxSphereGeometry; class PxTetrahedronMesh; class PxTetrahedronMeshGeometry; class PxTolerancesScale; class PxTriangleMesh; class PxTriangleMeshGeometry; struct OmniPvdPxCoreRegistrationData { void registerData(OmniPvdWriter&); // auto-generate members and setter methods from object definition file #include "omnipvd/CmOmniPvdAutoGenCreateRegistrationStruct.h" #include "OmniPvdTypes.h" #include "omnipvd/CmOmniPvdAutoGenClearDefines.h" }; } #endif // PX_SUPPORT_OMNI_PVD #endif // NP_OMNI_PVD_REGISTRATION_DATA_H
3,554
C
33.852941
74
0.791221
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/OmniPvdChunkAlloc.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 "OmniPvdChunkAlloc.h" #include <string.h> // memcpy #include "foundation/PxAllocator.h" OmniPvdChunkElement::OmniPvdChunkElement() { } OmniPvdChunkElement::~OmniPvdChunkElement() { } OmniPvdChunk::OmniPvdChunk() : mData (NULL), mNbrBytesAllocated (0), mNbrBytesFree (0), mBytePtr (NULL), mNextChunk (NULL) { } OmniPvdChunk::~OmniPvdChunk() { PX_FREE(mData); } void OmniPvdChunk::resetChunk(int nbrBytes) { if (nbrBytes>mNbrBytesAllocated) { PX_FREE(mData); mData = static_cast<unsigned char*>(PX_ALLOC(sizeof(unsigned char)*(nbrBytes), "m_data")); mNbrBytesAllocated=nbrBytes; } mNbrBytesFree=mNbrBytesAllocated; mBytePtr=mData; } int OmniPvdChunk::nbrBytesUSed() { return mNbrBytesAllocated-mNbrBytesFree; } OmniPvdChunkList::OmniPvdChunkList() { resetList(); } OmniPvdChunkList::~OmniPvdChunkList() { } void OmniPvdChunkList::resetList() { mFirstChunk=0; mLastChunk=0; mNbrChunks=0; } OmniPvdChunk* OmniPvdChunkList::removeFirst() { if (mFirstChunk) { OmniPvdChunk* chunk=mFirstChunk; mFirstChunk=mFirstChunk->mNextChunk; if (!mFirstChunk) { // Did we remove the last one? mLastChunk=NULL; } chunk->mNextChunk=NULL; mNbrChunks--; return chunk; } else { return 0; } } void OmniPvdChunkList::appendList(OmniPvdChunkList* list) { if (!list) return; if (list->mNbrChunks==0) return; if (list->mFirstChunk==NULL) return; if (mFirstChunk) { mLastChunk->mNextChunk=list->mFirstChunk; mLastChunk=list->mLastChunk; } else { mFirstChunk=list->mFirstChunk; mLastChunk=list->mLastChunk; } mNbrChunks+=list->mNbrChunks; list->resetList(); } void OmniPvdChunkList::appendChunk(OmniPvdChunk* chunk) { if (!chunk) return; if (mFirstChunk) { mLastChunk->mNextChunk=chunk; mLastChunk=chunk; } else { mFirstChunk=chunk; mLastChunk=chunk; } chunk->mNextChunk=NULL; mNbrChunks++; } OmniPvdChunkPool::OmniPvdChunkPool() { mNbrAllocatedChunks = 0; mChunkSize = 65536; // random default value :-) } OmniPvdChunkPool::~OmniPvdChunkPool() { OmniPvdChunk* chunk=mFreeChunks.mFirstChunk; while (chunk) { OmniPvdChunk* nextChunk=chunk->mNextChunk; PX_DELETE(chunk); chunk=nextChunk; } mNbrAllocatedChunks = 0; } void OmniPvdChunkPool::setChunkSize(int chunkSize) { if (mNbrAllocatedChunks > 0) return; // makes it impossible to re-set the size of a chunk once a chunk was already allocated mChunkSize = chunkSize; } OmniPvdChunk* OmniPvdChunkPool::getChunk() { OmniPvdChunk* chunk=mFreeChunks.removeFirst(); if (!chunk) { chunk= PX_NEW(OmniPvdChunk); mNbrAllocatedChunks++; } chunk->resetChunk(mChunkSize); return chunk; } OmniPvdChunkByteAllocator::OmniPvdChunkByteAllocator() { mPool = NULL; } OmniPvdChunkByteAllocator::~OmniPvdChunkByteAllocator() { freeChunks(); } OmniPvdChunkElement* OmniPvdChunkByteAllocator::allocChunkElement(int totalStructSize) { return reinterpret_cast<OmniPvdChunkElement*>(allocBytes(totalStructSize)); } void OmniPvdChunkByteAllocator::setPool(OmniPvdChunkPool* pool) { mPool = pool; } unsigned char* OmniPvdChunkByteAllocator::allocBytes(int nbrBytes) { if (!mPool) return 0; if (mPool->mChunkSize < nbrBytes) { return 0; // impossible request! } if (mUsedChunks.mLastChunk) { // If a chunk is free if (mUsedChunks.mLastChunk->mNbrBytesFree< nbrBytes) { // The last chunk has not enough space, so get a fresh one from the pool mUsedChunks.appendChunk(mPool->getChunk()); } } else { // No last chunk is available, allocate a fresh one mUsedChunks.appendChunk(mPool->getChunk()); } // Use the last chunk to allocate the data necessary unsigned char* pSubChunk=mUsedChunks.mLastChunk->mBytePtr; mUsedChunks.mLastChunk->mNbrBytesFree-= nbrBytes; mUsedChunks.mLastChunk->mBytePtr+= nbrBytes; return pSubChunk; } void OmniPvdChunkByteAllocator::freeChunks() { if (!mPool) return; mPool->mFreeChunks.appendList(&mUsedChunks); }
5,619
C++
23.541485
125
0.745862
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/OmniPvdPxSampler.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. #if PX_SUPPORT_OMNI_PVD #include <stdio.h> #include "foundation/PxPreprocessor.h" #include "foundation/PxAllocator.h" #include "ScIterators.h" #include "omnipvd/NpOmniPvd.h" #include "OmniPvdPxSampler.h" #include "OmniPvdWriteStream.h" #include "NpOmniPvdSetData.h" #include "NpPhysics.h" #include "NpScene.h" #include "NpAggregate.h" #include "NpRigidStatic.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationLink.h" using namespace physx; class OmniPvdStreamContainer { public: OmniPvdStreamContainer(); ~OmniPvdStreamContainer(); bool initOmniPvd(); void registerClasses(); void setOmniPvdInstance(NpOmniPvd* omniPvdInstance); NpOmniPvd* mOmniPvdInstance; physx::PxMutex mMutex; OmniPvdPxCoreRegistrationData mRegistrationData; bool mClassesRegistered; }; class OmniPvdSamplerInternals : public physx::PxUserAllocated { public: OmniPvdStreamContainer mPvdStream; bool addSharedMeshIfNotSeen(const void* geom, OmniPvdSharedMeshEnum geomEnum); // Returns true if the Geom was not yet seen and added physx::PxMutex mSampleMutex; bool mIsSampling; physx::PxMutex mSampledScenesMutex; physx::PxHashMap<physx::NpScene*, OmniPvdPxScene*> mSampledScenes; physx::PxMutex mSharedGeomsMutex; physx::PxHashMap<const void*, OmniPvdSharedMeshEnum> mSharedMeshesMap; }; OmniPvdSamplerInternals * samplerInternals = NULL; class OmniPvdPxScene : public physx::PxUserAllocated { public: OmniPvdPxScene() : mFrameId(0) {} ~OmniPvdPxScene() {} void sampleScene() { mFrameId++; samplerInternals->mPvdStream.mOmniPvdInstance->getWriter()->startFrame(OMNI_PVD_CONTEXT_HANDLE, mFrameId); } physx::PxU64 mFrameId; }; OmniPvdStreamContainer::OmniPvdStreamContainer() { physx::PxMutex::ScopedLock myLock(mMutex); mClassesRegistered = false; mOmniPvdInstance = NULL; } OmniPvdStreamContainer::~OmniPvdStreamContainer() { } void OmniPvdStreamContainer::setOmniPvdInstance(NpOmniPvd* omniPvdInstance) { mOmniPvdInstance = omniPvdInstance; } bool OmniPvdStreamContainer::initOmniPvd() { physx::PxMutex::ScopedLock myLock(mMutex); registerClasses(); PxPhysics& physicsRef = static_cast<PxPhysics&>(NpPhysics::getInstance()); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPhysics, physicsRef); const physx::PxTolerancesScale& tolScale = physicsRef.getTolerancesScale(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPhysics, tolerancesScale, physicsRef, tolScale); OMNI_PVD_WRITE_SCOPE_END return true; } void OmniPvdStreamContainer::registerClasses() { if (mClassesRegistered) return; OmniPvdWriter* writer = mOmniPvdInstance->acquireExclusiveWriterAccess(); if (writer) { mRegistrationData.registerData(*writer); mClassesRegistered = true; } mOmniPvdInstance->releaseExclusiveWriterAccess(); } int streamStringLength(const char* name) { #if PX_SUPPORT_OMNI_PVD if (NpPhysics::getInstance().mOmniPvdSampler == NULL) { return 0; } if (name == NULL) { return 0; } int len = static_cast<int>(strlen(name)); if (len > 0) { return len; } else { return 0; } #else return 0; #endif } void streamActorName(const physx::PxActor & a, const char* name) { #if PX_SUPPORT_OMNI_PVD int strLen = streamStringLength(name); if (strLen) { OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxActor, name, a, name, strLen + 1); // copies over the trailing zero too } #endif } void streamSceneName(const physx::PxScene & s, const char* name) { #if PX_SUPPORT_OMNI_PVD int strLen = streamStringLength(name); if (strLen) { OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxScene, name, s, name, strLen + 1); // copies over the trailing zero too } #endif } void streamSphereGeometry(const physx::PxSphereGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphereGeometry, g); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphereGeometry, radius, g, g.radius); OMNI_PVD_WRITE_SCOPE_END } void streamCapsuleGeometry(const physx::PxCapsuleGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCapsuleGeometry, g); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCapsuleGeometry, halfHeight, g, g.halfHeight); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCapsuleGeometry, radius, g, g.radius); OMNI_PVD_WRITE_SCOPE_END } void streamBoxGeometry(const physx::PxBoxGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxBoxGeometry, g); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxBoxGeometry, halfExtents, g, g.halfExtents); OMNI_PVD_WRITE_SCOPE_END } void streamPlaneGeometry(const physx::PxPlaneGeometry& g) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxPlaneGeometry, g); } void streamCustomGeometry(const physx::PxCustomGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometry, g); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometry, callbacks, g, g.callbacks); OMNI_PVD_WRITE_SCOPE_END } void streamConvexMesh(const physx::PxConvexMesh& mesh) { if (samplerInternals->addSharedMeshIfNotSeen(&mesh, OmniPvdSharedMeshEnum::eOmniPvdConvexMesh)) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxConvexMesh, mesh); const PxU32 nbPolys = mesh.getNbPolygons(); const PxU8* polygons = mesh.getIndexBuffer(); const PxVec3* verts = mesh.getVertices(); const PxU32 nbrVerts = mesh.getNbVertices(); PxU32 totalTris = 0; for (PxU32 i = 0; i < nbPolys; i++) { physx::PxHullPolygon data; mesh.getPolygonData(i, data); totalTris += data.mNbVerts - 2; } float* tmpVerts = (float*)PX_ALLOC(sizeof(float)*(nbrVerts * 3), "tmpVerts"); PxU32* tmpIndices = (PxU32*)PX_ALLOC(sizeof(PxU32)*(totalTris * 3), "tmpIndices"); //TODO: this copy is useless PxU32 vertIndex = 0; for (PxU32 v = 0; v < nbrVerts; v++) { tmpVerts[vertIndex + 0] = verts[v].x; tmpVerts[vertIndex + 1] = verts[v].y; tmpVerts[vertIndex + 2] = verts[v].z; vertIndex += 3; } PxU32 triIndex = 0; for (PxU32 p = 0; p < nbPolys; p++) { physx::PxHullPolygon data; mesh.getPolygonData(p, data); PxU32 nbTris = data.mNbVerts - 2; const PxU32 vref0 = polygons[data.mIndexBase + 0 + 0]; for (PxU32 t = 0; t < nbTris; t++) { const PxU32 vref1 = polygons[data.mIndexBase + t + 1]; const PxU32 vref2 = polygons[data.mIndexBase + t + 2]; tmpIndices[triIndex + 0] = vref0; tmpIndices[triIndex + 1] = vref1; tmpIndices[triIndex + 2] = vref2; triIndex += 3; } } OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxConvexMesh, verts, mesh, tmpVerts, 3 * nbrVerts); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxConvexMesh, tris, mesh, tmpIndices, 3 * totalTris); PX_FREE(tmpVerts); PX_FREE(tmpIndices); OMNI_PVD_WRITE_SCOPE_END } } void streamConvexMeshGeometry(const physx::PxConvexMeshGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxConvexMeshGeometry, g); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxConvexMeshGeometry, scale, g, g.scale.scale); streamConvexMesh(*g.convexMesh); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxConvexMeshGeometry, convexMesh, g, g.convexMesh); OMNI_PVD_WRITE_SCOPE_END } void streamHeightField(const physx::PxHeightField& hf) { if (samplerInternals->addSharedMeshIfNotSeen(&hf, OmniPvdSharedMeshEnum::eOmniPvdHeightField)) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxHeightField, hf); const PxU32 nbCols = hf.getNbColumns(); const PxU32 nbRows = hf.getNbRows(); const PxU32 nbVerts = nbRows * nbCols; const PxU32 nbFaces = (nbCols - 1) * (nbRows - 1) * 2; physx::PxHeightFieldSample* sampleBuffer = (physx::PxHeightFieldSample*)PX_ALLOC(sizeof(physx::PxHeightFieldSample)*(nbVerts), "sampleBuffer"); hf.saveCells(sampleBuffer, nbVerts * sizeof(physx::PxHeightFieldSample)); //TODO: are the copies necessary? float* tmpVerts = (float*)PX_ALLOC(sizeof(float)*(nbVerts * 3), "tmpVerts"); PxU32* tmpIndices = (PxU32*)PX_ALLOC(sizeof(PxU32)*(nbFaces * 3), "tmpIndices"); for (PxU32 i = 0; i < nbRows; i++) { for (PxU32 j = 0; j < nbCols; j++) { const float x = PxReal(i);// *rs; const float y = PxReal(sampleBuffer[j + (i*nbCols)].height);// *hs; const float z = PxReal(j);// *cs; const PxU32 vertexIndex = 3 * (i * nbCols + j); float* vert = &tmpVerts[vertexIndex]; vert[0] = x; vert[1] = y; vert[2] = z; } } for (PxU32 i = 0; i < (nbCols - 1); ++i) { for (PxU32 j = 0; j < (nbRows - 1); ++j) { PxU8 tessFlag = sampleBuffer[i + j * nbCols].tessFlag(); PxU32 i0 = j * nbCols + i; PxU32 i1 = j * nbCols + i + 1; PxU32 i2 = (j + 1) * nbCols + i; PxU32 i3 = (j + 1) * nbCols + i + 1; // i2---i3 // | | // | | // i0---i1 // this is really a corner vertex index, not triangle index PxU32 mat0 = hf.getTriangleMaterialIndex((j*nbCols + i) * 2); PxU32 mat1 = hf.getTriangleMaterialIndex((j*nbCols + i) * 2 + 1); bool hole0 = (mat0 == PxHeightFieldMaterial::eHOLE); bool hole1 = (mat1 == PxHeightFieldMaterial::eHOLE); // first triangle tmpIndices[6 * (i * (nbRows - 1) + j) + 0] = hole0 ? i0 : i2; // duplicate i0 to make a hole tmpIndices[6 * (i * (nbRows - 1) + j) + 1] = i0; tmpIndices[6 * (i * (nbRows - 1) + j) + 2] = tessFlag ? i3 : i1; // second triangle tmpIndices[6 * (i * (nbRows - 1) + j) + 3] = hole1 ? i1 : i3; // duplicate i1 to make a hole tmpIndices[6 * (i * (nbRows - 1) + j) + 4] = tessFlag ? i0 : i2; tmpIndices[6 * (i * (nbRows - 1) + j) + 5] = i1; } } PX_FREE(sampleBuffer); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxHeightField, verts, hf, tmpVerts, 3 * nbVerts); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxHeightField, tris, hf, tmpIndices, 3 * nbFaces); PX_FREE(tmpVerts); PX_FREE(tmpIndices); OMNI_PVD_WRITE_SCOPE_END } } void streamHeightFieldGeometry(const physx::PxHeightFieldGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxHeightFieldGeometry, g); PxVec3 vertScale(g.rowScale, g.heightScale, g.columnScale); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxHeightFieldGeometry, scale, g, vertScale); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxHeightFieldGeometry, heightField, g, g.heightField); OMNI_PVD_WRITE_SCOPE_END } void streamActorAttributes(const physx::PxActor& actor) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, flags, actor, actor.getActorFlags()); streamActorName(actor, actor.getName()); // Should we stream the worldBounds if the actor is not part of a Scene yet? OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, worldBounds, actor, actor.getWorldBounds()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, dominance, actor, actor.getDominanceGroup()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, ownerClient, actor, actor.getOwnerClient()) OMNI_PVD_WRITE_SCOPE_END } void streamRigidActorAttributes(const PxRigidActor &ra) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) if (ra.is<PxArticulationLink>()) { const PxArticulationLink& link = static_cast<const PxArticulationLink&>(ra); PxTransform TArtLinkLocal; PxArticulationJointReducedCoordinate* joint = link.getInboundJoint(); if (joint) { PxArticulationLink& parentLink = joint->getParentArticulationLink(); // TGlobal = TFatherGlobal * TLocal // Inv(TFatherGlobal)* TGlobal = Inv(TFatherGlobal)*TFatherGlobal * TLocal // Inv(TFatherGlobal)* TGlobal = TLocal // TLocal = Inv(TFatherGlobal) * TGlobal //physx::PxTransform TParentGlobal = pxArticulationParentLink->getGlobalPose(); PxTransform TParentGlobalInv = parentLink.getGlobalPose().getInverse(); PxTransform TArtLinkGlobal = link.getGlobalPose(); // PT:: tag: scalar transform*transform TArtLinkLocal = TParentGlobalInv * TArtLinkGlobal; } else { TArtLinkLocal = link.getGlobalPose(); } OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, ra, TArtLinkLocal.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, ra, TArtLinkLocal.q) } else { PxTransform t = ra.getGlobalPose(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, ra, t.p); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, ra, t.q); } // Stream shapes too const int nbrShapes = ra.getNbShapes(); for (int s = 0; s < nbrShapes; s++) { PxShape* shape[1]; ra.getShapes(shape, 1, s); OMNI_PVD_ADD_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, shapes, ra, *shape[0]) } OMNI_PVD_WRITE_SCOPE_END } void streamRigidBodyAttributes(const physx::PxRigidBody& rigidBody) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, cMassLocalPose, rigidBody, rigidBody.getCMassLocalPose()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, mass, rigidBody, rigidBody.getMass()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, massSpaceInertiaTensor, rigidBody, rigidBody.getMassSpaceInertiaTensor()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearDamping, rigidBody, rigidBody.getLinearDamping()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularDamping, rigidBody, rigidBody.getAngularDamping()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, rigidBody, rigidBody.getLinearVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, rigidBody, rigidBody.getAngularVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxLinearVelocity, rigidBody, rigidBody.getMaxLinearVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxAngularVelocity, rigidBody, rigidBody.getMaxAngularVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, rigidBody, rigidBody.getRigidBodyFlags()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, minAdvancedCCDCoefficient, rigidBody, rigidBody.getMinCCDAdvanceCoefficient()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxDepenetrationVelocity, rigidBody, rigidBody.getMaxDepenetrationVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxContactImpulse, rigidBody, rigidBody.getMaxContactImpulse()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, contactSlopCoefficient, rigidBody, rigidBody.getContactSlopCoefficient()); OMNI_PVD_WRITE_SCOPE_END } void streamRigidDynamicAttributes(const physx::PxRigidDynamic& rd) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) if (rd.getScene()) { OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, isSleeping, rd, rd.isSleeping()); } OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, sleepThreshold, rd, rd.getSleepThreshold()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, stabilizationThreshold, rd, rd.getStabilizationThreshold()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, rigidDynamicLockFlags, rd, rd.getRigidDynamicLockFlags()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, wakeCounter, rd, rd.getWakeCounter()); PxU32 positionIters, velocityIters; rd.getSolverIterationCounts(positionIters, velocityIters); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, positionIterations, rd, positionIters); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, velocityIterations, rd, velocityIters); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, contactReportThreshold, rd, rd.getContactReportThreshold()); OMNI_PVD_WRITE_SCOPE_END } void streamRigidDynamic(const physx::PxRigidDynamic& rd) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxActor& a = rd; PX_ASSERT(&a == &rd); // if this changes, we would have to cast in a way such that the addresses are the same OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, rd); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, type, a, PxActorType::eRIGID_DYNAMIC); OMNI_PVD_WRITE_SCOPE_END streamActorAttributes(rd); streamRigidActorAttributes(rd); streamRigidBodyAttributes(rd); streamRigidDynamicAttributes(rd); } void streamRigidStatic(const physx::PxRigidStatic& rs) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxActor& a = rs; PX_ASSERT(&a == &rs); // if this changes, we would have to cast in a way such that the addresses are the same OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidStatic, rs); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, type, a, PxActorType::eRIGID_STATIC); OMNI_PVD_WRITE_SCOPE_END streamActorAttributes(rs); streamRigidActorAttributes(rs); } void streamArticulationJoint(const physx::PxArticulationJointReducedCoordinate& jointRef) { const PxU32 degreesOfFreedom = PxArticulationAxis::eCOUNT; // make sure size matches the size used in the PVD description PX_ASSERT(sizeof(PxArticulationMotion::Enum) == getOmniPvdDataTypeSize<OmniPvdDataType::eUINT32>()); PX_ASSERT(sizeof(PxArticulationDriveType::Enum) == getOmniPvdDataTypeSize<OmniPvdDataType::eUINT32>()); PxArticulationJointType::Enum jointType = jointRef.getJointType(); const PxArticulationLink* parentPxLinkPtr = &jointRef.getParentArticulationLink(); const PxArticulationLink* childPxLinkPtr = &jointRef.getChildArticulationLink(); PxArticulationMotion::Enum motions[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) motions[ax] = jointRef.getMotion(static_cast<PxArticulationAxis::Enum>(ax)); PxReal armatures[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) armatures[ax] = jointRef.getArmature(static_cast<PxArticulationAxis::Enum>(ax)); PxReal coefficient = jointRef.getFrictionCoefficient(); PxReal maxJointV = jointRef.getMaxJointVelocity(); PxReal positions[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) positions[ax] = jointRef.getJointPosition(static_cast<PxArticulationAxis::Enum>(ax)); PxReal velocitys[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) velocitys[ax] = jointRef.getJointVelocity(static_cast<PxArticulationAxis::Enum>(ax)); const char* concreteTypeName = jointRef.getConcreteTypeName(); PxU32 concreteTypeNameLen = PxU32(strlen(concreteTypeName)) + 1; PxReal lowlimits[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) lowlimits[ax] = jointRef.getLimitParams(static_cast<PxArticulationAxis::Enum>(ax)).low; PxReal highlimits[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) highlimits[ax] = jointRef.getLimitParams(static_cast<PxArticulationAxis::Enum>(ax)).high; PxReal stiffnesss[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) stiffnesss[ax] = jointRef.getDriveParams(static_cast<PxArticulationAxis::Enum>(ax)).stiffness; PxReal dampings[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) dampings[ax] = jointRef.getDriveParams(static_cast<PxArticulationAxis::Enum>(ax)).damping; PxReal maxforces[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) maxforces[ax] = jointRef.getDriveParams(static_cast<PxArticulationAxis::Enum>(ax)).maxForce; PxArticulationDriveType::Enum drivetypes[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) drivetypes[ax] = jointRef.getDriveParams(static_cast<PxArticulationAxis::Enum>(ax)).driveType; PxReal drivetargets[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) drivetargets[ax] = jointRef.getDriveTarget(static_cast<PxArticulationAxis::Enum>(ax)); PxReal drivevelocitys[degreesOfFreedom]; for (PxU32 ax = 0; ax < degreesOfFreedom; ++ax) drivevelocitys[ax] = jointRef.getDriveVelocity(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointRef); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, type, jointRef, jointType); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, parentLink, jointRef, parentPxLinkPtr); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, childLink, jointRef, childPxLinkPtr); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, motion, jointRef, motions, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, armature, jointRef, armatures, degreesOfFreedom); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, frictionCoefficient, jointRef, coefficient); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, maxJointVelocity, jointRef, maxJointV); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointPosition, jointRef, positions, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointVelocity, jointRef, velocitys, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, concreteTypeName, jointRef, concreteTypeName, concreteTypeNameLen); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, limitLow, jointRef, lowlimits, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, limitHigh, jointRef, highlimits, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveStiffness, jointRef, stiffnesss, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveDamping, jointRef, dampings, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveMaxForce, jointRef, maxforces, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveType, jointRef, drivetypes, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveTarget, jointRef, drivetargets, degreesOfFreedom); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, driveVelocity, jointRef, drivevelocitys, degreesOfFreedom); OMNI_PVD_WRITE_SCOPE_END } void streamArticulationLink(const physx::PxArticulationLink& al) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxActor& a = al; PX_ASSERT(&a == &al); // if this changes, we would have to cast in a way such that the addresses are the same OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationLink, al); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, type, a, PxActorType::eARTICULATION_LINK); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationLink, articulation, al, &al.getArticulation()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationLink, CFMScale, al, al.getCfmScale()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationLink, inboundJointDOF, al, al.getInboundJointDof()); OMNI_PVD_WRITE_SCOPE_END streamActorAttributes(al); streamRigidActorAttributes(al); streamRigidBodyAttributes(al); } void streamArticulation(const physx::PxArticulationReducedCoordinate& art) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, art); PxU32 solverIterations[2]; art.getSolverIterationCounts(solverIterations[0], solverIterations[1]); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, positionIterations, art, solverIterations[0]); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, velocityIterations, art, solverIterations[1]); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, isSleeping, art, false); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, sleepThreshold, art, art.getSleepThreshold()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, stabilizationThreshold, art, art.getStabilizationThreshold()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, wakeCounter, art, art.getWakeCounter()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, maxLinearVelocity, art, art.getMaxCOMLinearVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, maxAngularVelocity, art, art.getMaxCOMAngularVelocity()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, worldBounds, art, art.getWorldBounds()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, articulationFlags, art, art.getArticulationFlags()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, dofs, art, art.getDofs()); OMNI_PVD_WRITE_SCOPE_END } void streamAggregate(const physx::PxAggregate& agg) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, agg); PxU32 actorCount = agg.getNbActors(); for (PxU32 i = 0; i < actorCount; ++i) { PxActor* a; agg.getActors(&a, 1, i); OMNI_PVD_ADD_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, actors, agg, *a); } OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, selfCollision, agg, agg.getSelfCollision()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, maxNbShapes, agg, agg.getMaxNbShapes()); PxScene* scene = static_cast<const NpAggregate&>(agg).getNpScene(); // because PxAggregate::getScene() is not marked const OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxAggregate, scene, agg, scene); OMNI_PVD_WRITE_SCOPE_END } void streamMPMMaterial(const physx::PxMPMMaterial& m) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxMPMMaterial, m); } void streamFLIPMaterial(const physx::PxFLIPMaterial& m) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxFLIPMaterial, m); } void streamPBDMaterial(const physx::PxPBDMaterial& m) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxPBDMaterial, m); } void streamFEMClothMaterial(const physx::PxFEMClothMaterial& m) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxFEMClothMaterial, m); } void streamFEMSoBoMaterial(const physx::PxFEMSoftBodyMaterial& m) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxFEMSoftBodyMaterial, m); } void streamMaterial(const physx::PxMaterial& m) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, m); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, m, m.getFlags()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, frictionCombineMode, m, m.getFrictionCombineMode()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitutionCombineMode, m, m.getRestitutionCombineMode()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, staticFriction, m, m.getStaticFriction()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, dynamicFriction, m, m.getDynamicFriction()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitution, m, m.getRestitution()); OMNI_PVD_WRITE_SCOPE_END } void streamShapeMaterials(const physx::PxShape& shape, physx::PxMaterial* const * mats, physx::PxU32 nbrMaterials) { OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxShape, materials, shape, mats, nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxFEMClothMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxFEMMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxFEMSoftBodyMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxFLIPMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxMPMMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxParticleMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShapeMaterials(const physx::PxShape& shape, physx::PxPBDMaterial* const * mats, physx::PxU32 nbrMaterials) { PX_UNUSED(shape); PX_UNUSED(mats); PX_UNUSED(nbrMaterials); } void streamShape(const physx::PxShape& shape) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, shape); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, isExclusive, shape, shape.isExclusive()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, geom, shape, &shape.getGeometry()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, contactOffset, shape, shape.getContactOffset()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, restOffset, shape, shape.getRestOffset()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, densityForFluid, shape, shape.getDensityForFluid()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, torsionalPatchRadius, shape, shape.getTorsionalPatchRadius()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, minTorsionalPatchRadius, shape, shape.getMinTorsionalPatchRadius()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, shapeFlags, shape, shape.getFlags()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, simulationFilterData, shape, shape.getSimulationFilterData()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxShape, queryFilterData, shape, shape.getQueryFilterData()); const int nbrMaterials = shape.getNbMaterials(); PxMaterial** tmpMaterials = (PxMaterial**)PX_ALLOC(sizeof(PxMaterial*) * nbrMaterials, "tmpMaterials"); physx::PxU32 nbrMats = shape.getMaterials(tmpMaterials, nbrMaterials); streamShapeMaterials(shape, tmpMaterials, nbrMats); PX_FREE(tmpMaterials); OMNI_PVD_WRITE_SCOPE_END } void streamBVH(const physx::PxBVH& bvh) { OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxBVH, bvh); } void streamSoBoMesh(const physx::PxSoftBodyMesh& mesh) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSoftBodyMesh, mesh); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSoftBodyMesh, collisionMesh, mesh, mesh.getCollisionMesh()); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSoftBodyMesh, simulationMesh, mesh, mesh.getSimulationMesh()); OMNI_PVD_WRITE_SCOPE_END } void streamTetMesh(const physx::PxTetrahedronMesh& mesh) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTetrahedronMesh, mesh); //this gets done at the bottom now const PxU32 tetrahedronCount = mesh.getNbTetrahedrons(); const PxU32 has16BitIndices = mesh.getTetrahedronMeshFlags() & physx::PxTetrahedronMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTetrahedrons(); const PxVec3* vertexBuffer = mesh.getVertices(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); //TODO: not needed to copy this const PxU32 nbrVerts = mesh.getNbVertices(); const PxU32 nbrTets = mesh.getNbTetrahedrons(); float* tmpVerts = (float*)PX_ALLOC(sizeof(float)*(nbrVerts * 3), "tmpVerts"); PxU32 vertIndex = 0; for (PxU32 v = 0; v < nbrVerts; v++) { tmpVerts[vertIndex + 0] = vertexBuffer[v].x; tmpVerts[vertIndex + 1] = vertexBuffer[v].y; tmpVerts[vertIndex + 2] = vertexBuffer[v].z; vertIndex += 3; } PxU32* tmpIndices = (PxU32*)PX_ALLOC(sizeof(PxU32)*(nbrTets * 4), "tmpIndices"); const PxU32 totalIndexCount = tetrahedronCount * 4; if (has16BitIndices) { for (PxU32 i = 0; i < totalIndexCount; ++i) { tmpIndices[i] = shortIndices[i]; } } else { for (PxU32 i = 0; i < totalIndexCount; ++i) { tmpIndices[i] = intIndices[i]; } } OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTetrahedronMesh, verts, mesh, tmpVerts, 3 * nbrVerts); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTetrahedronMesh, tets, mesh, tmpIndices, 4 * nbrTets); PX_FREE(tmpVerts); PX_FREE(tmpIndices); OMNI_PVD_WRITE_SCOPE_END } void streamTriMesh(const physx::PxTriangleMesh& mesh) { if (samplerInternals->addSharedMeshIfNotSeen(&mesh, OmniPvdSharedMeshEnum::eOmniPvdTriMesh)) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTriangleMesh, mesh); //this gets done at the bottom now const PxU32 triangleCount = mesh.getNbTriangles(); const PxU32 has16BitIndices = mesh.getTriangleMeshFlags() & physx::PxTriangleMeshFlag::e16_BIT_INDICES; const void* indexBuffer = mesh.getTriangles(); const PxVec3* vertexBuffer = mesh.getVertices(); const PxU32* intIndices = reinterpret_cast<const PxU32*>(indexBuffer); const PxU16* shortIndices = reinterpret_cast<const PxU16*>(indexBuffer); //TODO: not needed to copy this const PxU32 nbrVerts = mesh.getNbVertices(); const PxU32 nbrTris = mesh.getNbTriangles(); float* tmpVerts = (float*)PX_ALLOC(sizeof(float)*(nbrVerts * 3), "tmpVerts"); PxU32 vertIndex = 0; for (PxU32 v = 0; v < nbrVerts; v++) { tmpVerts[vertIndex + 0] = vertexBuffer[v].x; tmpVerts[vertIndex + 1] = vertexBuffer[v].y; tmpVerts[vertIndex + 2] = vertexBuffer[v].z; vertIndex += 3; } PxU32* tmpIndices = (PxU32*)PX_ALLOC(sizeof(PxU32)*(nbrTris * 3), "tmpIndices"); const PxU32 totalIndexCount = triangleCount * 3; if (has16BitIndices) { for (PxU32 i = 0; i < totalIndexCount; ++i) { tmpIndices[i] = shortIndices[i]; } } else { for (PxU32 i = 0; i < totalIndexCount; ++i) { tmpIndices[i] = intIndices[i]; } } OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTriangleMesh, verts, mesh, tmpVerts, 3 * nbrVerts); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTriangleMesh, tris, mesh, tmpIndices, 3 * nbrTris); PX_FREE(tmpVerts); PX_FREE(tmpIndices); OMNI_PVD_WRITE_SCOPE_END } } void streamTriMeshGeometry(const physx::PxTriangleMeshGeometry& g) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTriangleMeshGeometry, g); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTriangleMeshGeometry, scale, g, g.scale.scale); streamTriMesh(*g.triangleMesh); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxTriangleMeshGeometry, triangleMesh, g, g.triangleMesh); OMNI_PVD_WRITE_SCOPE_END } void OmniPvdPxSampler::streamSceneContacts(physx::NpScene& scene) { if (!isSampling()) return; PxsContactManagerOutputIterator outputIter; Sc::ContactIterator contactIter; scene.getScScene().initContactsIterator(contactIter, outputIter); Sc::ContactIterator::Pair* pair; PxU32 pairCount = 0; PxArray<PxActor*> pairsActors; PxArray<PxU32> pairsContactCounts; PxArray<PxVec3> pairsContactPoints; PxArray<PxVec3> pairsContactNormals; PxArray<PxReal> pairsContactSeparations; PxArray<PxShape*> pairsContactShapes; PxArray<PxU32> pairsContactFacesIndices; while ((pair = contactIter.getNextPair()) != NULL) { PxU32 pairContactCount = 0; Sc::Contact* contact = NULL; bool firstContact = true; while ((contact = pair->getNextContact()) != NULL) { if (firstContact) { pairsActors.pushBack(pair->getActor0()); pairsActors.pushBack(pair->getActor1()); ++pairCount; firstContact = false; } ++pairContactCount; pairsContactPoints.pushBack(contact->point); pairsContactNormals.pushBack(contact->normal); pairsContactSeparations.pushBack(contact->separation); pairsContactShapes.pushBack(contact->shape0); pairsContactShapes.pushBack(contact->shape1); pairsContactFacesIndices.pushBack(contact->faceIndex0); pairsContactFacesIndices.pushBack(contact->faceIndex1); } if (pairContactCount) { pairsContactCounts.pushBack(pairContactCount); } } if (pairCount == 0) return; OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairCount, scene, pairCount); const PxU32 actorCount = pairsActors.size(); const PxActor** actors = actorCount ? const_cast<const PxActor**>(pairsActors.begin()) : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsActors, scene, actors, actorCount); PxU32 nbContactCount = pairsContactCounts.size(); PxU32* contactCounts = nbContactCount ? pairsContactCounts.begin() : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsContactCounts, scene, contactCounts, nbContactCount); PxU32 contactPointFloatCount = pairsContactPoints.size() * 3; PxReal* contactPoints = contactPointFloatCount ? &pairsContactPoints[0].x : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsContactPoints, scene, contactPoints, contactPointFloatCount); PxU32 contactNormalFloatCount = pairsContactNormals.size() * 3; PxReal* contactNormals = contactNormalFloatCount ? &pairsContactNormals[0].x : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsContactNormals, scene, contactNormals, contactNormalFloatCount); PxU32 contactSeparationCount = pairsContactSeparations.size(); PxReal* contactSeparations = contactSeparationCount ? pairsContactSeparations.begin() : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsContactSeparations, scene, contactSeparations, contactSeparationCount); PxU32 contactShapeCount = pairsContactShapes.size(); const PxShape** contactShapes = contactShapeCount ? const_cast<const PxShape**>(pairsContactShapes.begin()) : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsContactShapes, scene, contactShapes, contactShapeCount); PxU32 contactFacesIndexCount = pairsContactFacesIndices.size(); PxU32* contactFacesIndices = contactFacesIndexCount ? pairsContactFacesIndices.begin() : NULL; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxScene, pairsContactFacesIndices, scene, contactFacesIndices, contactFacesIndexCount); OMNI_PVD_WRITE_SCOPE_END } OmniPvdPxSampler::OmniPvdPxSampler() { samplerInternals = PX_NEW(OmniPvdSamplerInternals)(); physx::PxMutex::ScopedLock myLock(samplerInternals->mSampleMutex); samplerInternals->mIsSampling = false; } OmniPvdPxSampler::~OmniPvdPxSampler() { physx::PxHashMap<physx::NpScene*, OmniPvdPxScene*>::Iterator iterScenes = samplerInternals->mSampledScenes.getIterator(); while (!iterScenes.done()) { OmniPvdPxScene* scene = iterScenes->second; PX_DELETE(scene); iterScenes++; } PX_DELETE(samplerInternals); } void OmniPvdPxSampler::startSampling() { physx::PxMutex::ScopedLock myLock(samplerInternals->mSampleMutex); if (samplerInternals->mIsSampling) { return; } if (samplerInternals->mPvdStream.initOmniPvd()) { samplerInternals->mIsSampling = true; } } bool OmniPvdPxSampler::isSampling() { if (!samplerInternals) return false; physx::PxMutex::ScopedLock myLock(samplerInternals->mSampleMutex); return samplerInternals->mIsSampling; } void OmniPvdPxSampler::setOmniPvdInstance(physx::NpOmniPvd* omniPvdInstance) { samplerInternals->mPvdStream.setOmniPvdInstance(omniPvdInstance); } void createGeometry(const physx::PxGeometry & pxGeom) { switch (pxGeom.getType()) { case physx::PxGeometryType::eSPHERE: { streamSphereGeometry((const physx::PxSphereGeometry &)pxGeom); } break; case physx::PxGeometryType::eCAPSULE: { streamCapsuleGeometry((const physx::PxCapsuleGeometry &)pxGeom); } break; case physx::PxGeometryType::eBOX: { streamBoxGeometry((const physx::PxBoxGeometry &)pxGeom); } break; case physx::PxGeometryType::eTRIANGLEMESH: { streamTriMeshGeometry((const physx::PxTriangleMeshGeometry &)pxGeom); } break; case physx::PxGeometryType::eCONVEXMESH: { streamConvexMeshGeometry((const physx::PxConvexMeshGeometry &)pxGeom); } break; case physx::PxGeometryType::eHEIGHTFIELD: { streamHeightFieldGeometry((const physx::PxHeightFieldGeometry &)pxGeom); } break; case physx::PxGeometryType::ePLANE: { streamPlaneGeometry((const physx::PxPlaneGeometry &)pxGeom); } break; case physx::PxGeometryType::eCUSTOM: { streamCustomGeometry((const physx::PxCustomGeometry &)pxGeom); } break; default: break; } } void destroyGeometry(const physx::PxGeometry& pxGeom) { switch (pxGeom.getType()) { case physx::PxGeometryType::eSPHERE: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxSphereGeometry, static_cast<const PxSphereGeometry&>(pxGeom)); } break; case physx::PxGeometryType::eCAPSULE: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxCapsuleGeometry, static_cast<const PxCapsuleGeometry&>(pxGeom)); } break; case physx::PxGeometryType::eBOX: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxBoxGeometry, static_cast<const PxBoxGeometry&>(pxGeom)); } break; case physx::PxGeometryType::eTRIANGLEMESH: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxTriangleMeshGeometry, static_cast<const PxTriangleMeshGeometry&>(pxGeom)); } break; case physx::PxGeometryType::eCONVEXMESH: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxConvexMeshGeometry, static_cast<const PxConvexMeshGeometry&>(pxGeom)); } break; case physx::PxGeometryType::eHEIGHTFIELD: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxHeightFieldGeometry, static_cast<const PxHeightFieldGeometry&>(pxGeom)); } break; case physx::PxGeometryType::ePLANE: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxPlaneGeometry, static_cast<const PxPlaneGeometry&>(pxGeom)); } break; case physx::PxGeometryType::eCUSTOM: { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometry, static_cast<const PxCustomGeometry&>(pxGeom)); } break; default: break; } } void OmniPvdPxSampler::sampleScene(physx::NpScene* scene) { { physx::PxMutex::ScopedLock myLock(samplerInternals->mSampleMutex); if (!samplerInternals->mIsSampling) return; } OmniPvdPxScene* ovdScene = getSampledScene(scene); ovdScene->sampleScene(); } void OmniPvdPxSampler::onObjectAdd(const physx::PxBase& object) { if (!isSampling()) return; const PxPhysics& physics = static_cast<PxPhysics&>(NpPhysics::getInstance()); switch (object.getConcreteType()) { case physx::PxConcreteType::eHEIGHTFIELD: { const PxHeightField& hf = static_cast<const PxHeightField&>(object); streamHeightField(hf); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, heightFields, physics, hf); } break; case physx::PxConcreteType::eCONVEX_MESH: { const PxConvexMesh& cm = static_cast<const PxConvexMesh&>(object); streamConvexMesh(cm); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, convexMeshes, physics, cm); } break; case physx::PxConcreteType::eTRIANGLE_MESH_BVH33: case physx::PxConcreteType::eTRIANGLE_MESH_BVH34: { const PxTriangleMesh& m = static_cast<const PxTriangleMesh&>(object); streamTriMesh(m); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, triangleMeshes, physics, m); } break; case physx::PxConcreteType::eTETRAHEDRON_MESH: { const PxTetrahedronMesh& tm = static_cast<const PxTetrahedronMesh&>(object); streamTetMesh(tm); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, tetrahedronMeshes, physics, tm); } break; case physx::PxConcreteType::eSOFTBODY_MESH: { const PxSoftBodyMesh& sm = static_cast<const PxSoftBodyMesh&>(object); streamSoBoMesh(sm); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, softBodyMeshes, physics, sm); } break; case physx::PxConcreteType::eBVH: { const PxBVH& bvh = static_cast<const PxBVH&>(object); streamBVH(bvh); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, bvhs, physics, bvh); } break; case physx::PxConcreteType::eSHAPE: { const PxShape& shape = static_cast<const physx::PxShape&>(object); createGeometry(shape.getGeometry()); streamShape(shape); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, shapes, physics, shape); } break; case physx::PxConcreteType::eMATERIAL: { const PxMaterial& mat = static_cast<const PxMaterial&>(object); streamMaterial(mat); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, materials, physics, mat); } break; case physx::PxConcreteType::eSOFTBODY_MATERIAL: { const PxFEMSoftBodyMaterial& sbMat = static_cast<const PxFEMSoftBodyMaterial&>(object); streamFEMSoBoMaterial(sbMat); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, FEMSoftBodyMaterials, physics, sbMat); } break; case physx::PxConcreteType::eCLOTH_MATERIAL: { const PxFEMClothMaterial& clothMat = static_cast<const PxFEMClothMaterial&>(object); streamFEMClothMaterial(clothMat); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, FEMClothMaterials, physics, clothMat); } break; case physx::PxConcreteType::ePBD_MATERIAL: { const PxPBDMaterial& pbdhMat = static_cast<const PxPBDMaterial&>(object); streamPBDMaterial(pbdhMat); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, PBDMaterials, physics, pbdhMat); } break; case physx::PxConcreteType::eFLIP_MATERIAL: { const PxFLIPMaterial& flipMat = static_cast<const PxFLIPMaterial&>(object); streamFLIPMaterial(flipMat); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, FLIPMaterials, physics, flipMat); } break; case physx::PxConcreteType::eMPM_MATERIAL: { const PxMPMMaterial& mpmMat = static_cast<const PxMPMMaterial&>(object); streamMPMMaterial(mpmMat); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, MPMMaterials, physics, mpmMat); } break; case physx::PxConcreteType::eAGGREGATE: { const PxAggregate& agg = static_cast<const PxAggregate&>(object); streamAggregate(agg); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, aggregates, physics, agg); } break; case physx::PxConcreteType::eARTICULATION_REDUCED_COORDINATE: { const PxArticulationReducedCoordinate& art = static_cast<const PxArticulationReducedCoordinate&>(object); streamArticulation(art); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, articulations, physics, art); } break; case physx::PxConcreteType::eARTICULATION_LINK: { const PxArticulationLink& artLink = static_cast<const PxArticulationLink&>(object); streamArticulationLink(artLink); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, links, artLink.getArticulation(), artLink); } break; case physx::PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE: { const PxArticulationJointReducedCoordinate& artJoint = static_cast<const PxArticulationJointReducedCoordinate&>(object); streamArticulationJoint(artJoint); break; } case physx::PxConcreteType::eRIGID_DYNAMIC: { const PxRigidDynamic& rd = static_cast<const PxRigidDynamic&>(object); streamRigidDynamic(rd); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, rigidDynamics, physics, rd); } break; case physx::PxConcreteType::eRIGID_STATIC: { const PxRigidStatic& rs = static_cast<const PxRigidStatic&>(object); streamRigidStatic(rs); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, rigidStatics, physics, rs); } break; } } void OmniPvdPxSampler::onObjectRemove(const physx::PxBase& object) { if (!isSampling()) return; const PxPhysics& physics = static_cast<PxPhysics&>(NpPhysics::getInstance()); switch (object.getConcreteType()) { case physx::PxConcreteType::eHEIGHTFIELD: { const PxHeightField& hf = static_cast<const PxHeightField&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, heightFields, physics, hf); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxHeightField, hf); } break; case physx::PxConcreteType::eCONVEX_MESH: { const PxConvexMesh& cm = static_cast<const PxConvexMesh&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, convexMeshes, physics, cm); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxConvexMesh, cm); } break; case physx::PxConcreteType::eTRIANGLE_MESH_BVH33: case physx::PxConcreteType::eTRIANGLE_MESH_BVH34: { const PxTriangleMesh& m = static_cast<const PxTriangleMesh&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, triangleMeshes, physics, m); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxTriangleMesh, m); } break; case physx::PxConcreteType::eTETRAHEDRON_MESH: { const PxTetrahedronMesh& tm = static_cast<const PxTetrahedronMesh&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, tetrahedronMeshes, physics, tm); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxTetrahedronMesh, tm); } break; case physx::PxConcreteType::eSOFTBODY_MESH: { const PxSoftBodyMesh& sm = static_cast<const PxSoftBodyMesh&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, softBodyMeshes, physics, sm); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxSoftBodyMesh, sm); } break; case physx::PxConcreteType::eBVH: { const PxBVH& bvh = static_cast<const PxBVH&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, bvhs, physics, bvh); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxBVH, bvh); } break; case physx::PxConcreteType::eSHAPE: { const PxShape& shape = static_cast<const physx::PxShape&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, shapes, physics, shape); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxShape, shape); destroyGeometry(shape.getGeometry()); } break; case physx::PxConcreteType::eMATERIAL: { const PxMaterial& mat = static_cast<const PxMaterial&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, materials, physics, mat); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, mat); } break; case physx::PxConcreteType::eSOFTBODY_MATERIAL: { const PxFEMSoftBodyMaterial& sbMat = static_cast<const PxFEMSoftBodyMaterial&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, FEMSoftBodyMaterials, physics, sbMat); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxFEMSoftBodyMaterial, sbMat); } break; case physx::PxConcreteType::eCLOTH_MATERIAL: { const PxFEMClothMaterial& clothMat = static_cast<const PxFEMClothMaterial&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, FEMClothMaterials, physics, clothMat); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxFEMClothMaterial, clothMat); } break; case physx::PxConcreteType::ePBD_MATERIAL: { const PxPBDMaterial& pbdhMat = static_cast<const PxPBDMaterial&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, PBDMaterials, physics, pbdhMat); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxPBDMaterial, pbdhMat); } break; case physx::PxConcreteType::eFLIP_MATERIAL: { const PxFLIPMaterial& flipMat = static_cast<const PxFLIPMaterial&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, FLIPMaterials, physics, flipMat); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxFLIPMaterial, flipMat); } break; case physx::PxConcreteType::eMPM_MATERIAL: { const PxMPMMaterial& mpmMat = static_cast<const PxMPMMaterial&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, MPMMaterials, physics, mpmMat); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxMPMMaterial, mpmMat); } break; case physx::PxConcreteType::eAGGREGATE: { const PxAggregate& agg = static_cast<const PxAggregate&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, aggregates, physics, agg); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxAggregate, agg); } break; case physx::PxConcreteType::eARTICULATION_REDUCED_COORDINATE: { const PxArticulationReducedCoordinate& art = static_cast<const PxArticulationReducedCoordinate&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, articulations, physics, art); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, art); } break; case physx::PxConcreteType::eARTICULATION_LINK: { const PxArticulationLink& artLink = static_cast<const PxArticulationLink&>(object); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxActor, artLink); } break; case physx::PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE: { const PxArticulationJointReducedCoordinate& artJoint = static_cast<const PxArticulationJointReducedCoordinate&>(object); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, artJoint); } break; case physx::PxConcreteType::eRIGID_DYNAMIC: { const PxRigidDynamic& rd = static_cast<const PxRigidDynamic&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, rigidDynamics, physics, rd); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxActor, rd); } break; case physx::PxConcreteType::eRIGID_STATIC: { const PxRigidStatic& rs = static_cast<const PxRigidStatic&>(object); OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxPhysics, rigidStatics, physics, rs); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxActor, rs); } break; } } OmniPvdPxScene* OmniPvdPxSampler::getSampledScene(physx::NpScene* scene) { physx::PxMutex::ScopedLock myLock(samplerInternals->mSampledScenesMutex); const physx::PxHashMap<physx::NpScene*, OmniPvdPxScene*>::Entry* entry = samplerInternals->mSampledScenes.find(scene); if (entry) { return entry->second; } else { OmniPvdPxScene* ovdScene = PX_NEW(OmniPvdPxScene)(); samplerInternals->mSampledScenes[scene] = ovdScene; return ovdScene; } } // Returns true if the Geom was not yet seen and added bool OmniPvdSamplerInternals::addSharedMeshIfNotSeen(const void* geom, OmniPvdSharedMeshEnum geomEnum) { physx::PxMutex::ScopedLock myLock(samplerInternals->mSharedGeomsMutex); const physx::PxHashMap<const void*, OmniPvdSharedMeshEnum>::Entry* entry = samplerInternals->mSharedMeshesMap.find(geom); if (entry) { return false; } else { samplerInternals->mSharedMeshesMap[geom] = geomEnum; return true; } } /////////////////////////////////////////////////////////////////////////////// OmniPvdPxSampler* OmniPvdPxSampler::getInstance() { PX_ASSERT(&physx::NpPhysics::getInstance() != NULL); return &physx::NpPhysics::getInstance() ? physx::NpPhysics::getInstance().mOmniPvdSampler : NULL; } namespace physx { const OmniPvdPxCoreRegistrationData* NpOmniPvdGetPxCoreRegistrationData() { if (samplerInternals) { return &samplerInternals->mPvdStream.mRegistrationData; } else { return NULL; } } physx::NpOmniPvd* NpOmniPvdGetInstance() { if (samplerInternals) { return samplerInternals->mPvdStream.mOmniPvdInstance; } else { return NULL; } } } #endif
60,308
C++
39.448692
182
0.7598
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/OmniPvdPxSampler.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 OMNI_PVD_PX_SAMPLER_H #define OMNI_PVD_PX_SAMPLER_H #if PX_SUPPORT_OMNI_PVD #include "foundation/PxSimpleTypes.h" #include "foundation/PxHashMap.h" #include "foundation/PxMutex.h" #include "foundation/PxUserAllocated.h" #include "OmniPvdChunkAlloc.h" namespace physx { class PxScene; class PxBase; class NpScene; class PxActor; class PxShape; class PxMaterial; class PxFEMClothMaterial; class PxFEMMaterial; class PxFEMSoftBodyMaterial; class PxFLIPMaterial; class PxMPMMaterial; class PxParticleMaterial; class PxPBDMaterial; struct OmniPvdPxCoreRegistrationData; class NpOmniPvd; } void streamActorName(const physx::PxActor & a, const char* name); void streamSceneName(const physx::PxScene & s, const char* name); void streamShapeMaterials(const physx::PxShape&, physx::PxMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxFEMClothMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxFEMMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxFEMSoftBodyMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxFLIPMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxMPMMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxParticleMaterial* const * mats, physx::PxU32 nbrMaterials); void streamShapeMaterials(const physx::PxShape&, physx::PxPBDMaterial* const * mats, physx::PxU32 nbrMaterials); enum OmniPvdSharedMeshEnum { eOmniPvdTriMesh = 0, eOmniPvdConvexMesh = 1, eOmniPvdHeightField = 2, }; class OmniPvdWriter; class OmniPvdPxScene; class OmniPvdPxSampler : public physx::PxUserAllocated { public: OmniPvdPxSampler(); ~OmniPvdPxSampler(); void startSampling(); bool isSampling(); void setOmniPvdInstance(physx::NpOmniPvd* omniPvdIntance); // writes all contacts to the stream void streamSceneContacts(physx::NpScene& scene); // call at the end of a simulation step: void sampleScene(physx::NpScene* scene); static OmniPvdPxSampler* getInstance(); void onObjectAdd(const physx::PxBase& object); void onObjectRemove(const physx::PxBase& object); private: OmniPvdPxScene* getSampledScene(physx::NpScene* scene); }; namespace physx { const OmniPvdPxCoreRegistrationData* NpOmniPvdGetPxCoreRegistrationData(); NpOmniPvd* NpOmniPvdGetInstance(); } #endif #endif
4,271
C
34.305785
120
0.777336
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/OmniPvdTypes.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. // Declare OMNI_PVD Types and Attributes here! // The last two attribute parameters could now be derived from the other data, so could be removed in a refactor, // though explicit control may be better. // Note that HANDLE attributes have to use (Type const *) style, otherwise it won't compile! //////////////////////////////////////////////////////////////////////////////// // Bitfields //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_ENUM_BEGIN (PxSceneFlag) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_ACTIVE_ACTORS) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_CCD) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eDISABLE_CCD_RESWEEP) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_PCM) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eDISABLE_CONTACT_REPORT_BUFFER_RESIZE) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eDISABLE_CONTACT_CACHE) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eREQUIRE_RW_LOCK) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_STABILIZATION) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_AVERAGE_POINT) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_GPU_DYNAMICS) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_ENHANCED_DETERMINISM) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_FRICTION_EVERY_ITERATION) OMNI_PVD_ENUM_VALUE (PxSceneFlag, eENABLE_DIRECT_GPU_API) OMNI_PVD_ENUM_END (PxSceneFlag) OMNI_PVD_ENUM_BEGIN (PxMaterialFlag) OMNI_PVD_ENUM_VALUE (PxMaterialFlag, eDISABLE_FRICTION) OMNI_PVD_ENUM_VALUE (PxMaterialFlag, eDISABLE_STRONG_FRICTION) OMNI_PVD_ENUM_VALUE (PxMaterialFlag, eIMPROVED_PATCH_FRICTION) OMNI_PVD_ENUM_END (PxMaterialFlag) OMNI_PVD_ENUM_BEGIN (PxActorFlag) OMNI_PVD_ENUM_VALUE (PxActorFlag, eVISUALIZATION) OMNI_PVD_ENUM_VALUE (PxActorFlag, eDISABLE_GRAVITY) OMNI_PVD_ENUM_VALUE (PxActorFlag, eSEND_SLEEP_NOTIFIES) OMNI_PVD_ENUM_VALUE (PxActorFlag, eDISABLE_SIMULATION) OMNI_PVD_ENUM_END (PxActorFlag) OMNI_PVD_ENUM_BEGIN (PxRigidBodyFlag) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eKINEMATIC) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eENABLE_CCD) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eENABLE_CCD_FRICTION) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eENABLE_POSE_INTEGRATION_PREVIEW) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eENABLE_SPECULATIVE_CCD) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eENABLE_CCD_MAX_CONTACT_IMPULSE) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eRETAIN_ACCELERATIONS) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eFORCE_KINE_KINE_NOTIFICATIONS) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eFORCE_STATIC_KINE_NOTIFICATIONS) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eENABLE_GYROSCOPIC_FORCES) OMNI_PVD_ENUM_VALUE (PxRigidBodyFlag, eRESERVED) OMNI_PVD_ENUM_END (PxRigidBodyFlag) OMNI_PVD_ENUM_BEGIN (PxArticulationFlag) OMNI_PVD_ENUM_VALUE (PxArticulationFlag, eFIX_BASE) OMNI_PVD_ENUM_VALUE (PxArticulationFlag, eDRIVE_LIMITS_ARE_FORCES) OMNI_PVD_ENUM_VALUE (PxArticulationFlag, eDISABLE_SELF_COLLISION) OMNI_PVD_ENUM_VALUE (PxArticulationFlag, eCOMPUTE_JOINT_FORCES) OMNI_PVD_ENUM_END (PxArticulationFlag) OMNI_PVD_ENUM_BEGIN (PxRigidDynamicLockFlag) OMNI_PVD_ENUM_VALUE (PxRigidDynamicLockFlag, eLOCK_LINEAR_X) OMNI_PVD_ENUM_VALUE (PxRigidDynamicLockFlag, eLOCK_LINEAR_Y) OMNI_PVD_ENUM_VALUE (PxRigidDynamicLockFlag, eLOCK_LINEAR_Z) OMNI_PVD_ENUM_VALUE (PxRigidDynamicLockFlag, eLOCK_ANGULAR_X) OMNI_PVD_ENUM_VALUE (PxRigidDynamicLockFlag, eLOCK_ANGULAR_Y) OMNI_PVD_ENUM_VALUE (PxRigidDynamicLockFlag, eLOCK_ANGULAR_Z) OMNI_PVD_ENUM_END (PxRigidDynamicLockFlag) OMNI_PVD_ENUM_BEGIN (PxShapeFlag) OMNI_PVD_ENUM_VALUE (PxShapeFlag, eSIMULATION_SHAPE) OMNI_PVD_ENUM_VALUE (PxShapeFlag, eSCENE_QUERY_SHAPE) OMNI_PVD_ENUM_VALUE (PxShapeFlag, eTRIGGER_SHAPE) OMNI_PVD_ENUM_VALUE (PxShapeFlag, eVISUALIZATION) OMNI_PVD_ENUM_END (PxShapeFlag) //////////////////////////////////////////////////////////////////////////////// // Single value enums //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_ENUM_BEGIN (PxFrictionType) OMNI_PVD_ENUM_VALUE (PxFrictionType, ePATCH) OMNI_PVD_ENUM_VALUE (PxFrictionType, eONE_DIRECTIONAL) OMNI_PVD_ENUM_VALUE (PxFrictionType, eTWO_DIRECTIONAL) OMNI_PVD_ENUM_END (PxFrictionType) OMNI_PVD_ENUM_BEGIN (PxBroadPhaseType) OMNI_PVD_ENUM_VALUE (PxBroadPhaseType, eSAP) OMNI_PVD_ENUM_VALUE (PxBroadPhaseType, eMBP) OMNI_PVD_ENUM_VALUE (PxBroadPhaseType, eABP) OMNI_PVD_ENUM_VALUE (PxBroadPhaseType, eGPU) OMNI_PVD_ENUM_END (PxBroadPhaseType) OMNI_PVD_ENUM_BEGIN (PxSolverType) OMNI_PVD_ENUM_VALUE (PxSolverType, ePGS) OMNI_PVD_ENUM_VALUE (PxSolverType, eTGS) OMNI_PVD_ENUM_END (PxSolverType) OMNI_PVD_ENUM_BEGIN (PxPairFilteringMode) OMNI_PVD_ENUM_VALUE (PxPairFilteringMode, eKEEP) OMNI_PVD_ENUM_VALUE (PxPairFilteringMode, eSUPPRESS) OMNI_PVD_ENUM_VALUE (PxPairFilteringMode, eKILL) OMNI_PVD_ENUM_END (PxPairFilteringMode) OMNI_PVD_ENUM_BEGIN (PxCombineMode) OMNI_PVD_ENUM_VALUE (PxCombineMode, eAVERAGE) OMNI_PVD_ENUM_VALUE (PxCombineMode, eMIN) OMNI_PVD_ENUM_VALUE (PxCombineMode, eMULTIPLY) OMNI_PVD_ENUM_VALUE (PxCombineMode, eMAX) OMNI_PVD_ENUM_END (PxCombineMode) OMNI_PVD_ENUM_BEGIN (PxActorType) OMNI_PVD_ENUM_VALUE (PxActorType, eRIGID_STATIC) OMNI_PVD_ENUM_VALUE (PxActorType, eRIGID_DYNAMIC) OMNI_PVD_ENUM_VALUE (PxActorType, eARTICULATION_LINK) OMNI_PVD_ENUM_VALUE (PxActorType, eSOFTBODY) OMNI_PVD_ENUM_VALUE (PxActorType, eFEMCLOTH) OMNI_PVD_ENUM_VALUE (PxActorType, ePBD_PARTICLESYSTEM) OMNI_PVD_ENUM_VALUE (PxActorType, eFLIP_PARTICLESYSTEM) OMNI_PVD_ENUM_VALUE (PxActorType, eMPM_PARTICLESYSTEM) OMNI_PVD_ENUM_VALUE (PxActorType, eHAIRSYSTEM) OMNI_PVD_ENUM_END (PxActorType) OMNI_PVD_ENUM_BEGIN (PxArticulationJointType) OMNI_PVD_ENUM_VALUE (PxArticulationJointType, eFIX) OMNI_PVD_ENUM_VALUE (PxArticulationJointType, ePRISMATIC) OMNI_PVD_ENUM_VALUE (PxArticulationJointType, eREVOLUTE) OMNI_PVD_ENUM_VALUE (PxArticulationJointType, eREVOLUTE_UNWRAPPED) OMNI_PVD_ENUM_VALUE (PxArticulationJointType, eSPHERICAL) OMNI_PVD_ENUM_VALUE (PxArticulationJointType, eUNDEFINED) OMNI_PVD_ENUM_END (PxArticulationJointType) OMNI_PVD_ENUM_BEGIN (PxArticulationMotion) OMNI_PVD_ENUM_VALUE (PxArticulationMotion, eLOCKED) OMNI_PVD_ENUM_VALUE (PxArticulationMotion, eLIMITED) OMNI_PVD_ENUM_VALUE (PxArticulationMotion, eFREE) OMNI_PVD_ENUM_END (PxArticulationMotion) OMNI_PVD_ENUM_BEGIN (PxArticulationDriveType) OMNI_PVD_ENUM_VALUE (PxArticulationDriveType, eFORCE) OMNI_PVD_ENUM_VALUE (PxArticulationDriveType, eACCELERATION) OMNI_PVD_ENUM_VALUE (PxArticulationDriveType, eTARGET) OMNI_PVD_ENUM_VALUE (PxArticulationDriveType, eVELOCITY) OMNI_PVD_ENUM_VALUE (PxArticulationDriveType, eNONE) OMNI_PVD_ENUM_END (PxArticulationDriveType) //////////////////////////////////////////////////////////////////////////////// // Classes //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // PxPhysics //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxPhysics) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, scenes, PxScene) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, heightFields, PxHeightField) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, convexMeshes, PxConvexMesh) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, triangleMeshes, PxTriangleMesh) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, tetrahedronMeshes, PxTetrahedronMesh) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, softBodyMeshes, PxSoftBodyMesh) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, shapes, PxShape) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, bvhs, PxBVH) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, materials, PxMaterial) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, FEMSoftBodyMaterials, PxFEMSoftBodyMaterial) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, FEMClothMaterials, PxFEMClothMaterial) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, PBDMaterials, PxPBDMaterial) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, FLIPMaterials, PxFLIPMaterial) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, MPMMaterials, PxMPMMaterial) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, rigidDynamics, PxActor) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, rigidStatics, PxActor) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, aggregates, PxAggregate) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxPhysics, articulations, PxArticulationReducedCoordinate) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxPhysics, tolerancesScale, PxTolerancesScale, OmniPvdDataType::eFLOAT32, 2) OMNI_PVD_CLASS_END (PxPhysics) //////////////////////////////////////////////////////////////////////////////// // PxScene //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxScene) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxScene, actors, PxActor) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxScene, articulations, PxArticulationReducedCoordinate) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxScene, aggregates, PxAggregate) OMNI_PVD_ATTRIBUTE_FLAG (PxScene, flags, PxSceneFlags, PxSceneFlag) OMNI_PVD_ATTRIBUTE_FLAG (PxScene, frictionType, PxFrictionType::Enum, PxFrictionType) OMNI_PVD_ATTRIBUTE_FLAG (PxScene, broadPhaseType, PxBroadPhaseType::Enum, PxBroadPhaseType) OMNI_PVD_ATTRIBUTE_FLAG (PxScene, kineKineFilteringMode, PxPairFilteringMode::Enum, PxPairFilteringMode) OMNI_PVD_ATTRIBUTE_FLAG (PxScene, staticKineFilteringMode,PxPairFilteringMode::Enum, PxPairFilteringMode) OMNI_PVD_ATTRIBUTE_FLAG (PxScene, solverType, PxSolverType::Enum, PxSolverType) OMNI_PVD_ATTRIBUTE_STRING (PxScene, name) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxScene, gravity, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE (PxScene, bounceThresholdVelocity,PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, frictionOffsetThreshold,PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, frictionCorrelationDistance, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, solverOffsetSlop, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, solverBatchSize, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, solverArticulationBatchSize, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, nbContactDataBlocks, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, maxNbContactDataBlocks, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, maxBiasCoefficient, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, contactReportStreamBufferSize, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, ccdMaxPasses, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, ccdThreshold, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, ccdMaxSeparation, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, wakeCounterResetValue, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxScene, hasCPUDispatcher, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, hasCUDAContextManager, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, hasSimulationEventCallback, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, hasContactModifyCallback, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, hasCCDContactModifyCallback, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, hasBroadPhaseCallback, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, hasFilterCallback, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbActors, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbBodies, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbStaticShapes,PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbDynamicShapes, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbAggregates, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbConstraints, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbRegions, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, limitsMaxNbBroadPhaseOverlaps, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxScene, sanityBounds, PxBounds3, OmniPvdDataType::eFLOAT32, 6) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxScene, gpuDynamicsConfig, PxgDynamicsMemoryConfig, OmniPvdDataType::eUINT32, 12) OMNI_PVD_ATTRIBUTE (PxScene, gpuMaxNumPartitions, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, gpuMaxNumStaticPartitions, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, gpuComputeVersion, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxScene, contactPairSlabSize, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxScene, tolerancesScale, PxTolerancesScale, OmniPvdDataType::eFLOAT32, 2) OMNI_PVD_ATTRIBUTE (PxScene, pairCount, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsActors, PxActor*, OmniPvdDataType::eOBJECT_HANDLE) // 2 for each pair OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsContactCounts, PxU32, OmniPvdDataType::eUINT32) // 1 for each pair OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsContactPoints, PxReal, OmniPvdDataType::eFLOAT32) // 3 for each contact OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsContactNormals, PxReal, OmniPvdDataType::eFLOAT32) // 3 for each contact OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsContactSeparations, PxReal, OmniPvdDataType::eFLOAT32) // 1 for each contact OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsContactShapes, PxShape*, OmniPvdDataType::eOBJECT_HANDLE) // 2 for each contact OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxScene, pairsContactFacesIndices, PxU32, OmniPvdDataType::eUINT32) // 2 for each contact OMNI_PVD_CLASS_END (PxScene) //////////////////////////////////////////////////////////////////////////////// // PxBaseMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxBaseMaterial) OMNI_PVD_CLASS_END (PxBaseMaterial) //////////////////////////////////////////////////////////////////////////////// // PxMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxMaterial, PxBaseMaterial) OMNI_PVD_ATTRIBUTE_FLAG (PxMaterial, flags, PxMaterialFlags, PxMaterialFlag) OMNI_PVD_ATTRIBUTE_FLAG (PxMaterial, frictionCombineMode, PxCombineMode::Enum, PxCombineMode) OMNI_PVD_ATTRIBUTE_FLAG (PxMaterial, restitutionCombineMode,PxCombineMode::Enum, PxCombineMode) OMNI_PVD_ATTRIBUTE (PxMaterial, staticFriction, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxMaterial, dynamicFriction, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxMaterial, restitution, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxMaterial, damping, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxMaterial) //////////////////////////////////////////////////////////////////////////////// // PxFEMSoftBodyMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxFEMSoftBodyMaterial, PxBaseMaterial) OMNI_PVD_CLASS_END (PxFEMSoftBodyMaterial) //////////////////////////////////////////////////////////////////////////////// // PxFEMClothMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxFEMClothMaterial, PxBaseMaterial) OMNI_PVD_CLASS_END (PxFEMClothMaterial) //////////////////////////////////////////////////////////////////////////////// // PxPBDMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxPBDMaterial, PxBaseMaterial) OMNI_PVD_CLASS_END (PxPBDMaterial) //////////////////////////////////////////////////////////////////////////////// // PxFLIPMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxFLIPMaterial, PxBaseMaterial) OMNI_PVD_CLASS_END (PxFLIPMaterial) //////////////////////////////////////////////////////////////////////////////// // PxMPMMaterial //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxMPMMaterial, PxBaseMaterial) OMNI_PVD_CLASS_END (PxMPMMaterial) //////////////////////////////////////////////////////////////////////////////// // PxAggregate //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxAggregate) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxAggregate, actors, PxActor) OMNI_PVD_ATTRIBUTE (PxAggregate, selfCollision, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxAggregate, maxNbShapes, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxAggregate, scene, PxScene* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxAggregate) //////////////////////////////////////////////////////////////////////////////// // PxActor // Missing // aggregate? // scene? //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxActor) OMNI_PVD_ATTRIBUTE_FLAG (PxActor, type, PxActorType::Enum, PxActorType) OMNI_PVD_ATTRIBUTE_FLAG (PxActor, flags, PxActorFlags, PxActorFlag) OMNI_PVD_ATTRIBUTE_STRING (PxActor, name) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxActor, worldBounds, PxBounds3, OmniPvdDataType::eFLOAT32, 6) OMNI_PVD_ATTRIBUTE (PxActor, dominance, PxDominanceGroup, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxActor, ownerClient, PxClientID, OmniPvdDataType::eUINT8) OMNI_PVD_CLASS_END (PxActor) //////////////////////////////////////////////////////////////////////////////// // PxRigidActor // Missing // internalActorIndex? // constraints? // Remap // translation + rotation -> globalPose? //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxRigidActor, PxActor) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxRigidActor, translation, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxRigidActor, rotation, PxQuat, OmniPvdDataType::eFLOAT32, 4) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxRigidActor, shapes, PxShape) OMNI_PVD_CLASS_END (PxRigidActor) //////////////////////////////////////////////////////////////////////////////// // PxRigidStatic //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxRigidStatic, PxRigidActor) OMNI_PVD_CLASS_END (PxRigidStatic) //////////////////////////////////////////////////////////////////////////////// // PxRigidBody // Missing // islandNodeIndex? // force? // torque? //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxRigidBody, PxRigidActor) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxRigidBody, cMassLocalPose, PxTransform, OmniPvdDataType::eFLOAT32, 7) OMNI_PVD_ATTRIBUTE (PxRigidBody, mass, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxRigidBody, massSpaceInertiaTensor, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE (PxRigidBody, linearDamping, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidBody, angularDamping, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxRigidBody, linearVelocity, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxRigidBody, angularVelocity, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE (PxRigidBody, maxLinearVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidBody, maxAngularVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_FLAG (PxRigidBody, rigidBodyFlags, PxRigidBodyFlags, PxRigidBodyFlag) OMNI_PVD_ATTRIBUTE (PxRigidBody, minAdvancedCCDCoefficient, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidBody, maxDepenetrationVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidBody, maxContactImpulse, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidBody, contactSlopCoefficient, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxRigidBody) //////////////////////////////////////////////////////////////////////////////// // PxRigidDynamic // Missing // kinematicTarget? //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxRigidDynamic, PxRigidBody) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, isSleeping, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, sleepThreshold, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, stabilizationThreshold, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_FLAG (PxRigidDynamic, rigidDynamicLockFlags, PxRigidDynamicLockFlags, PxRigidDynamicLockFlag) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, wakeCounter, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, positionIterations, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, velocityIterations, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxRigidDynamic, contactReportThreshold, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxRigidDynamic) //////////////////////////////////////////////////////////////////////////////// // PxArticulationLink // Missing // inboundJoint? // children? // linkIndex? //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxArticulationLink, PxRigidBody) OMNI_PVD_ATTRIBUTE (PxArticulationLink, articulation, PxArticulationReducedCoordinate* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_ATTRIBUTE (PxArticulationLink, inboundJointDOF, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxArticulationLink, CFMScale, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxArticulationLink) //////////////////////////////////////////////////////////////////////////////// // PxArticulationReducedCoordinate //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxArticulationReducedCoordinate) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, positionIterations, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, velocityIterations, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, isSleeping, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, sleepThreshold, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, stabilizationThreshold, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, wakeCounter, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, maxLinearVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, maxAngularVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_UNIQUE_LIST (PxArticulationReducedCoordinate, links, PxArticulationLink) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxArticulationReducedCoordinate, worldBounds, PxBounds3, OmniPvdDataType::eFLOAT32, 6) OMNI_PVD_ATTRIBUTE_FLAG (PxArticulationReducedCoordinate, articulationFlags, PxArticulationFlags, PxArticulationFlag) OMNI_PVD_ATTRIBUTE (PxArticulationReducedCoordinate, dofs, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_CLASS_END (PxArticulationReducedCoordinate) //////////////////////////////////////////////////////////////////////////////// // PxArticulationJointReducedCoordinate //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxArticulationJointReducedCoordinate) OMNI_PVD_ATTRIBUTE (PxArticulationJointReducedCoordinate, parentLink, PxArticulationLink* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_ATTRIBUTE (PxArticulationJointReducedCoordinate, childLink, PxArticulationLink* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxArticulationJointReducedCoordinate, parentTranslation, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxArticulationJointReducedCoordinate, parentRotation, PxQuat, OmniPvdDataType::eFLOAT32, 4) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxArticulationJointReducedCoordinate, childTranslation, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxArticulationJointReducedCoordinate, childRotation, PxQuat, OmniPvdDataType::eFLOAT32, 4) OMNI_PVD_ATTRIBUTE_FLAG (PxArticulationJointReducedCoordinate, type, PxArticulationJointType::Enum, PxArticulationJointType) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, motion, PxArticulationMotion::Enum, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, armature, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxArticulationJointReducedCoordinate, frictionCoefficient, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxArticulationJointReducedCoordinate, maxJointVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, jointPosition, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, jointVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_STRING (PxArticulationJointReducedCoordinate, concreteTypeName) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, limitLow, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, limitHigh, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, driveStiffness, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, driveDamping, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, driveMaxForce, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, driveType, PxArticulationDriveType::Enum, OmniPvdDataType::eUINT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, driveTarget, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxArticulationJointReducedCoordinate, driveVelocity, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxArticulationJointReducedCoordinate) //////////////////////////////////////////////////////////////////////////////// // PxShape //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxShape) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxShape, translation, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxShape, rotation, PxQuat, OmniPvdDataType::eFLOAT32, 4) OMNI_PVD_ATTRIBUTE (PxShape, isExclusive, bool, OmniPvdDataType::eUINT8) OMNI_PVD_ATTRIBUTE (PxShape, geom, PxGeometry* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_ATTRIBUTE (PxShape, contactOffset, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxShape, restOffset, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxShape, densityForFluid, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxShape, torsionalPatchRadius, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxShape, minTorsionalPatchRadius, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_FLAG (PxShape, shapeFlags, PxShapeFlags, PxShapeFlag) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxShape, simulationFilterData, PxFilterData, OmniPvdDataType::eUINT32, 4) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxShape, queryFilterData, PxFilterData, OmniPvdDataType::eUINT32, 4) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxShape, materials, PxMaterial* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxShape) //////////////////////////////////////////////////////////////////////////////// // PxGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxGeometry) OMNI_PVD_CLASS_END (PxGeometry) //////////////////////////////////////////////////////////////////////////////// // PxSphereGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxSphereGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE (PxSphereGeometry, radius, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxSphereGeometry) //////////////////////////////////////////////////////////////////////////////// // PxCapsuleGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxCapsuleGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE (PxCapsuleGeometry, halfHeight, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE (PxCapsuleGeometry, radius, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_CLASS_END (PxCapsuleGeometry) //////////////////////////////////////////////////////////////////////////////// // PxBoxGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxBoxGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxBoxGeometry, halfExtents, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_CLASS_END (PxBoxGeometry) //////////////////////////////////////////////////////////////////////////////// // PxPlaneGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxPlaneGeometry, PxGeometry) OMNI_PVD_CLASS_END (PxPlaneGeometry) //////////////////////////////////////////////////////////////////////////////// // PxConvexMeshGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxConvexMeshGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxConvexMeshGeometry, scale, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE (PxConvexMeshGeometry, convexMesh, PxConvexMesh* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxConvexMeshGeometry) //////////////////////////////////////////////////////////////////////////////// // PxConvexMesh //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxConvexMesh) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxConvexMesh, verts, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxConvexMesh, tris, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_CLASS_END (PxConvexMesh) //////////////////////////////////////////////////////////////////////////////// // PxHeightFieldGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxHeightFieldGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxHeightFieldGeometry, scale, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE (PxHeightFieldGeometry, heightField, PxHeightField* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxHeightFieldGeometry) //////////////////////////////////////////////////////////////////////////////// // PxHeightField //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxHeightField) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxHeightField, verts, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxHeightField, tris, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_CLASS_END (PxHeightField) //////////////////////////////////////////////////////////////////////////////// // PxTriangleMeshGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxTriangleMeshGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxTriangleMeshGeometry, scale, PxVec3, OmniPvdDataType::eFLOAT32, 3) OMNI_PVD_ATTRIBUTE (PxTriangleMeshGeometry, triangleMesh, PxTriangleMesh* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxTriangleMeshGeometry) //////////////////////////////////////////////////////////////////////////////// // PxTriangleMesh //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxTriangleMesh) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxTriangleMesh, verts, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxTriangleMesh, tris, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_CLASS_END (PxTriangleMesh) //////////////////////////////////////////////////////////////////////////////// // PxTetrahedronMeshGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxTetrahedronMeshGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE (PxTetrahedronMeshGeometry, tetrahedronMesh, PxTetrahedronMesh* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxTetrahedronMeshGeometry) //////////////////////////////////////////////////////////////////////////////// // PxTetrahedronMesh //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxTetrahedronMesh) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxTetrahedronMesh, verts, PxReal, OmniPvdDataType::eFLOAT32) OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxTetrahedronMesh, tets, PxU32, OmniPvdDataType::eUINT32) OMNI_PVD_CLASS_END (PxTetrahedronMesh) //////////////////////////////////////////////////////////////////////////////// // PxCustomGeometry //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_DERIVED_BEGIN (PxCustomGeometry, PxGeometry) OMNI_PVD_ATTRIBUTE (PxCustomGeometry, callbacks, PxCustomGeometry::Callbacks* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxCustomGeometry) //////////////////////////////////////////////////////////////////////////////// // PxSoftBodyMesh //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxSoftBodyMesh) OMNI_PVD_ATTRIBUTE (PxSoftBodyMesh, collisionMesh, PxTetrahedronMesh* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_ATTRIBUTE (PxSoftBodyMesh, simulationMesh,PxTetrahedronMesh* const, OmniPvdDataType::eOBJECT_HANDLE) OMNI_PVD_CLASS_END (PxSoftBodyMesh) //////////////////////////////////////////////////////////////////////////////// // PxBVH //////////////////////////////////////////////////////////////////////////////// OMNI_PVD_CLASS_BEGIN (PxBVH) OMNI_PVD_CLASS_END (PxBVH)
37,269
C
61.428811
148
0.6602
NVIDIA-Omniverse/PhysX/physx/source/physx/src/omnipvd/OmniPvdChunkAlloc.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 OMNI_PVD_CHUNK_ALLOC_H #define OMNI_PVD_CHUNK_ALLOC_H #include "foundation/PxUserAllocated.h" //////////////////////////////////////////////////////////////////////////////// // The usage reason for splitting the Chunk allocator into a ChunkPool and a // ByteAllocator is so that similarly accessed objects get allocated next to each // other within the same Chunk, which is managed by the ByteAllocator. The // ChunkPool is basically just a resource pool. Not thread safe anything :-) // Locking is bad mkkk... //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Usage example of setting up a ChunkPool, a ByteAllocator and allocating some // bytes, for the lulz. //////////////////////////////////////////////////////////////////////////////// /* OmniPvdChunkPool pool; // set the individual Chunks to a size of 100k bytes pool.setChunkSize(100000); // all allocations must go through a ByteAllocator, so create one OmniPvdChunkByteAllocator allocator; // connect the ByteAllocator to the pool allocator.setPool(&pool); // we allocate 100 bytes through the ByteAllocator unsigned char *someBytes=allocator.allocBytes(100); */ //////////////////////////////////////////////////////////////////////////////// // Once we want to cleanup the allocations, return the Chunks to the ChunkPool, // which is also done silently in the destructor of the ByteAllocator. //////////////////////////////////////////////////////////////////////////////// /* allocator.freeChunks(); */ //////////////////////////////////////////////////////////////////////////////// // Memory management warning! The ByteAllocator does not deallocate the Chunks, // but must return the Chunks to the ChunkPool before going out of scope. The // ChunkPool can only deallocate the Chunks that is has in its free Chunks list, // so all ByteAllocators must either all go out of scope before the ChunkPool // goes out of scope or the ByteAllocators must all call the function freeChunks // before the ChunkPool goes out of scope. //////////////////////////////////////////////////////////////////////////////// class OmniPvdChunkElement { public: OmniPvdChunkElement(); ~OmniPvdChunkElement(); OmniPvdChunkElement* mNextElement; }; class OmniPvdChunk : public physx::PxUserAllocated { public: OmniPvdChunk(); ~OmniPvdChunk(); void resetChunk(int nbrBytes); int nbrBytesUSed(); unsigned char* mData; int mNbrBytesAllocated; int mNbrBytesFree; unsigned char* mBytePtr; OmniPvdChunk* mNextChunk; }; class OmniPvdChunkList { public: OmniPvdChunkList(); ~OmniPvdChunkList(); void resetList(); void appendList(OmniPvdChunkList* list); void appendChunk(OmniPvdChunk* chunk); OmniPvdChunk* removeFirst(); OmniPvdChunk* mFirstChunk; OmniPvdChunk* mLastChunk; int mNbrChunks; }; class OmniPvdChunkPool { public: OmniPvdChunkPool(); ~OmniPvdChunkPool(); void setChunkSize(int chunkSize); OmniPvdChunk* getChunk(); OmniPvdChunkList mFreeChunks; int mChunkSize; int mNbrAllocatedChunks; }; class OmniPvdChunkByteAllocator { public: OmniPvdChunkByteAllocator(); ~OmniPvdChunkByteAllocator(); OmniPvdChunkElement* allocChunkElement(int totalStructSize); void setPool(OmniPvdChunkPool* pool); unsigned char* allocBytes(int nbrBytes); void freeChunks(); OmniPvdChunkList mUsedChunks; OmniPvdChunkPool* mPool; }; #endif
5,205
C
33.25
81
0.667819