file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultErrorCallback.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/PxString.h"
#include "foundation/PxThread.h"
#include "extensions/PxDefaultErrorCallback.h"
#include <stdio.h>
using namespace physx;
PxDefaultErrorCallback::PxDefaultErrorCallback()
{
}
PxDefaultErrorCallback::~PxDefaultErrorCallback()
{
}
void PxDefaultErrorCallback::reportError(PxErrorCode::Enum e, const char* message, const char* file, int line)
{
const char* errorCode = NULL;
switch (e)
{
case PxErrorCode::eNO_ERROR:
errorCode = "no error";
break;
case PxErrorCode::eINVALID_PARAMETER:
errorCode = "invalid parameter";
break;
case PxErrorCode::eINVALID_OPERATION:
errorCode = "invalid operation";
break;
case PxErrorCode::eOUT_OF_MEMORY:
errorCode = "out of memory";
break;
case PxErrorCode::eDEBUG_INFO:
errorCode = "info";
break;
case PxErrorCode::eDEBUG_WARNING:
errorCode = "warning";
break;
case PxErrorCode::ePERF_WARNING:
errorCode = "performance warning";
break;
case PxErrorCode::eABORT:
errorCode = "abort";
break;
case PxErrorCode::eINTERNAL_ERROR:
errorCode = "internal error";
break;
case PxErrorCode::eMASK_ALL:
errorCode = "unknown error";
break;
}
PX_ASSERT(errorCode);
if(errorCode)
{
char buffer[1024];
sprintf(buffer, "%s (%d) : %s : %s\n", file, line, errorCode, message);
PxPrintString(buffer);
// in debug builds halt execution for abort codes
PX_ASSERT(e != PxErrorCode::eABORT);
// in release builds we also want to halt execution
// and make sure that the error message is flushed
while (e == PxErrorCode::eABORT)
{
PxPrintString(buffer);
PxThread::sleep(1000);
}
}
}
| 3,353 | C++ | 30.942857 | 110 | 0.739338 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtFixedJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_FIXED_JOINT_H
#define EXT_FIXED_JOINT_H
#include "extensions/PxFixedJoint.h"
#include "ExtJoint.h"
#include "CmUtils.h"
namespace physx
{
struct PxFixedJointGeneratedValues;
namespace Ext
{
struct FixedJointData : public JointData
{
};
typedef JointT<PxFixedJoint, FixedJointData, PxFixedJointGeneratedValues> FixedJointT;
class FixedJoint : public FixedJointT
{
public:
// PX_SERIALIZATION
FixedJoint(PxBaseFlags baseFlags) : FixedJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static FixedJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<FixedJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
FixedJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxFixedJoint
//~PxFixedJoint
// PxConstraintConnector
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
//~PxConstraintConnector
};
} // namespace Ext
} // namespace physx
#endif
| 2,854 | C | 39.785714 | 165 | 0.764541 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRackAndPinionJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_RACK_AND_PINION_JOINT_H
#define EXT_RACK_AND_PINION_JOINT_H
#include "extensions/PxRackAndPinionJoint.h"
#include "ExtJoint.h"
#include "CmUtils.h"
namespace physx
{
struct PxRackAndPinionJointGeneratedValues;
namespace Ext
{
struct RackAndPinionJointData : public JointData
{
const PxBase* hingeJoint;
const PxBase* prismaticJoint;
float ratio;
float px;
float vangle;
};
typedef JointT<PxRackAndPinionJoint, RackAndPinionJointData, PxRackAndPinionJointGeneratedValues> RackAndPinionJointT;
class RackAndPinionJoint : public RackAndPinionJointT
{
public:
// PX_SERIALIZATION
RackAndPinionJoint(PxBaseFlags baseFlags) : RackAndPinionJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static RackAndPinionJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<RackAndPinionJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
RackAndPinionJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxRackAndPinionJoint
virtual bool setJoints(const PxBase* hinge, const PxBase* prismatic) PX_OVERRIDE;
virtual void getJoints(const PxBase*& hinge, const PxBase*& prismatic) const PX_OVERRIDE;
virtual void setRatio(float ratio) PX_OVERRIDE;
virtual float getRatio() const PX_OVERRIDE;
virtual bool setData(PxU32 nbRackTeeth, PxU32 nbPinionTeeth, float rackLength) PX_OVERRIDE;
//~PxRackAndPinionJoint
// PxConstraintConnector
virtual void* prepareData() PX_OVERRIDE
{
updateError();
return mData;
}
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
//~PxConstraintConnector
private:
float mVirtualAngle0;
float mPersistentAngle0;
bool mInitDone;
void updateError();
void resetError();
};
} // namespace Ext
}
#endif
| 3,749 | C | 39.760869 | 173 | 0.751667 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRevoluteJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_REVOLUTE_JOINT_H
#define EXT_REVOLUTE_JOINT_H
#include "extensions/PxRevoluteJoint.h"
#include "ExtJoint.h"
#include "foundation/PxIntrinsics.h"
#include "CmUtils.h"
namespace physx
{
struct PxRevoluteJointGeneratedValues;
namespace Ext
{
struct RevoluteJointData : public JointData
{
PxReal driveVelocity;
PxReal driveForceLimit;
PxReal driveGearRatio;
PxJointAngularLimitPair limit;
PxRevoluteJointFlags jointFlags;
// private: // PT: must be public for a benchmark
RevoluteJointData(const PxJointAngularLimitPair& pair) : limit(pair) {}
};
typedef JointT<PxRevoluteJoint, RevoluteJointData, PxRevoluteJointGeneratedValues> RevoluteJointT;
class RevoluteJoint : public RevoluteJointT
{
public:
// PX_SERIALIZATION
RevoluteJoint(PxBaseFlags baseFlags) : RevoluteJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static RevoluteJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<RevoluteJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
RevoluteJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxRevoluteJoint
virtual PxReal getAngle() const PX_OVERRIDE;
virtual PxReal getVelocity() const PX_OVERRIDE;
virtual void setLimit(const PxJointAngularLimitPair& limit) PX_OVERRIDE;
virtual PxJointAngularLimitPair getLimit() const PX_OVERRIDE;
virtual void setDriveVelocity(PxReal velocity, bool autowake = true) PX_OVERRIDE;
virtual PxReal getDriveVelocity() const PX_OVERRIDE;
virtual void setDriveForceLimit(PxReal forceLimit) PX_OVERRIDE;
virtual PxReal getDriveForceLimit() const PX_OVERRIDE;
virtual void setDriveGearRatio(PxReal gearRatio) PX_OVERRIDE;
virtual PxReal getDriveGearRatio() const PX_OVERRIDE;
virtual void setRevoluteJointFlags(PxRevoluteJointFlags flags) PX_OVERRIDE;
virtual void setRevoluteJointFlag(PxRevoluteJointFlag::Enum flag, bool value) PX_OVERRIDE;
virtual PxRevoluteJointFlags getRevoluteJointFlags() const PX_OVERRIDE;
//~PxRevoluteJoint
// PxConstraintConnector
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
#if PX_SUPPORT_OMNI_PVD
virtual void updateOmniPvdProperties() const PX_OVERRIDE;
#endif
//~PxConstraintConnector
};
} // namespace Ext
} // namespace physx
#endif
| 4,240 | C | 42.27551 | 169 | 0.767689 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtJointMetaDataExtensions.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_JOINT_META_DATA_EXTENSIONS_H
#define EXT_JOINT_META_DATA_EXTENSIONS_H
#include "PvdMetaDataExtensions.h"
namespace physx
{
namespace pvdsdk
{
struct PxExtensionPvdOnlyProperties
{
enum Enum
{
FirstProp = PxExtensionsPropertyInfoName::LastPxPropertyInfoName,
DEFINE_ENUM_RANGE( PxJoint_Actors, 2 ),
DEFINE_ENUM_RANGE( PxJoint_BreakForce, 2 ),
DEFINE_ENUM_RANGE( PxD6Joint_DriveVelocity, 2 ),
DEFINE_ENUM_RANGE( PxD6Joint_Motion, PxD6Axis::eCOUNT ),
DEFINE_ENUM_RANGE( PxD6Joint_Drive, PxD6Drive::eCOUNT * ( PxExtensionsPropertyInfoName::PxD6JointDrive_PropertiesStop - PxExtensionsPropertyInfoName::PxD6JointDrive_PropertiesStart ) ),
DEFINE_ENUM_RANGE( PxD6Joint_LinearLimit, 100 ),
DEFINE_ENUM_RANGE( PxD6Joint_SwingLimit, 100 ),
DEFINE_ENUM_RANGE( PxD6Joint_TwistLimit, 100 ),
DEFINE_ENUM_RANGE( PxPrismaticJoint_Limit, 100 ),
DEFINE_ENUM_RANGE( PxRevoluteJoint_Limit, 100 ),
DEFINE_ENUM_RANGE( PxSphericalJoint_LimitCone, 100 ),
DEFINE_ENUM_RANGE( PxJoint_LocalPose, 2 )
};
};
}
}
#endif
| 2,737 | C | 41.123076 | 187 | 0.765802 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtExtensions.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 "common/PxMetaData.h"
#include "common/PxSerializer.h"
#include "extensions/PxExtensionsAPI.h"
#include "extensions/PxRepXSerializer.h"
#include "ExtDistanceJoint.h"
#include "ExtD6Joint.h"
#include "ExtFixedJoint.h"
#include "ExtPrismaticJoint.h"
#include "ExtRevoluteJoint.h"
#include "ExtSphericalJoint.h"
#include "ExtSerialization.h"
#include "SnRepXCoreSerializer.h"
#include "SnJointRepXSerializer.h"
#include "PxExtensionMetaDataObjects.h"
#if PX_SUPPORT_PVD
#include "ExtPvd.h"
#include "PxPvdDataStream.h"
#include "PxPvdClient.h"
#include "PsPvd.h"
#endif
#if PX_SUPPORT_OMNI_PVD
# include "omnipvd/PxOmniPvd.h"
# include "omnipvd/OmniPvdPxExtensionsSampler.h"
#endif
using namespace physx;
using namespace physx::pvdsdk;
#if PX_SUPPORT_PVD
struct JointConnectionHandler : public PvdClient
{
JointConnectionHandler() : mPvd(NULL),mConnected(false){}
PvdDataStream* getDataStream()
{
return NULL;
}
void onPvdConnected()
{
PvdDataStream* stream = PvdDataStream::create(mPvd);
if(stream)
{
mConnected = true;
Ext::Pvd::sendClassDescriptions(*stream);
stream->release();
}
}
bool isConnected() const
{
return mConnected;
}
void onPvdDisconnected()
{
mConnected = false;
}
void flush()
{
}
PsPvd* mPvd;
bool mConnected;
};
static JointConnectionHandler gPvdHandler;
#endif
bool PxInitExtensions(PxPhysics& physics, PxPvd* pvd)
{
PX_ASSERT(&physics.getFoundation() == &PxGetFoundation());
PX_UNUSED(physics);
PX_UNUSED(pvd);
PxIncFoundationRefCount();
#if PX_SUPPORT_PVD
if(pvd)
{
gPvdHandler.mPvd = static_cast<PsPvd*>(pvd);
gPvdHandler.mPvd->addClient(&gPvdHandler);
}
#endif
#if PX_SUPPORT_OMNI_PVD
if (physics.getOmniPvd() && physics.getOmniPvd()->getWriter())
{
if (OmniPvdPxExtensionsSampler::createInstance())
{
OmniPvdPxExtensionsSampler::getInstance()->setOmniPvdInstance(physics.getOmniPvd());
OmniPvdPxExtensionsSampler::getInstance()->registerClasses();
}
}
#endif
return true;
}
static PxArray<PxSceneQuerySystem*>* gExternalSQ = NULL;
void addExternalSQ(PxSceneQuerySystem* added)
{
if(!gExternalSQ)
gExternalSQ = new PxArray<PxSceneQuerySystem*>;
gExternalSQ->pushBack(added);
}
void removeExternalSQ(PxSceneQuerySystem* removed)
{
if(gExternalSQ)
{
const PxU32 nb = gExternalSQ->size();
for(PxU32 i=0;i<nb;i++)
{
PxSceneQuerySystem* sq = (*gExternalSQ)[i];
if(sq==removed)
{
gExternalSQ->replaceWithLast(i);
return;
}
}
}
}
static void releaseExternalSQ()
{
if(gExternalSQ)
{
PxArray<PxSceneQuerySystem*>* copy = gExternalSQ;
gExternalSQ = NULL;
const PxU32 nb = copy->size();
for(PxU32 i=0;i<nb;i++)
{
PxSceneQuerySystem* sq = (*copy)[i];
sq->release();
}
PX_DELETE(copy);
}
}
void PxCloseExtensions(void)
{
releaseExternalSQ();
PxDecFoundationRefCount();
#if PX_SUPPORT_PVD
if(gPvdHandler.mConnected)
{
PX_ASSERT(gPvdHandler.mPvd);
gPvdHandler.mPvd->removeClient(&gPvdHandler);
gPvdHandler.mPvd = NULL;
}
#endif
#if PX_SUPPORT_OMNI_PVD
if (OmniPvdPxExtensionsSampler::getInstance())
{
OmniPvdPxExtensionsSampler::destroyInstance();
}
#endif
}
void Ext::RegisterExtensionsSerializers(PxSerializationRegistry& sr)
{
//for repx serialization
sr.registerRepXSerializer(PxConcreteType::eMATERIAL, PX_NEW_REPX_SERIALIZER( PxMaterialRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eSHAPE, PX_NEW_REPX_SERIALIZER( PxShapeRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH33, PX_NEW_REPX_SERIALIZER( PxBVH33TriangleMeshRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH34, PX_NEW_REPX_SERIALIZER( PxBVH34TriangleMeshRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eHEIGHTFIELD, PX_NEW_REPX_SERIALIZER( PxHeightFieldRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eCONVEX_MESH, PX_NEW_REPX_SERIALIZER( PxConvexMeshRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eRIGID_STATIC, PX_NEW_REPX_SERIALIZER( PxRigidStaticRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eRIGID_DYNAMIC, PX_NEW_REPX_SERIALIZER( PxRigidDynamicRepXSerializer ));
sr.registerRepXSerializer(PxConcreteType::eARTICULATION_REDUCED_COORDINATE, PX_NEW_REPX_SERIALIZER( PxArticulationReducedCoordinateRepXSerializer));
sr.registerRepXSerializer(PxConcreteType::eAGGREGATE, PX_NEW_REPX_SERIALIZER( PxAggregateRepXSerializer ));
sr.registerRepXSerializer(PxJointConcreteType::eFIXED, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxFixedJoint> ));
sr.registerRepXSerializer(PxJointConcreteType::eDISTANCE, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxDistanceJoint> ));
sr.registerRepXSerializer(PxJointConcreteType::eD6, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxD6Joint> ));
sr.registerRepXSerializer(PxJointConcreteType::ePRISMATIC, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxPrismaticJoint> ));
sr.registerRepXSerializer(PxJointConcreteType::eREVOLUTE, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxRevoluteJoint> ));
sr.registerRepXSerializer(PxJointConcreteType::eSPHERICAL, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxSphericalJoint> ));
//for binary serialization
sr.registerSerializer(PxJointConcreteType::eFIXED, PX_NEW_SERIALIZER_ADAPTER( FixedJoint ));
sr.registerSerializer(PxJointConcreteType::eDISTANCE, PX_NEW_SERIALIZER_ADAPTER( DistanceJoint ));
sr.registerSerializer(PxJointConcreteType::eD6, PX_NEW_SERIALIZER_ADAPTER( D6Joint) );
sr.registerSerializer(PxJointConcreteType::ePRISMATIC, PX_NEW_SERIALIZER_ADAPTER( PrismaticJoint ));
sr.registerSerializer(PxJointConcreteType::eREVOLUTE, PX_NEW_SERIALIZER_ADAPTER( RevoluteJoint ));
sr.registerSerializer(PxJointConcreteType::eSPHERICAL, PX_NEW_SERIALIZER_ADAPTER( SphericalJoint ));
}
void Ext::UnregisterExtensionsSerializers(PxSerializationRegistry& sr)
{
PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eFIXED));
PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eDISTANCE));
PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eD6 ));
PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::ePRISMATIC));
PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eREVOLUTE));
PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eSPHERICAL));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eMATERIAL));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eSHAPE));
// PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eTRIANGLE_MESH));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH33));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH34));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eHEIGHTFIELD));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eCONVEX_MESH));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eRIGID_STATIC));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eRIGID_DYNAMIC));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eARTICULATION_REDUCED_COORDINATE));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eAGGREGATE));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eFIXED));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eDISTANCE));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eD6));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::ePRISMATIC));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eREVOLUTE));
PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eSPHERICAL));
}
| 9,731 | C++ | 37.015625 | 149 | 0.781215 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSoftBodyExt.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 "extensions/PxSoftBodyExt.h"
#include "extensions/PxTetMakerExt.h"
#include "GuTetrahedronMesh.h"
#include "cooking/PxCooking.h"
#include "PxPhysics.h"
#include "extensions/PxRemeshingExt.h"
#include "cudamanager/PxCudaContextManager.h"
#include "cudamanager/PxCudaContext.h"
using namespace physx;
using namespace Cm;
//Computes the volume of the simulation mesh defined as the sum of the volumes of all tetrahedra
static PxReal computeSimulationMeshVolume(PxSoftBody& sb, PxVec4* simPositions)
{
const PxU32 numTetsGM = sb.getSimulationMesh()->getNbTetrahedrons();
const PxU32* tetPtr32 = reinterpret_cast<const PxU32*>(sb.getSimulationMesh()->getTetrahedrons());
const PxU16* tetPtr16 = reinterpret_cast<const PxU16*>(sb.getSimulationMesh()->getTetrahedrons());
const bool sixteenBit = sb.getSimulationMesh()->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES;
PxReal volume = 0;
for (PxU32 i = 0; i < numTetsGM; ++i)
{
PxVec4& x0 = simPositions[sixteenBit ? tetPtr16[4 * i] : tetPtr32[4 * i]];
PxVec4& x1 = simPositions[sixteenBit ? tetPtr16[4 * i + 1] : tetPtr32[4 * i + 1]];
PxVec4& x2 = simPositions[sixteenBit ? tetPtr16[4 * i + 2] : tetPtr32[4 * i + 2]];
PxVec4& x3 = simPositions[sixteenBit ? tetPtr16[4 * i + 3] : tetPtr32[4 * i + 3]];
const PxVec3 u1 = x1.getXYZ() - x0.getXYZ();
const PxVec3 u2 = x2.getXYZ() - x0.getXYZ();
const PxVec3 u3 = x3.getXYZ() - x0.getXYZ();
PxMat33 Q = PxMat33(u1, u2, u3);
const PxReal det = Q.getDeterminant();
volume += det;
}
volume /= 6.0f;
return volume;
}
//Recomputes the volume associated with a vertex. Every tetrahedron distributes a quarter of its volume to
//each vertex it is connected to. Finally the volume stored for every vertex is inverted.
static void updateNodeInverseVolumes(PxSoftBody& sb, PxVec4* simPositions)
{
const PxU32 numVertsGM = sb.getSimulationMesh()->getNbVertices();
const PxU32 numTetsGM = sb.getSimulationMesh()->getNbTetrahedrons();
const PxU32* tetPtr32 = reinterpret_cast<const PxU32*>(sb.getSimulationMesh()->getTetrahedrons());
const PxU16* tetPtr16 = reinterpret_cast<const PxU16*>(sb.getSimulationMesh()->getTetrahedrons());
const bool sixteenBit = sb.getSimulationMesh()->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES;
for (PxU32 i = 0; i < numVertsGM; ++i)
simPositions[i].w = 0.0f;
for (PxU32 i = 0; i < numTetsGM; ++i)
{
PxVec4& x0 = simPositions[sixteenBit ? tetPtr16[4 * i] : tetPtr32[4 * i]];
PxVec4& x1 = simPositions[sixteenBit ? tetPtr16[4 * i + 1] : tetPtr32[4 * i + 1]];
PxVec4& x2 = simPositions[sixteenBit ? tetPtr16[4 * i + 2] : tetPtr32[4 * i + 2]];
PxVec4& x3 = simPositions[sixteenBit ? tetPtr16[4 * i + 3] : tetPtr32[4 * i + 3]];
const PxVec3 u1 = x1.getXYZ() - x0.getXYZ();
const PxVec3 u2 = x2.getXYZ() - x0.getXYZ();
const PxVec3 u3 = x3.getXYZ() - x0.getXYZ();
PxMat33 Q = PxMat33(u1, u2, u3);
//det should be positive
const PxReal det = Q.getDeterminant();
if (det <= 1.e-9f)
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "updateNodeInverseVolumes(): tetrahedron is degenerate or inverted");
//Distribute one quarter of the volume to each vertex the tetrahedron is connected to
const PxReal volume = det / 6.0f;
x0.w += 0.25f * volume;
x1.w += 0.25f * volume;
x2.w += 0.25f * volume;
x3.w += 0.25f * volume;
}
//Invert the volumes stored per vertex and copy it to the velocity buffer
for (PxU32 i = 0; i < numVertsGM; ++i)
{
if (simPositions[i].w > 0)
{
simPositions[i].w = 1.0f / simPositions[i].w;
}
}
}
void PxSoftBodyExt::updateMass(PxSoftBody& sb, const PxReal density, const PxReal maxInvMassRatio, PxVec4* simPositionsPinned)
{
//Inverse volumes are recomputed to ensure that multiple subsequent calls of this method lead to correct results
updateNodeInverseVolumes(sb, simPositionsPinned);
const PxU32 numVertsGM = sb.getSimulationMesh()->getNbVertices();
PxReal minInvMass = PX_MAX_F32, maxInvMass = 0.f;
for (PxU32 i = 0; i < numVertsGM; ++i)
{
const PxVec4& vert = simPositionsPinned[i];
PxReal invMass = vert.w;
invMass = invMass / (density);
minInvMass = invMass > 0.f ? PxMin(invMass, minInvMass) : minInvMass;
maxInvMass = PxMax(invMass, maxInvMass);
simPositionsPinned[i] = PxVec4(vert.x, vert.y, vert.z, invMass);
}
if (minInvMass != PX_MAX_F32)
{
const PxReal ratio = maxInvMass / minInvMass;
if (ratio > maxInvMassRatio)
{
//Clamp the upper limit...
maxInvMass = minInvMass * maxInvMassRatio;
for (PxU32 i = 0; i < numVertsGM; ++i)
{
PxVec4& posInvMass = simPositionsPinned[i];
posInvMass.w = PxMin(posInvMass.w, maxInvMass);
}
}
}
}
void PxSoftBodyExt::setMass(PxSoftBody& sb, const PxReal mass, const PxReal maxInvMassRatio, PxVec4* simPositionsPinned)
{
//Compute the density such that density times volume is equal to the desired mass
updateMass(sb, mass / computeSimulationMeshVolume(sb, simPositionsPinned), maxInvMassRatio, simPositionsPinned);
}
void PxSoftBodyExt::transform(PxSoftBody& sb, const PxTransform& transform, const PxReal scale, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned)
{
const PxU32 numVertsGM = sb.getSimulationMesh()->getNbVertices();
const PxU32 numVerts = sb.getCollisionMesh()->getNbVertices();
for (PxU32 i = 0; i < numVertsGM; ++i)
{
const PxVec4 tpInvMass = simPositionsPinned[i];
const PxReal invMass = tpInvMass.w;
PxVec3 vert = PxVec3(tpInvMass.x * scale, tpInvMass.y * scale, tpInvMass.z * scale);
//Transform the vertex position and keep the inverse mass
vert = transform.transform(vert);
simPositionsPinned[i] = PxVec4(vert.x, vert.y, vert.z, invMass);
PxVec4 vel = simVelocitiesPinned[i];
PxVec3 v = PxVec3(vel.x * scale, vel.y * scale, vel.z * scale);
//Velocities are translation invariant, therefore only the direction needs to get adjusted.
//The inverse mass is stored as well to optimize memory access on the GPU
v = transform.rotate(v);
simVelocitiesPinned[i] = PxVec4(v.x, v.y, v.z, invMass);
}
for (PxU32 i = 0; i < numVerts; ++i)
{
restPositionsPinned[i] = PxVec4(restPositionsPinned[i].x*scale, restPositionsPinned[i].y*scale, restPositionsPinned[i].z*scale, 1.f);
const PxVec4 tpInvMass = collPositionsPinned[i];
PxVec3 vert = PxVec3(tpInvMass.x * scale, tpInvMass.y * scale, tpInvMass.z * scale);
vert = transform.transform(vert);
collPositionsPinned[i] = PxVec4(vert.x, vert.y, vert.z, tpInvMass.w);
}
PxMat33* tetraRestPosesGM = static_cast<Gu::SoftBodyAuxData*>(sb.getSoftBodyAuxData())->getGridModelRestPosesFast(); // reinterpret_cast<PxMat33*>(simMeshData->softBodyAuxData.getGridModelRestPosesFast());
const PxU32 nbTetraGM = sb.getSimulationMesh()->getNbTetrahedrons();
const PxReal invScale = 1.0f / scale;
for (PxU32 i = 0; i < nbTetraGM; ++i)
{
PxMat33& m = tetraRestPosesGM[i];
//Scale the rest pose
m.column0 = m.column0 * invScale;
m.column1 = m.column1 * invScale;
m.column2 = m.column2 * invScale;
//The rest pose is translation invariant, it only needs be rotated
PxVec3 row0 = transform.rotateInv(PxVec3(m.column0.x, m.column1.x, m.column2.x));
PxVec3 row1 = transform.rotateInv(PxVec3(m.column0.y, m.column1.y, m.column2.y));
PxVec3 row2 = transform.rotateInv(PxVec3(m.column0.z, m.column1.z, m.column2.z));
m.column0 = PxVec3(row0.x, row1.x, row2.x);
m.column1 = PxVec3(row0.y, row1.y, row2.y);
m.column2 = PxVec3(row0.z, row1.z, row2.z);
}
PxMat33* tetraRestPoses = static_cast<Gu::SoftBodyAuxData*>(sb.getSoftBodyAuxData())->getRestPosesFast(); // reinterpret_cast<PxMat33*>(simMeshData->softBodyAuxData.getGridModelRestPosesFast());
const PxU32 nbTetra = sb.getCollisionMesh()->getNbTetrahedrons();
for (PxU32 i = 0; i < nbTetra; ++i)
{
PxMat33& m = tetraRestPoses[i];
//Scale the rest pose
m.column0 = m.column0 * invScale;
m.column1 = m.column1 * invScale;
m.column2 = m.column2 * invScale;
//The rest pose is translation invariant, it only needs be rotated
PxVec3 row0 = transform.rotateInv(PxVec3(m.column0.x, m.column1.x, m.column2.x));
PxVec3 row1 = transform.rotateInv(PxVec3(m.column0.y, m.column1.y, m.column2.y));
PxVec3 row2 = transform.rotateInv(PxVec3(m.column0.z, m.column1.z, m.column2.z));
m.column0 = PxVec3(row0.x, row1.x, row2.x);
m.column1 = PxVec3(row0.y, row1.y, row2.y);
m.column2 = PxVec3(row0.z, row1.z, row2.z);
}
}
void PxSoftBodyExt::updateEmbeddedCollisionMesh(PxSoftBody& sb, PxVec4* simPositionsPinned, PxVec4* collPositionsPinned)
{
Gu::SoftBodyAuxData* softBodyAuxData = static_cast<Gu::SoftBodyAuxData*>(sb.getSoftBodyAuxData());
const PxU32* remapTable = softBodyAuxData->mVertsRemapInGridModel;
PxReal* barycentricCoordinates = softBodyAuxData->mVertsBarycentricInGridModel;
PxTetrahedronMesh* simMesh = sb.getSimulationMesh();
const void* tets = simMesh->getTetrahedrons();
const PxU32* tets32 = static_cast<const PxU32*>(tets);
const PxU16* tets16 = static_cast<const PxU16*>(tets);
bool sixteenBit = simMesh->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES;
const PxU32 numVerts = sb.getCollisionMesh()->getNbVertices();
for (PxU32 i = 0; i < numVerts; ++i)
{
//The tetrahedra are ordered differently on the GPU, therefore the index must be taken from the remap table
const PxU32 tetrahedronIdx = remapTable[i];
const PxVec4 p0 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx] : tets32[4 * tetrahedronIdx]];
const PxVec4 p1 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx + 1] : tets32[4 * tetrahedronIdx + 1]];
const PxVec4 p2 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx + 2] : tets32[4 * tetrahedronIdx + 2]];
const PxVec4 p3 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx + 3] : tets32[4 * tetrahedronIdx + 3]];
const PxReal* barycentric = &barycentricCoordinates[4*i];
//Compute the embedded position as a weigted sum of vertices from the simulation mesh
//This ensures that all tranformations and scale changes applied to the simulation mesh get transferred
//to the collision mesh
collPositionsPinned[i] = p0 * barycentric[0] + p1 * barycentric[1] + p2 * barycentric[2] + p3 * barycentric[3];
collPositionsPinned[i].w = 1.0f;
}
}
void PxSoftBodyExt::commit(PxSoftBody& sb, PxSoftBodyDataFlags flags, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned, CUstream stream)
{
copyToDevice(sb, flags, simPositionsPinned, simVelocitiesPinned, collPositionsPinned, restPositionsPinned, stream);
}
void PxSoftBodyExt::copyToDevice(PxSoftBody& sb, PxSoftBodyDataFlags flags, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned, CUstream stream)
{
//Updating the collision mesh's vertices ensures that simulation mesh and collision mesh are
//represented in the same coordinate system and the same scale
updateEmbeddedCollisionMesh(sb, simPositionsPinned, collPositionsPinned);
#if PX_SUPPORT_GPU_PHYSX
PxScopedCudaLock _lock(*sb.getCudaContextManager());
PxCudaContext* ctx = sb.getCudaContextManager()->getCudaContext();
if (flags & PxSoftBodyDataFlag::ePOSITION_INVMASS && collPositionsPinned)
ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getPositionInvMassBufferD()), collPositionsPinned, sb.getCollisionMesh()->getNbVertices() * sizeof(PxVec4), stream);
if (flags & PxSoftBodyDataFlag::eREST_POSITION_INVMASS && restPositionsPinned)
ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getRestPositionBufferD()), restPositionsPinned, sb.getCollisionMesh()->getNbVertices() * sizeof(PxVec4), stream);
if (flags & PxSoftBodyDataFlag::eSIM_POSITION_INVMASS && simPositionsPinned)
ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getSimPositionInvMassBufferD()), simPositionsPinned, sb.getSimulationMesh()->getNbVertices() * sizeof(PxVec4), stream);
if (flags & PxSoftBodyDataFlag::eSIM_VELOCITY && simVelocitiesPinned)
ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getSimVelocityBufferD()), simVelocitiesPinned, sb.getSimulationMesh()->getNbVertices() * sizeof(PxVec4), stream);
// we need to synchronize if the stream is the default argument.
if (stream == 0)
{
ctx->streamSynchronize(stream);
}
#else
PX_UNUSED(restPositionsPinned);
PX_UNUSED(simVelocitiesPinned);
PX_UNUSED(stream);
#endif
sb.markDirty(flags);
}
PxSoftBodyMesh* PxSoftBodyExt::createSoftBodyMesh(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, PxU32 numVoxelsAlongLongestAABBAxis, PxInsertionCallback& insertionCallback, const bool validate)
{
//Compute collision mesh
physx::PxArray<physx::PxVec3> collisionMeshVertices;
physx::PxArray<physx::PxU32> collisionMeshIndices;
if (!PxTetMaker::createConformingTetrahedronMesh(surfaceMesh, collisionMeshVertices, collisionMeshIndices, validate))
return NULL;
PxTetrahedronMeshDesc meshDesc(collisionMeshVertices, collisionMeshIndices);
//Compute simulation mesh
physx::PxArray<physx::PxI32> vertexToTet;
vertexToTet.resize(meshDesc.points.count);
physx::PxArray<physx::PxVec3> simulationMeshVertices;
physx::PxArray<physx::PxU32> simulationMeshIndices;
PxTetMaker::createVoxelTetrahedronMesh(meshDesc, numVoxelsAlongLongestAABBAxis, simulationMeshVertices, simulationMeshIndices, vertexToTet.begin());
PxTetrahedronMeshDesc simMeshDesc(simulationMeshVertices, simulationMeshIndices);
PxSoftBodySimulationDataDesc simDesc(vertexToTet);
physx::PxSoftBodyMesh* softBodyMesh = PxCreateSoftBodyMesh(params, simMeshDesc, meshDesc, simDesc, insertionCallback);
return softBodyMesh;
}
PxSoftBodyMesh* PxSoftBodyExt::createSoftBodyMeshNoVoxels(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, PxInsertionCallback& insertionCallback, PxReal maxWeightRatioInTet, const bool validate)
{
PxCookingParams p = params;
p.maxWeightRatioInTet = maxWeightRatioInTet;
physx::PxArray<physx::PxVec3> collisionMeshVertices;
physx::PxArray<physx::PxU32> collisionMeshIndices;
if (!PxTetMaker::createConformingTetrahedronMesh(surfaceMesh, collisionMeshVertices, collisionMeshIndices, validate))
return NULL;
PxTetrahedronMeshDesc meshDesc(collisionMeshVertices, collisionMeshIndices);
PxSoftBodySimulationDataDesc simDesc;
physx::PxSoftBodyMesh* softBodyMesh = PxCreateSoftBodyMesh(p, meshDesc, meshDesc, simDesc, insertionCallback);
return softBodyMesh;
}
PxSoftBody* PxSoftBodyExt::createSoftBodyFromMesh(PxSoftBodyMesh* softBodyMesh, const PxTransform& transform, const PxFEMSoftBodyMaterial& material, PxCudaContextManager& cudaContextManager,
PxReal density, PxU32 solverIterationCount, const PxFEMParameters& femParams, PxReal scale)
{
PxSoftBody* softBody = PxGetPhysics().createSoftBody(cudaContextManager);
if (softBody)
{
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE;
PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh());
PxFEMSoftBodyMaterial* materialPointer = const_cast<PxFEMSoftBodyMaterial*>(&material);
PxShape* shape = PxGetPhysics().createShape(geometry, &materialPointer, 1, true, shapeFlags);
if (shape)
{
softBody->attachShape(*shape);
}
softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData());
PxVec4* simPositionInvMassPinned;
PxVec4* simVelocityPinned;
PxVec4* collPositionInvMassPinned;
PxVec4* restPositionPinned;
PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, &cudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned);
const PxReal maxInvMassRatio = 50.f;
softBody->setParameter(femParams);
softBody->setSolverIterationCounts(solverIterationCount);
PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned);
PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned);
PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned);
#if PX_SUPPORT_GPU_PHYSX
PxCudaContextManager* mgr = &cudaContextManager;
PX_PINNED_HOST_FREE(mgr, simPositionInvMassPinned);
PX_PINNED_HOST_FREE(mgr, simVelocityPinned);
PX_PINNED_HOST_FREE(mgr, collPositionInvMassPinned);
PX_PINNED_HOST_FREE(mgr, restPositionPinned)
#endif
}
return softBody;
}
PxSoftBody* PxSoftBodyExt::createSoftBodyBox(const PxTransform& transform, const PxVec3& boxDimensions, const PxFEMSoftBodyMaterial& material,
PxCudaContextManager& cudaContextManager, PxReal maxEdgeLength, PxReal density, PxU32 solverIterationCount, const PxFEMParameters& femParams, PxU32 numVoxelsAlongLongestAABBAxis, PxReal scale)
{
PxArray<PxVec3> triVerts;
triVerts.reserve(8);
triVerts.pushBack(PxVec3(0.5f, -0.5f, -0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(0.5f, -0.5f, 0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(-0.5f, -0.5f, 0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(-0.5f, -0.5f, -0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(0.5f, 0.5f, -0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(0.5f, 0.5f, 0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(-0.5f, 0.5f, 0.5f).multiply(boxDimensions));
triVerts.pushBack(PxVec3(-0.5f, 0.5f, -0.5f).multiply(boxDimensions));
PxArray<PxU32> triIndices;
triIndices.reserve(12 * 3);
triIndices.pushBack(1); triIndices.pushBack(2); triIndices.pushBack(3);
triIndices.pushBack(7); triIndices.pushBack(6); triIndices.pushBack(5);
triIndices.pushBack(4); triIndices.pushBack(5); triIndices.pushBack(1);
triIndices.pushBack(5); triIndices.pushBack(6); triIndices.pushBack(2);
triIndices.pushBack(2); triIndices.pushBack(6); triIndices.pushBack(7);
triIndices.pushBack(0); triIndices.pushBack(3); triIndices.pushBack(7);
triIndices.pushBack(0); triIndices.pushBack(1); triIndices.pushBack(3);
triIndices.pushBack(4); triIndices.pushBack(7); triIndices.pushBack(5);
triIndices.pushBack(0); triIndices.pushBack(4); triIndices.pushBack(1);
triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(2);
triIndices.pushBack(3); triIndices.pushBack(2); triIndices.pushBack(7);
triIndices.pushBack(4); triIndices.pushBack(0); triIndices.pushBack(7);
if (maxEdgeLength > 0.0f)
PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 3);
PxSimpleTriangleMesh surfaceMesh;
surfaceMesh.points.count = triVerts.size();
surfaceMesh.points.data = triVerts.begin();
surfaceMesh.triangles.count = triIndices.size() / 3;
surfaceMesh.triangles.data = triIndices.begin();
PxTolerancesScale tolerancesScale;
PxCookingParams params(tolerancesScale);
params.meshWeldTolerance = 0.001f;
params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES);
params.buildTriangleAdjacencies = false;
params.buildGPUData = true;
params.midphaseDesc = PxMeshMidPhase::eBVH34;
PxSoftBodyMesh* softBodyMesh = createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, PxGetPhysics().getPhysicsInsertionCallback());
return createSoftBodyFromMesh(softBodyMesh, transform, material, cudaContextManager, density, solverIterationCount, femParams, scale);
}
void PxSoftBodyExt::allocateAndInitializeHostMirror(PxSoftBody& softBody, PxCudaContextManager* cudaContextManager, PxVec4*& simPositionInvMassPinned, PxVec4*& simVelocityPinned, PxVec4*& collPositionInvMassPinned, PxVec4*& restPositionPinned)
{
PX_ASSERT(softBody.getCollisionMesh() != NULL);
PX_ASSERT(softBody.getSimulationMesh() != NULL);
PxU32 nbCollVerts = softBody.getCollisionMesh()->getNbVertices();
PxU32 nbSimVerts = softBody.getSimulationMesh()->getNbVertices();
#if PX_SUPPORT_GPU_PHYSX
simPositionInvMassPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbSimVerts);
simVelocityPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbSimVerts);
collPositionInvMassPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbCollVerts);
restPositionPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbCollVerts);
#else
PX_UNUSED(cudaContextManager);
#endif
// write positionInvMass into CPU part.
const PxVec3* positions = softBody.getCollisionMesh()->getVertices();
for (PxU32 i = 0; i < nbCollVerts; ++i)
{
PxVec3 vert = positions[i];
collPositionInvMassPinned[i] = PxVec4(vert, 1.f);
restPositionPinned[i] = PxVec4(vert, 1.f);
}
// write sim mesh part.
PxSoftBodyAuxData* s = softBody.getSoftBodyAuxData();
PxReal* invMassGM = s->getGridModelInvMass();
const PxVec3* simPositions = softBody.getSimulationMesh()->getVertices();
for (PxU32 i = 0; i < nbSimVerts; ++i)
{
PxReal invMass = invMassGM ? invMassGM[i] : 1.f;
simPositionInvMassPinned[i] = PxVec4(simPositions[i], invMass);
simVelocityPinned[i] = PxVec4(0.f, 0.f, 0.f, invMass);
}
}
struct InternalSoftBodyState
{
PxVec4* mVertices;
PxArray<PxReal> mInvMasses;
const PxU32* mTetrahedra;
PxArray<PxMat33> mInvRestPose;
PxArray<PxVec3> mPrevPos;
InternalSoftBodyState(const PxVec4* verticesOriginal, PxVec4* verticesDeformed, PxU32 nbVertices, const PxU32* tetrahedra, PxU32 nbTetraheda, const bool* vertexIsFixed) :
mVertices(verticesDeformed), mTetrahedra(tetrahedra)
{
PxReal density = 1.0f;
mInvMasses.resize(nbVertices, 0.0f);
mInvRestPose.resize(nbTetraheda, PxMat33(PxZero));
for (PxU32 i = 0; i < nbTetraheda; i++)
{
const PxU32* t = &mTetrahedra[4 * i];
const PxVec3 a = verticesOriginal[t[0]].getXYZ();
PxMat33 ir(verticesOriginal[t[1]].getXYZ() - a, verticesOriginal[t[2]].getXYZ() - a, verticesOriginal[t[3]].getXYZ() - a);
PxReal volume = ir.getDeterminant() / 6.0f;
if (volume > 1e-8f)
mInvRestPose[i] = ir.getInverse();
PxReal m = 0.25f * volume * density;
mInvMasses[t[0]] += m;
mInvMasses[t[1]] += m;
mInvMasses[t[2]] += m;
mInvMasses[t[3]] += m;
}
for (PxU32 i = 0; i < nbVertices; i++)
{
bool fixed = vertexIsFixed ? vertexIsFixed[i] : verticesOriginal[i].w == 0.0f;
if (mInvMasses[i] != 0.0f && !fixed)
mInvMasses[i] = 1.0f / mInvMasses[i];
else
mInvMasses[i] = 0.0f;
}
mPrevPos.resize(nbVertices);
for (PxU32 i = 0; i < mPrevPos.size(); ++i)
mPrevPos[i] = mVertices[i].getXYZ();
}
void applyDelta()
{
for (PxU32 i = 0; i < mPrevPos.size(); ++i)
{
PxVec3 delta = mVertices[i].getXYZ() - mPrevPos[i];
mPrevPos[i] = mVertices[i].getXYZ();
mVertices[i] += PxVec4(0.99f * delta, 0.0f);
}
}
PX_FORCE_INLINE void applyToElem(PxU32 elemNr, PxReal C, PxReal compliance, const PxVec3& g1, const PxVec3& g2, const PxVec3& g3, const PxVec4& invMasses)
{
if (C == 0.0f)
return;
const PxVec3 g0 = -g1 - g2 - g3;
const PxU32* t = &mTetrahedra[4 * elemNr];
const PxReal w = g0.magnitudeSquared() * invMasses.x + g1.magnitudeSquared() * invMasses.y + g2.magnitudeSquared() * invMasses.z + g3.magnitudeSquared() * invMasses.w;
if (w == 0.0f)
return;
const PxReal alpha = compliance;
const PxReal dlambda = -C / (w + alpha);
if (invMasses.x != 0.0f)
mVertices[t[0]] += PxVec4(g0 * dlambda * invMasses.x, 0.0f);
if (invMasses.y != 0.0f)
mVertices[t[1]] += PxVec4(g1 * dlambda * invMasses.y, 0.0f);
if (invMasses.z != 0.0f)
mVertices[t[2]] += PxVec4(g2 * dlambda * invMasses.z, 0.0f);
if (invMasses.w != 0.0f)
mVertices[t[3]] += PxVec4(g3 * dlambda * invMasses.w, 0.0f);
}
void solveElem(PxU32 elemNr)
{
const PxMat33& ir = mInvRestPose[elemNr];
if (ir == PxMat33(PxZero))
return;
const PxU32* tet = &mTetrahedra[4 * elemNr];
PxVec4 invMasses(mInvMasses[tet[0]], mInvMasses[tet[1]], mInvMasses[tet[2]], mInvMasses[tet[3]]);
PxMat33 P;
P.column0 = mVertices[tet[1]].getXYZ() - mVertices[tet[0]].getXYZ();
P.column1 = mVertices[tet[2]].getXYZ() - mVertices[tet[0]].getXYZ();
P.column2 = mVertices[tet[3]].getXYZ() - mVertices[tet[0]].getXYZ();
PxMat33 F = P * ir;
PxVec3 g1 = F.column0 * 2.0f * ir.column0.x + F.column1 * 2.0f * ir.column1.x + F.column2 * 2.0f * ir.column2.x;
PxVec3 g2 = F.column0 * 2.0f * ir.column0.y + F.column1 * 2.0f * ir.column1.y + F.column2 * 2.0f * ir.column2.y;
PxVec3 g3 = F.column0 * 2.0f * ir.column0.z + F.column1 * 2.0f * ir.column1.z + F.column2 * 2.0f * ir.column2.z;
PxReal C = F.column0.magnitudeSquared() + F.column1.magnitudeSquared() + F.column2.magnitudeSquared() - 3.0f;
applyToElem(elemNr, C, 0.0f, g1, g2, g3, invMasses);
P.column0 = mVertices[tet[1]].getXYZ() - mVertices[tet[0]].getXYZ();
P.column1 = mVertices[tet[2]].getXYZ() - mVertices[tet[0]].getXYZ();
P.column2 = mVertices[tet[3]].getXYZ() - mVertices[tet[0]].getXYZ();
F = P * ir;
PxMat33& dF = P; //Re-use memory, possible since P is not used anymore afterwards
dF.column0 = F.column1.cross(F.column2);
dF.column1 = F.column2.cross(F.column0);
dF.column2 = F.column0.cross(F.column1);
g1 = dF.column0 * ir.column0.x + dF.column1 * ir.column1.x + dF.column2 * ir.column2.x;
g2 = dF.column0 * ir.column0.y + dF.column1 * ir.column1.y + dF.column2 * ir.column2.y;
g3 = dF.column0 * ir.column0.z + dF.column1 * ir.column1.z + dF.column2 * ir.column2.z;
C = F.getDeterminant() - 1.0f;
applyToElem(elemNr, C, 0.0f, g1, g2, g3, invMasses);
}
};
void PxSoftBodyExt::relaxSoftBodyMesh(const PxVec4* verticesOriginal, PxVec4* verticesDeformed, PxU32 nbVertices, const PxU32* tetrahedra, PxU32 nbTetraheda, const bool* vertexIsFixed, PxU32 numIterations)
{
InternalSoftBodyState state(verticesOriginal, verticesDeformed, nbVertices, tetrahedra, nbTetraheda, vertexIsFixed);
for (PxU32 iter = 0; iter < numIterations; ++iter)
{
state.applyDelta();
for (PxU32 i = 0; i < nbTetraheda; ++i)
state.solveElem(i);
}
return;
}
| 27,653 | C++ | 42.895238 | 243 | 0.74397 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultSimulationFilterShader.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 "extensions/PxDefaultSimulationFilterShader.h"
#include "PxRigidActor.h"
#include "PxShape.h"
#include "PxSoftBody.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxInlineArray.h"
using namespace physx;
namespace
{
#define GROUP_SIZE 32
struct PxCollisionBitMap
{
PX_INLINE PxCollisionBitMap() : enable(true) {}
bool operator()() const { return enable; }
bool& operator= (const bool &v) { enable = v; return enable; }
private:
bool enable;
};
PxCollisionBitMap gCollisionTable[GROUP_SIZE][GROUP_SIZE];
PxFilterOp::Enum gFilterOps[3] = { PxFilterOp::PX_FILTEROP_AND, PxFilterOp::PX_FILTEROP_AND, PxFilterOp::PX_FILTEROP_AND };
PxGroupsMask gFilterConstants[2];
bool gFilterBool = false;
static void gAND(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(mask0.bits0 & mask1.bits0);
results.bits1 = PxU16(mask0.bits1 & mask1.bits1);
results.bits2 = PxU16(mask0.bits2 & mask1.bits2);
results.bits3 = PxU16(mask0.bits3 & mask1.bits3);
}
static void gOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(mask0.bits0 | mask1.bits0);
results.bits1 = PxU16(mask0.bits1 | mask1.bits1);
results.bits2 = PxU16(mask0.bits2 | mask1.bits2);
results.bits3 = PxU16(mask0.bits3 | mask1.bits3);
}
static void gXOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(mask0.bits0 ^ mask1.bits0);
results.bits1 = PxU16(mask0.bits1 ^ mask1.bits1);
results.bits2 = PxU16(mask0.bits2 ^ mask1.bits2);
results.bits3 = PxU16(mask0.bits3 ^ mask1.bits3);
}
static void gNAND(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(~(mask0.bits0 & mask1.bits0));
results.bits1 = PxU16(~(mask0.bits1 & mask1.bits1));
results.bits2 = PxU16(~(mask0.bits2 & mask1.bits2));
results.bits3 = PxU16(~(mask0.bits3 & mask1.bits3));
}
static void gNOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(~(mask0.bits0 | mask1.bits0));
results.bits1 = PxU16(~(mask0.bits1 | mask1.bits1));
results.bits2 = PxU16(~(mask0.bits2 | mask1.bits2));
results.bits3 = PxU16(~(mask0.bits3 | mask1.bits3));
}
static void gNXOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(~(mask0.bits0 ^ mask1.bits0));
results.bits1 = PxU16(~(mask0.bits1 ^ mask1.bits1));
results.bits2 = PxU16(~(mask0.bits2 ^ mask1.bits2));
results.bits3 = PxU16(~(mask0.bits3 ^ mask1.bits3));
}
static void gSWAP_AND(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1)
{
results.bits0 = PxU16(mask0.bits0 & mask1.bits2);
results.bits1 = PxU16(mask0.bits1 & mask1.bits3);
results.bits2 = PxU16(mask0.bits2 & mask1.bits0);
results.bits3 = PxU16(mask0.bits3 & mask1.bits1);
}
typedef void (*FilterFunction) (PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1);
FilterFunction const gTable[] = { gAND, gOR, gXOR, gNAND, gNOR, gNXOR, gSWAP_AND };
static PxFilterData convert(const PxGroupsMask& mask)
{
PxFilterData fd;
fd.word2 = PxU32(mask.bits0 | (mask.bits1 << 16));
fd.word3 = PxU32(mask.bits2 | (mask.bits3 << 16));
return fd;
}
static PxGroupsMask convert(const PxFilterData& fd)
{
PxGroupsMask mask;
mask.bits0 = PxU16((fd.word2 & 0xffff));
mask.bits1 = PxU16((fd.word2 >> 16));
mask.bits2 = PxU16((fd.word3 & 0xffff));
mask.bits3 = PxU16((fd.word3 >> 16));
return mask;
}
static bool getFilterData(const PxActor& actor, PxFilterData& fd)
{
PxActorType::Enum aType = actor.getType();
switch (aType)
{
case PxActorType::eRIGID_DYNAMIC:
case PxActorType::eRIGID_STATIC:
case PxActorType::eARTICULATION_LINK:
{
const PxRigidActor& rActor = static_cast<const PxRigidActor&>(actor);
PX_CHECK_AND_RETURN_VAL(rActor.getNbShapes() >= 1,"There must be a shape in actor", false);
PxShape* shape = NULL;
rActor.getShapes(&shape, 1);
fd = shape->getSimulationFilterData();
}
break;
default:
break;
}
return true;
}
PX_FORCE_INLINE static void adjustFilterData(bool groupsMask, const PxFilterData& src, PxFilterData& dst)
{
if (groupsMask)
{
dst.word2 = src.word2;
dst.word3 = src.word3;
}
else
dst.word0 = src.word0;
}
template<bool TGroupsMask>
static void setFilterData(PxActor& actor, const PxFilterData& fd)
{
PxActorType::Enum aType = actor.getType();
switch (aType)
{
case PxActorType::eRIGID_DYNAMIC:
case PxActorType::eRIGID_STATIC:
case PxActorType::eARTICULATION_LINK:
{
const PxRigidActor& rActor = static_cast<const PxRigidActor&>(actor);
PxShape* shape;
for(PxU32 i=0; i < rActor.getNbShapes(); i++)
{
rActor.getShapes(&shape, 1, i);
// retrieve current group mask
PxFilterData resultFd = shape->getSimulationFilterData();
adjustFilterData(TGroupsMask, fd, resultFd);
// set new filter data
shape->setSimulationFilterData(resultFd);
}
}
break;
case PxActorType::eSOFTBODY:
{
PxSoftBody& sActor = static_cast<PxSoftBody&>(actor);
PxShape* shape = sActor.getShape();
// retrieve current group mask
PxFilterData resultFd = shape->getSimulationFilterData();
adjustFilterData(TGroupsMask, fd, resultFd);
// set new filter data
shape->setSimulationFilterData(resultFd);
}
break;
break;
default:
break;
}
}
}
PxFilterFlags physx::PxDefaultSimulationFilterShader(
PxFilterObjectAttributes attributes0,
PxFilterData filterData0,
PxFilterObjectAttributes attributes1,
PxFilterData filterData1,
PxPairFlags& pairFlags,
const void* constantBlock,
PxU32 constantBlockSize)
{
PX_UNUSED(constantBlock);
PX_UNUSED(constantBlockSize);
// let triggers through
if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))
{
pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
return PxFilterFlags();
}
// Collision Group
if (!gCollisionTable[filterData0.word0][filterData1.word0]())
{
return PxFilterFlag::eSUPPRESS;
}
// Filter function
PxGroupsMask g0 = convert(filterData0);
PxGroupsMask g1 = convert(filterData1);
PxGroupsMask g0k0; gTable[gFilterOps[0]](g0k0, g0, gFilterConstants[0]);
PxGroupsMask g1k1; gTable[gFilterOps[1]](g1k1, g1, gFilterConstants[1]);
PxGroupsMask final; gTable[gFilterOps[2]](final, g0k0, g1k1);
bool r = final.bits0 || final.bits1 || final.bits2 || final.bits3;
if (r != gFilterBool)
{
return PxFilterFlag::eSUPPRESS;
}
pairFlags = PxPairFlag::eCONTACT_DEFAULT;
return PxFilterFlags();
}
bool physx::PxGetGroupCollisionFlag(const PxU16 group1, const PxU16 group2)
{
PX_CHECK_AND_RETURN_NULL(group1 < 32 && group2 < 32, "Group must be less than 32");
return gCollisionTable[group1][group2]();
}
void physx::PxSetGroupCollisionFlag(const PxU16 group1, const PxU16 group2, const bool enable)
{
PX_CHECK_AND_RETURN(group1 < 32 && group2 < 32, "Group must be less than 32");
gCollisionTable[group1][group2] = enable;
gCollisionTable[group2][group1] = enable;
}
PxU16 physx::PxGetGroup(const PxActor& actor)
{
PxFilterData fd;
getFilterData(actor, fd);
return PxU16(fd.word0);
}
void physx::PxSetGroup(PxActor& actor, const PxU16 collisionGroup)
{
PX_CHECK_AND_RETURN(collisionGroup < 32,"Collision group must be less than 32");
PxFilterData fd(collisionGroup, 0, 0, 0);
setFilterData<false>(actor, fd);
}
void physx::PxGetFilterOps(PxFilterOp::Enum& op0, PxFilterOp::Enum& op1, PxFilterOp::Enum& op2)
{
op0 = gFilterOps[0];
op1 = gFilterOps[1];
op2 = gFilterOps[2];
}
void physx::PxSetFilterOps(const PxFilterOp::Enum& op0, const PxFilterOp::Enum& op1, const PxFilterOp::Enum& op2)
{
gFilterOps[0] = op0;
gFilterOps[1] = op1;
gFilterOps[2] = op2;
}
bool physx::PxGetFilterBool()
{
return gFilterBool;
}
void physx::PxSetFilterBool(const bool enable)
{
gFilterBool = enable;
}
void physx::PxGetFilterConstants(PxGroupsMask& c0, PxGroupsMask& c1)
{
c0 = gFilterConstants[0];
c1 = gFilterConstants[1];
}
void physx::PxSetFilterConstants(const PxGroupsMask& c0, const PxGroupsMask& c1)
{
gFilterConstants[0] = c0;
gFilterConstants[1] = c1;
}
PxGroupsMask physx::PxGetGroupsMask(const PxActor& actor)
{
PxFilterData fd;
if (getFilterData(actor, fd))
return convert(fd);
else
return PxGroupsMask();
}
void physx::PxSetGroupsMask(PxActor& actor, const PxGroupsMask& mask)
{
PxFilterData fd = convert(mask);
setFilterData<true>(actor, fd);
}
| 10,357 | C++ | 28.679083 | 124 | 0.722989 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtGearJoint.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 "ExtGearJoint.h"
#include "ExtConstraintHelper.h"
#include "extensions/PxRevoluteJoint.h"
#include "PxArticulationJointReducedCoordinate.h"
#include "omnipvd/ExtOmniPvdSetData.h"
//#include <stdio.h>
using namespace physx;
using namespace Ext;
PX_IMPLEMENT_OUTPUT_ERROR
GearJoint::GearJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) :
GearJointT(PxJointConcreteType::eGEAR, actor0, localFrame0, actor1, localFrame1, "GearJointData")
{
GearJointData* data = static_cast<GearJointData*>(mData);
data->hingeJoint0 = NULL;
data->hingeJoint1 = NULL;
data->gearRatio = 0.0f;
data->error = 0.0f;
resetError();
}
bool GearJoint::setHinges(const PxBase* hinge0, const PxBase* hinge1)
{
GearJointData* data = static_cast<GearJointData*>(mData);
if(hinge0)
{
const PxType type0 = hinge0->getConcreteType();
if(type0 == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE)
{
const PxArticulationJointReducedCoordinate* joint0 = static_cast<const PxArticulationJointReducedCoordinate*>(hinge0);
const PxArticulationJointType::Enum artiJointType = joint0->getJointType();
if(artiJointType != PxArticulationJointType::eREVOLUTE && artiJointType != PxArticulationJointType::eREVOLUTE_UNWRAPPED)
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint.");
}
else
{
if(type0 != PxJointConcreteType::eREVOLUTE && type0 != PxJointConcreteType::eD6)
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint or a D6 joint.");
}
}
if(hinge1)
{
const PxType type1 = hinge1->getConcreteType();
if(type1 == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE)
{
const PxArticulationJointReducedCoordinate* joint1 = static_cast<const PxArticulationJointReducedCoordinate*>(hinge1);
const PxArticulationJointType::Enum artiJointType = joint1->getJointType();
if(artiJointType != PxArticulationJointType::eREVOLUTE && artiJointType != PxArticulationJointType::eREVOLUTE_UNWRAPPED)
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint.");
}
else
{
if(type1 != PxJointConcreteType::eREVOLUTE && type1 != PxJointConcreteType::eD6)
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint or a D6 joint.");
}
}
data->hingeJoint0 = hinge0;
data->hingeJoint1 = hinge1;
resetError();
markDirty();
#if PX_SUPPORT_OMNI_PVD
const PxBase* joints[] ={ hinge0, hinge1 };
const PxU32 hingeCount = sizeof(joints) / sizeof(joints[0]);
OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, hinges, static_cast<PxGearJoint&>(*this), joints, hingeCount)
#endif
return true;
}
void GearJoint::getHinges(const PxBase*& hinge0, const PxBase*& hinge1) const
{
const GearJointData* data = static_cast<const GearJointData*>(mData);
hinge0 = data->hingeJoint0;
hinge1 = data->hingeJoint1;
}
void GearJoint::setGearRatio(float ratio)
{
GearJointData* data = static_cast<GearJointData*>(mData);
data->gearRatio = ratio;
resetError();
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, ratio, static_cast<PxGearJoint&>(*this), ratio)
}
float GearJoint::getGearRatio() const
{
const GearJointData* data = static_cast<const GearJointData*>(mData);
return data->gearRatio;
}
static float angleDiff(float angle0, float angle1)
{
const float diff = fmodf(angle1 - angle0 + PxPi, PxTwoPi) - PxPi;
return diff < -PxPi ? diff + PxTwoPi : diff;
}
static void getAngleAndSign(float& angle, float& sign, const PxBase* dataHingeJoint, PxRigidActor* gearActor0, PxRigidActor* gearActor1)
{
PxRigidActor* hingeActor0;
PxRigidActor* hingeActor1;
const PxType type = dataHingeJoint->getConcreteType();
if(type == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE)
{
const PxArticulationJointReducedCoordinate* artiHingeJoint = static_cast<const PxArticulationJointReducedCoordinate*>(dataHingeJoint);
hingeActor0 = &artiHingeJoint->getParentArticulationLink();
hingeActor1 = &artiHingeJoint->getChildArticulationLink();
angle = artiHingeJoint->getJointPosition(PxArticulationAxis::eTWIST);
}
else
{
const PxJoint* hingeJoint = static_cast<const PxJoint*>(dataHingeJoint);
hingeJoint->getActors(hingeActor0, hingeActor1);
if(type == PxJointConcreteType::eREVOLUTE)
angle = static_cast<const PxRevoluteJoint*>(hingeJoint)->getAngle();
else if(type == PxJointConcreteType::eD6)
angle = static_cast<const PxD6Joint*>(hingeJoint)->getTwistAngle();
}
if(gearActor0 == hingeActor0 || gearActor1 == hingeActor0)
sign = -1.0f;
else if(gearActor0 == hingeActor1 || gearActor1 == hingeActor1)
sign = 1.0f;
else
PX_ASSERT(0);
}
void GearJoint::updateError()
{
GearJointData* data = static_cast<GearJointData*>(mData);
if(!data->hingeJoint0 || !data->hingeJoint1)
return;
PxRigidActor* gearActor0;
PxRigidActor* gearActor1;
getActors(gearActor0, gearActor1);
float Angle0 = 0.0f;
float Sign0 = 0.0f;
getAngleAndSign(Angle0, Sign0, data->hingeJoint0, gearActor0, gearActor1);
float Angle1 = 0.0f;
float Sign1 = 0.0f;
getAngleAndSign(Angle1, Sign1, data->hingeJoint1, gearActor0, gearActor1);
Angle1 = -Angle1;
if(!mInitDone)
{
mInitDone = true;
mPersistentAngle0 = Angle0;
mPersistentAngle1 = Angle1;
}
const float travelThisFrame0 = angleDiff(Angle0, mPersistentAngle0);
const float travelThisFrame1 = angleDiff(Angle1, mPersistentAngle1);
mVirtualAngle0 += travelThisFrame0;
mVirtualAngle1 += travelThisFrame1;
// printf("travelThisFrame0: %f\n", travelThisFrame0);
// printf("travelThisFrame1: %f\n", travelThisFrame1);
// printf("ratio: %f\n", travelThisFrame1/travelThisFrame0);
mPersistentAngle0 = Angle0;
mPersistentAngle1 = Angle1;
const float error = Sign0*mVirtualAngle0*data->gearRatio - Sign1*mVirtualAngle1;
// printf("error: %f\n", error);
data->error = error;
markDirty();
}
void GearJoint::resetError()
{
mVirtualAngle0 = mVirtualAngle1 = 0.0f;
mPersistentAngle0 = mPersistentAngle1 = 0.0f;
mInitDone = false;
}
static const bool gVizJointFrames = true;
static const bool gVizGearAxes = false;
static void GearJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags)
{
if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES)
{
const GearJointData& data = *reinterpret_cast<const GearJointData*>(constantBlock);
// Visualize joint frames
PxTransform32 cA2w, cB2w;
joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform);
if(gVizJointFrames)
viz.visualizeJointFrames(cA2w, cB2w);
if(gVizGearAxes)
{
const PxVec3 gearAxis0 = cA2w.rotate(PxVec3(1.0f, 0.0f, 0.0f)).getNormalized();
const PxVec3 gearAxis1 = cB2w.rotate(PxVec3(1.0f, 0.0f, 0.0f)).getNormalized();
viz.visualizeLine(body0Transform.p+gearAxis0, body0Transform.p, 0xff0000ff);
viz.visualizeLine(body1Transform.p+gearAxis1, body1Transform.p, 0xff0000ff);
}
}
}
//TAG:solverprepshader
static PxU32 GearJointSolverPrep(Px1DConstraint* constraints,
PxVec3p& body0WorldOffset,
PxU32 /*maxConstraints*/,
PxConstraintInvMassScale& invMassScale,
const void* constantBlock,
const PxTransform& bA2w,
const PxTransform& bB2w,
bool /*useExtendedLimits*/,
PxVec3p& cA2wOut, PxVec3p& cB2wOut)
{
const GearJointData& data = *reinterpret_cast<const GearJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w);
cA2wOut = cB2w.p;
cB2wOut = cB2w.p;
const PxVec3 gearAxis0 = cA2w.q.getBasisVector0();
const PxVec3 gearAxis1 = cB2w.q.getBasisVector0();
Px1DConstraint& con = constraints[0];
con.linear0 = PxVec3(0.0f);
con.linear1 = PxVec3(0.0f);
con.angular0 = gearAxis0*data.gearRatio;
con.angular1 = -gearAxis1;
con.geometricError = -data.error;
con.minImpulse = -PX_MAX_F32;
con.maxImpulse = PX_MAX_F32;
con.velocityTarget = 0.f;
con.forInternalUse = 0.f;
con.solveHint = 0;
con.flags = Px1DConstraintFlag::eOUTPUT_FORCE|Px1DConstraintFlag::eANGULAR_CONSTRAINT;
con.mods.bounce.restitution = 0.0f;
con.mods.bounce.velocityThreshold = 0.0f;
return 1;
}
///////////////////////////////////////////////////////////////////////////////
static PxConstraintShaderTable gGearJointShaders = { GearJointSolverPrep, GearJointVisualize, PxConstraintFlag::eALWAYS_UPDATE };
PxConstraintSolverPrep GearJoint::getPrep() const { return gGearJointShaders.solverPrep; }
PxGearJoint* physx::PxGearJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1)
{
PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxGearJointCreate: local frame 0 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxGearJointCreate: local frame 1 is not a valid transform");
PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxGearJointCreate: at least one actor must be dynamic");
PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxGearJointCreate: actors must be different");
return createJointT<GearJoint, GearJointData>(physics, actor0, localFrame0, actor1, localFrame1, gGearJointShaders);
}
// PX_SERIALIZATION
void GearJoint::resolveReferences(PxDeserializationContext& context)
{
mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gGearJointShaders);
GearJointData* data = static_cast<GearJointData*>(mData);
context.translatePxBase(data->hingeJoint0);
context.translatePxBase(data->hingeJoint1);
}
//~PX_SERIALIZATION
#if PX_SUPPORT_OMNI_PVD
template<>
void physx::Ext::omniPvdInitJoint<GearJoint>(GearJoint& joint)
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxGearJoint& j = static_cast<PxGearJoint&>(joint);
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, j);
omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eGEAR);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, ratio, j , joint.getGearRatio())
OMNI_PVD_WRITE_SCOPE_END
}
#endif
| 12,129 | C++ | 35.869301 | 169 | 0.756534 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtPxStringTable.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/PxAllocatorCallback.h"
#include "foundation/PxString.h"
#include "foundation/PxUserAllocated.h"
#include "extensions/PxStringTableExt.h"
#include "PxProfileAllocatorWrapper.h" //tools for using a custom allocator
namespace physx
{
using namespace physx::profile;
class PxStringTableImpl : public PxStringTable, public PxUserAllocated
{
typedef PxProfileHashMap<const char*, PxU32> THashMapType;
PxProfileAllocatorWrapper mWrapper;
THashMapType mHashMap;
public:
PxStringTableImpl( PxAllocatorCallback& inAllocator )
: mWrapper ( inAllocator )
, mHashMap ( mWrapper )
{
}
virtual ~PxStringTableImpl()
{
for ( THashMapType::Iterator iter = mHashMap.getIterator();
iter.done() == false;
++iter )
PX_PROFILE_DELETE( mWrapper, const_cast<char*>( iter->first ) );
mHashMap.clear();
}
virtual const char* allocateStr( const char* inSrc )
{
if ( inSrc == NULL )
inSrc = "";
const THashMapType::Entry* existing( mHashMap.find( inSrc ) );
if ( existing == NULL )
{
size_t len( strlen( inSrc ) );
len += 1;
char* newMem = reinterpret_cast<char*>(mWrapper.getAllocator().allocate( len, "PxStringTableImpl: const char*", PX_FL));
physx::Pxstrlcpy( newMem, len, inSrc );
mHashMap.insert( newMem, 1 );
return newMem;
}
else
{
++const_cast<THashMapType::Entry*>(existing)->second;
return existing->first;
}
}
/**
* Release the string table and all the strings associated with it.
*/
virtual void release()
{
PX_PROFILE_DELETE( mWrapper.getAllocator(), this );
}
};
PxStringTable& PxStringTableExt::createStringTable( PxAllocatorCallback& inAllocator )
{
return *PX_PROFILE_NEW( inAllocator, PxStringTableImpl )( inAllocator );
}
}
| 3,477 | C++ | 34.85567 | 124 | 0.727064 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDistanceJoint.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 "ExtDistanceJoint.h"
#include "ExtConstraintHelper.h"
#include "omnipvd/ExtOmniPvdSetData.h"
using namespace physx;
using namespace Ext;
DistanceJoint::DistanceJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) :
DistanceJointT(PxJointConcreteType::eDISTANCE, actor0, localFrame0, actor1, localFrame1, "DistanceJointData")
{
DistanceJointData* data = static_cast<DistanceJointData*>(mData);
data->stiffness = 0.0f;
data->damping = 0.0f;
data->minDistance = 0.0f;
data->maxDistance = 0.0f;
data->tolerance = 0.025f * scale.length;
data->jointFlags = PxDistanceJointFlag::eMAX_DISTANCE_ENABLED;
}
PxReal DistanceJoint::getDistance() const
{
return getRelativeTransform().p.magnitude();
}
void DistanceJoint::setMinDistance(PxReal distance)
{
PX_CHECK_AND_RETURN(PxIsFinite(distance) && distance>=0.0f, "PxDistanceJoint::setMinDistance: invalid parameter");
data().minDistance = distance;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, minDistance, static_cast<PxDistanceJoint&>(*this), distance)
}
PxReal DistanceJoint::getMinDistance() const
{
return data().minDistance;
}
void DistanceJoint::setMaxDistance(PxReal distance)
{
PX_CHECK_AND_RETURN(PxIsFinite(distance) && distance>=0.0f, "PxDistanceJoint::setMaxDistance: invalid parameter");
data().maxDistance = distance;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, maxDistance, static_cast<PxDistanceJoint&>(*this), distance)
}
PxReal DistanceJoint::getMaxDistance() const
{
return data().maxDistance;
}
void DistanceJoint::setTolerance(PxReal tolerance)
{
PX_CHECK_AND_RETURN(PxIsFinite(tolerance), "PxDistanceJoint::setTolerance: invalid parameter");
data().tolerance = tolerance;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, tolerance, static_cast<PxDistanceJoint&>(*this), tolerance)
}
PxReal DistanceJoint::getTolerance() const
{
return data().tolerance;
}
void DistanceJoint::setStiffness(PxReal stiffness)
{
PX_CHECK_AND_RETURN(PxIsFinite(stiffness), "PxDistanceJoint::setStiffness: invalid parameter");
data().stiffness = stiffness;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, stiffness, static_cast<PxDistanceJoint&>(*this), stiffness)
}
PxReal DistanceJoint::getStiffness() const
{
return data().stiffness;
}
void DistanceJoint::setDamping(PxReal damping)
{
PX_CHECK_AND_RETURN(PxIsFinite(damping), "PxDistanceJoint::setDamping: invalid parameter");
data().damping = damping;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, damping, static_cast<PxDistanceJoint&>(*this), damping)
}
PxReal DistanceJoint::getDamping() const
{
return data().damping;
}
PxDistanceJointFlags DistanceJoint::getDistanceJointFlags(void) const
{
return data().jointFlags;
}
void DistanceJoint::setDistanceJointFlags(PxDistanceJointFlags flags)
{
data().jointFlags = flags;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, jointFlags, static_cast<PxDistanceJoint&>(*this), flags)
}
void DistanceJoint::setDistanceJointFlag(PxDistanceJointFlag::Enum flag, bool value)
{
if(value)
data().jointFlags |= flag;
else
data().jointFlags &= ~flag;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, jointFlags, static_cast<PxDistanceJoint&>(*this), getDistanceJointFlags())
}
static void DistanceJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags)
{
const DistanceJointData& data = *reinterpret_cast<const DistanceJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform);
if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES)
viz.visualizeJointFrames(cA2w, cB2w);
// PT: we consider the following is part of the joint's "limits" since that's the only available flag we have
if(flags & PxConstraintVisualizationFlag::eLIMITS)
{
const bool enforceMax = (data.jointFlags & PxDistanceJointFlag::eMAX_DISTANCE_ENABLED);
const bool enforceMin = (data.jointFlags & PxDistanceJointFlag::eMIN_DISTANCE_ENABLED);
if(!enforceMin && !enforceMax)
return;
PxVec3 dir = cB2w.p - cA2w.p;
const float currentDist = dir.normalize();
PxU32 color = 0x00ff00;
if(enforceMax && currentDist>data.maxDistance)
color = 0xff0000;
if(enforceMin && currentDist<data.minDistance)
color = 0x0000ff;
viz.visualizeLine(cA2w.p, cB2w.p, color);
}
}
static PX_FORCE_INLINE void setupConstraint(Px1DConstraint& c, const PxVec3& direction, const PxVec3& angular0, const PxVec3& angular1, const DistanceJointData& data)
{
// constraint is breakable, so we need to output forces
c.flags = Px1DConstraintFlag::eOUTPUT_FORCE;
c.linear0 = direction; c.angular0 = angular0;
c.linear1 = direction; c.angular1 = angular1;
if(data.jointFlags & PxDistanceJointFlag::eSPRING_ENABLED)
{
c.flags |= Px1DConstraintFlag::eSPRING;
c.mods.spring.stiffness= data.stiffness;
c.mods.spring.damping = data.damping;
}
}
static PX_FORCE_INLINE PxU32 setupMinConstraint(Px1DConstraint& c, const PxVec3& direction, const PxVec3& angular0, const PxVec3& angular1, const DistanceJointData& data, float distance)
{
setupConstraint(c, direction, angular0, angular1, data);
c.geometricError = distance - data.minDistance + data.tolerance;
c.minImpulse = 0.0f;
if(distance>=data.minDistance)
c.flags |= Px1DConstraintFlag::eKEEPBIAS;
return 1;
}
static PX_FORCE_INLINE PxU32 setupMaxConstraint(Px1DConstraint& c, const PxVec3& direction, const PxVec3& angular0, const PxVec3& angular1, const DistanceJointData& data, float distance)
{
setupConstraint(c, direction, angular0, angular1, data);
c.geometricError = distance - data.maxDistance - data.tolerance;
c.maxImpulse = 0.0f;
if(distance<=data.maxDistance)
c.flags |= Px1DConstraintFlag::eKEEPBIAS;
return 1;
}
//TAG:solverprepshader
static PxU32 DistanceJointSolverPrep(Px1DConstraint* constraints,
PxVec3p& body0WorldOffset,
PxU32 /*maxConstraints*/,
PxConstraintInvMassScale& invMassScale,
const void* constantBlock,
const PxTransform& bA2w,
const PxTransform& bB2w,
bool /*useExtendedLimits*/,
PxVec3p& cA2wOut, PxVec3p& cB2wOut)
{
const DistanceJointData& data = *reinterpret_cast<const DistanceJointData*>(constantBlock);
const bool enforceMax = (data.jointFlags & PxDistanceJointFlag::eMAX_DISTANCE_ENABLED) && data.maxDistance>=0.0f;
const bool enforceMin = (data.jointFlags & PxDistanceJointFlag::eMIN_DISTANCE_ENABLED) && data.minDistance>=0.0f;
if(!enforceMax && !enforceMin)
return 0;
PxTransform32 cA2w, cB2w;
joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w);
cA2wOut = cB2w.p;
cB2wOut = cB2w.p;
PxVec3 direction = cA2w.p - cB2w.p;
const PxReal distance = direction.normalize();
#define EPS_REAL 1.192092896e-07F
if(distance < EPS_REAL)
direction = PxVec3(1.0f, 0.0f, 0.0f);
Px1DConstraint* c = constraints;
const PxVec3 angular0 = ch.getRa().cross(direction);
const PxVec3 angular1 = ch.getRb().cross(direction);
if(enforceMin && !enforceMax)
return setupMinConstraint(*c, direction, angular0, angular1, data, distance);
else if(enforceMax && !enforceMin)
return setupMaxConstraint(*c, direction, angular0, angular1, data, distance);
else
{
if(data.minDistance == data.maxDistance)
{
setupConstraint(*c, direction, angular0, angular1, data);
//add tolerance so we don't have contact-style jitter problem.
const PxReal error = distance - data.maxDistance;
c->geometricError = error > data.tolerance ? error - data.tolerance :
error < -data.tolerance ? error + data.tolerance : 0.0f;
return 1;
}
// since we dont know the current rigid velocity, we need to insert row for both limits
PxU32 nb = setupMinConstraint(*c, direction, angular0, angular1, data, distance);
if(nb)
c++;
nb += setupMaxConstraint(*c, direction, angular0, angular1, data, distance);
return nb;
}
}
///////////////////////////////////////////////////////////////////////////////
static PxConstraintShaderTable gDistanceJointShaders = { DistanceJointSolverPrep, DistanceJointVisualize, PxConstraintFlag::Enum(0) };
PxConstraintSolverPrep DistanceJoint::getPrep() const { return gDistanceJointShaders.solverPrep; }
PxDistanceJoint* physx::PxDistanceJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1)
{
PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxDistanceJointCreate: local frame 0 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxDistanceJointCreate: local frame 1 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxDistanceJointCreate: actors must be different");
PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxD6JointCreate: at least one actor must be dynamic");
return createJointT<DistanceJoint, DistanceJointData>(physics, actor0, localFrame0, actor1, localFrame1, gDistanceJointShaders);
}
// PX_SERIALIZATION
void DistanceJoint::resolveReferences(PxDeserializationContext& context)
{
mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gDistanceJointShaders);
}
//~PX_SERIALIZATION
#if PX_SUPPORT_OMNI_PVD
void DistanceJoint::updateOmniPvdProperties() const
{
const PxDistanceJoint& j = static_cast<const PxDistanceJoint&>(*this);
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, distance, j, getDistance())
}
template<>
void physx::Ext::omniPvdInitJoint<DistanceJoint>(DistanceJoint& joint)
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxDistanceJoint& j = static_cast<PxDistanceJoint&>(joint);
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, j);
omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eDISTANCE);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, minDistance, j, joint.getMinDistance())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, maxDistance, j, joint.getMaxDistance())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, tolerance, j, joint.getTolerance())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, stiffness, j, joint.getStiffness())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, damping, j, joint.getDamping())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, jointFlags, j, joint.getDistanceJointFlags())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, distance, j, joint.getDistance())
OMNI_PVD_WRITE_SCOPE_END
}
#endif
| 12,711 | C++ | 37.289157 | 186 | 0.761466 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtContactJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_CONTACT_JOINT_H
#define EXT_CONTACT_JOINT_H
#include "common/PxTolerancesScale.h"
#include "extensions/PxContactJoint.h"
#include "ExtJoint.h"
#include "foundation/PxUserAllocated.h"
#include "CmUtils.h"
namespace physx
{
struct PxContactJointGeneratedValues;
namespace Ext
{
struct ContactJointData : public JointData
{
PxVec3 contact;
PxVec3 normal;
PxReal penetration;
PxReal restitution;
PxReal bounceThreshold;
};
typedef JointT<PxContactJoint, ContactJointData, PxContactJointGeneratedValues> ContactJointT;
class ContactJoint : public ContactJointT
{
public:
// PX_SERIALIZATION
ContactJoint(PxBaseFlags baseFlags) : ContactJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static ContactJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<ContactJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ContactJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxContactJoint
virtual PxVec3 getContact() const PX_OVERRIDE;
virtual void setContact(const PxVec3& contact) PX_OVERRIDE;
virtual PxVec3 getContactNormal() const PX_OVERRIDE;
virtual void setContactNormal(const PxVec3& normal) PX_OVERRIDE;
virtual PxReal getPenetration() const PX_OVERRIDE;
virtual void setPenetration(const PxReal penetration) PX_OVERRIDE;
virtual PxReal getRestitution() const PX_OVERRIDE;
virtual void setRestitution(const PxReal resititution) PX_OVERRIDE;
virtual PxReal getBounceThreshold() const PX_OVERRIDE;
virtual void setBounceThreshold(const PxReal bounceThreshold) PX_OVERRIDE;
virtual void computeJacobians(PxJacobianRow* jacobian) const PX_OVERRIDE;
virtual PxU32 getNbJacobianRows() const PX_OVERRIDE;
//~PxContactJoint
// PxConstraintConnector
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
//~PxConstraintConnector
};
} // namespace Ext
} // namespace physx
#endif
| 3,862 | C | 42.897727 | 163 | 0.767478 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSmoothNormals.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "extensions/PxSmoothNormals.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
using namespace physx;
static PxReal computeAngle(const PxVec3* verts, const PxU32* refs, PxU32 vref)
{
PxU32 e0=0,e2=0;
if(vref==refs[0])
{
e0 = 2;
e2 = 1;
}
else if(vref==refs[1])
{
e0 = 2;
e2 = 0;
}
else if(vref==refs[2])
{
e0 = 0;
e2 = 1;
}
else
{
PX_ASSERT(0);
}
const PxVec3 edge0 = verts[refs[e0]] - verts[vref];
const PxVec3 edge1 = verts[refs[e2]] - verts[vref];
return PxComputeAngle(edge0, edge1);
}
bool PxBuildSmoothNormals(PxU32 nbTris, PxU32 nbVerts, const PxVec3* verts, const PxU32* dFaces, const PxU16* wFaces, PxVec3* normals, bool flip)
{
if(!verts || !normals || !nbTris || !nbVerts)
return false;
// Get correct destination buffers
// - if available, write directly to user-provided buffers
// - else get some ram and keep track of it
PxVec3* FNormals = PX_ALLOCATE(PxVec3, nbTris, "PxVec3");
if(!FNormals) return false;
// Compute face normals
const PxU32 c = PxU32(flip!=0);
for(PxU32 i=0; i<nbTris; i++)
{
// compute indices outside of array index to workaround
// SNC bug which was generating incorrect addresses
const PxU32 i0 = i*3+0;
const PxU32 i1 = i*3+1+c;
const PxU32 i2 = i*3+2-c;
const PxU32 Ref0 = dFaces ? dFaces[i0] : wFaces ? wFaces[i0] : 0;
const PxU32 Ref1 = dFaces ? dFaces[i1] : wFaces ? wFaces[i1] : 1;
const PxU32 Ref2 = dFaces ? dFaces[i2] : wFaces ? wFaces[i2] : 2;
FNormals[i] = (verts[Ref2]-verts[Ref0]).cross(verts[Ref1] - verts[Ref0]);
PX_ASSERT(!FNormals[i].isZero());
FNormals[i].normalize();
}
// Compute vertex normals
PxMemSet(normals, 0, nbVerts*sizeof(PxVec3));
// TTP 3751
PxVec3* TmpNormals = PX_ALLOCATE(PxVec3, nbVerts, "PxVec3");
PxMemSet(TmpNormals, 0, nbVerts*sizeof(PxVec3));
for(PxU32 i=0;i<nbTris;i++)
{
PxU32 Ref[3];
Ref[0] = dFaces ? dFaces[i*3+0] : wFaces ? wFaces[i*3+0] : 0;
Ref[1] = dFaces ? dFaces[i*3+1] : wFaces ? wFaces[i*3+1] : 1;
Ref[2] = dFaces ? dFaces[i*3+2] : wFaces ? wFaces[i*3+2] : 2;
for(PxU32 j=0;j<3;j++)
{
if(TmpNormals[Ref[j]].isZero())
TmpNormals[Ref[j]] = FNormals[i];
}
}
//~TTP 3751
for(PxU32 i=0;i<nbTris;i++)
{
PxU32 Ref[3];
Ref[0] = dFaces ? dFaces[i*3+0] : wFaces ? wFaces[i*3+0] : 0;
Ref[1] = dFaces ? dFaces[i*3+1] : wFaces ? wFaces[i*3+1] : 1;
Ref[2] = dFaces ? dFaces[i*3+2] : wFaces ? wFaces[i*3+2] : 2;
normals[Ref[0]] += FNormals[i] * computeAngle(verts, Ref, Ref[0]);
normals[Ref[1]] += FNormals[i] * computeAngle(verts, Ref, Ref[1]);
normals[Ref[2]] += FNormals[i] * computeAngle(verts, Ref, Ref[2]);
}
// Normalize vertex normals
for(PxU32 i=0;i<nbVerts;i++)
{
if(normals[i].isZero())
normals[i] = TmpNormals[i];
// PX_ASSERT(!normals[i].isZero());
normals[i].normalize();
}
PX_FREE(TmpNormals); // TTP 3751
PX_FREE(FNormals);
return true;
}
| 4,681 | C++ | 31.513889 | 145 | 0.687246 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSphericalJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_SPHERICAL_JOINT_H
#define EXT_SPHERICAL_JOINT_H
#include "extensions/PxSphericalJoint.h"
#include "ExtJoint.h"
#include "CmUtils.h"
namespace physx
{
struct PxSphericalJointGeneratedValues;
namespace Ext
{
struct SphericalJointData: public JointData
{
PxJointLimitCone limit;
PxSphericalJointFlags jointFlags;
private:
SphericalJointData(const PxJointLimitCone& cone) : limit(cone) {}
};
typedef JointT<PxSphericalJoint, SphericalJointData, PxSphericalJointGeneratedValues> SphericalJointT;
class SphericalJoint : public SphericalJointT
{
public:
// PX_SERIALIZATION
SphericalJoint(PxBaseFlags baseFlags) : SphericalJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static SphericalJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<SphericalJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
SphericalJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxSphericalJoint
virtual void setLimitCone(const PxJointLimitCone &limit) PX_OVERRIDE;
virtual PxJointLimitCone getLimitCone() const PX_OVERRIDE;
virtual void setSphericalJointFlags(PxSphericalJointFlags flags) PX_OVERRIDE;
virtual void setSphericalJointFlag(PxSphericalJointFlag::Enum flag, bool value) PX_OVERRIDE;
virtual PxSphericalJointFlags getSphericalJointFlags(void) const PX_OVERRIDE;
virtual PxReal getSwingYAngle() const PX_OVERRIDE;
virtual PxReal getSwingZAngle() const PX_OVERRIDE;
//~PxSphericalJoint
// PxConstraintConnector
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
#if PX_SUPPORT_OMNI_PVD
virtual void updateOmniPvdProperties() const PX_OVERRIDE;
#endif
//~PxConstraintConnector
};
} // namespace Ext
} // namespace physx
#endif
| 3,682 | C | 41.825581 | 169 | 0.773221 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtTetrahedronMeshExt.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 "extensions/PxTetrahedronMeshExt.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxHashMap.h"
#include "GuTetrahedronMesh.h"
#include "GuBox.h"
#include "GuBV4.h"
#include "GuBV4_Common.h"
#include "GuDistancePointTetrahedron.h"
#include "GuAABBTreeNode.h"
#include "GuAABBTree.h"
#include "GuAABBTreeBounds.h"
#include "GuAABBTreeQuery.h"
namespace physx
{
struct TetrahedronFinderCallback
{
PxVec3 mQueryPoint;
PxI32 mTetId;
PxVec4 mBary;
const PxVec3* mVertices;
const PxU32* mTets;
PxReal mTolerance = 1e-6f;
TetrahedronFinderCallback(const PxVec3& queryPoint, const PxVec3* vertices, const PxU32* tets, const PxReal tolerance = 1e-6f) :
mQueryPoint(queryPoint), mTetId(-1), mVertices(vertices), mTets(tets), mTolerance(tolerance) {}
PX_FORCE_INLINE bool testPrimitive(const PxU32 primitiveStartId, const PxU32 numPrimitives)
{
for (PxU32 i = 0; i < numPrimitives; ++i)
{
const PxU32* tet = &mTets[4 * (primitiveStartId + i)];
computeBarycentric(mVertices[tet[0]], mVertices[tet[1]], mVertices[tet[2]], mVertices[tet[3]], mQueryPoint, mBary);
if (mBary.x >= -mTolerance && mBary.x <= 1 + mTolerance && mBary.y >= -mTolerance && mBary.y <= 1 + mTolerance &&
mBary.z >= -mTolerance && mBary.z <= 1 + mTolerance && mBary.w >= -mTolerance && mBary.w <= 1 + mTolerance)
{
mTetId = PxI32(primitiveStartId + i);
return true;
}
}
return false;
}
PX_FORCE_INLINE bool testBox(const float boxMinX, const float boxMinY, const float boxMinZ, const float boxMaxX, const float boxMaxY, const float boxMaxZ)
{
return mQueryPoint.x >= boxMinX && mQueryPoint.y >= boxMinY && mQueryPoint.z >= boxMinZ &&
mQueryPoint.x <= boxMaxX && mQueryPoint.y <= boxMaxY && mQueryPoint.z <= boxMaxZ;
}
};
struct ClosestTetrahedronFinderCallback
{
PxVec3 mQueryPoint;
PxI32 mTetId;
PxVec4 mBary;
PxReal mDist = 1.84467e+19f; // sqrtf(FLT_MAX)
const PxVec3* mVertices;
const PxU32* mTets;
PxReal mTolerance = 1e-6f;
ClosestTetrahedronFinderCallback(const PxVec3& queryPoint, const PxVec3* vertices, const PxU32* tets) :
mQueryPoint(queryPoint), mTetId(-1), mVertices(vertices), mTets(tets) {}
PX_FORCE_INLINE bool testPrimitive(const PxU32 primitiveStartId, const PxU32 numPrimitives)
{
for (PxU32 i = 0; i < numPrimitives; ++i)
{
PxVec4 bary;
const PxU32* tet = &mTets[4 * (primitiveStartId + i)];
computeBarycentric(mVertices[tet[0]], mVertices[tet[1]], mVertices[tet[2]], mVertices[tet[3]], mQueryPoint, bary);
if (bary.x >= -mTolerance && bary.x <= 1 + mTolerance && bary.y >= -mTolerance && bary.y <= 1 + mTolerance &&
bary.z >= -mTolerance && bary.z <= 1 + mTolerance && bary.w >= -mTolerance && bary.w <= 1 + mTolerance)
{
mTetId = PxI32(primitiveStartId + i);
mBary = bary;
mDist = 0;
return true;
}
PxVec3 closest = Gu::closestPtPointTetrahedron(mQueryPoint, mVertices[tet[0]], mVertices[tet[1]], mVertices[tet[2]], mVertices[tet[3]]);
PxReal distSq = (closest - mQueryPoint).magnitudeSquared();
if (distSq < mDist * mDist)
{
mTetId = PxI32(primitiveStartId + i);
mBary = bary;
mDist = PxSqrt(distSq);
}
}
return false;
}
PX_FORCE_INLINE bool testBox(const float boxMinX, const float boxMinY, const float boxMinZ, const float boxMaxX, const float boxMaxY, const float boxMaxZ)
{
if (mQueryPoint.x >= boxMinX && mQueryPoint.y >= boxMinY && mQueryPoint.z >= boxMinZ &&
mQueryPoint.x <= boxMaxX && mQueryPoint.y <= boxMaxY && mQueryPoint.z <= boxMaxZ)
return true;
PxVec3 closest = mQueryPoint;
closest.x = PxClamp(closest.x, boxMinX, boxMaxX);
closest.y = PxClamp(closest.y, boxMinY, boxMaxY);
closest.z = PxClamp(closest.z, boxMinZ, boxMaxZ);
PxReal distSq = (closest - mQueryPoint).magnitudeSquared();
return distSq < mDist * mDist;
}
};
template<typename T, PxU32 i>
int process(PxU32* stack, PxU32& stackSize, const Gu::BVDataSwizzledNQ* node, T& callback)
{
if (callback.testBox(node->mMinX[i], node->mMinY[i], node->mMinZ[i], node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i]))
{
if (node->isLeaf(i))
{
PxU32 primitiveIndex = node->getPrimitive(i);
const PxU32 numPrimitives = Gu::getNbPrimitives(primitiveIndex);
if(callback.testPrimitive(primitiveIndex, numPrimitives)) //Returns true if the query should be terminated immediately
return 1;
}
else
stack[stackSize++] = node->getChildData(i);
}
return 0;
}
template<typename T>
void traverseBVH(const Gu::BV4Tree& tree, T& callback)
{
const Gu::BVDataPackedNQ* root = static_cast<const Gu::BVDataPackedNQ*>(tree.mNodes);
PxU32 stack[GU_BV4_STACK_SIZE];
PxU32 stackSize = 0;
stack[stackSize++] = tree.mInitData;
while (stackSize > 0)
{
const PxU32 childData = stack[--stackSize];
const Gu::BVDataSwizzledNQ* node = reinterpret_cast<const Gu::BVDataSwizzledNQ*>(root + Gu::getChildOffset(childData));
const PxU32 nodeType = Gu::getChildType(childData);
if (nodeType > 1)
if (process<T, 3>(stack, stackSize, node, callback)) return;
if (nodeType > 0)
if (process<T, 2>(stack, stackSize, node, callback)) return;
if (process<T, 1>(stack, stackSize, node, callback)) return;
if (process<T, 0>(stack, stackSize, node, callback)) return;
}
}
PxI32 PxTetrahedronMeshExt::findTetrahedronContainingPoint(const PxTetrahedronMesh* mesh, const PxVec3& point, PxVec4& bary, PxReal tolerance)
{
TetrahedronFinderCallback callback(point, mesh->getVertices(), static_cast<const PxU32*>(mesh->getTetrahedrons()), tolerance);
traverseBVH(static_cast<const Gu::BVTetrahedronMesh*>(mesh)->getBV4Tree(), callback);
bary = callback.mBary;
return callback.mTetId;
}
PxI32 PxTetrahedronMeshExt::findTetrahedronClosestToPoint(const PxTetrahedronMesh* mesh, const PxVec3& point, PxVec4& bary)
{
ClosestTetrahedronFinderCallback callback(point, mesh->getVertices(), static_cast<const PxU32*>(mesh->getTetrahedrons()));
const Gu::BV4Tree& tree = static_cast<const Gu::BVTetrahedronMesh*>(mesh)->getBV4Tree();
if (tree.mNbNodes) traverseBVH(tree, callback);
else callback.testPrimitive(0, mesh->getNbTetrahedrons());
bary = callback.mBary;
return callback.mTetId;
}
class ClosestDistanceToTetmeshTraversalController
{
private:
PxReal mClosestDistanceSquared;
const PxU32* mTetrahedra;
const PxVec3* mPoints;
const Gu::BVHNode* mNodes;
PxVec3 mQueryPoint;
PxVec3 mClosestPoint;
PxI32 mClosestTetId;
public:
PX_FORCE_INLINE ClosestDistanceToTetmeshTraversalController() {}
PX_FORCE_INLINE ClosestDistanceToTetmeshTraversalController(const PxU32* tetrahedra, const PxVec3* points, Gu::BVHNode* nodes) :
mTetrahedra(tetrahedra), mPoints(points), mNodes(nodes), mQueryPoint(0.0f), mClosestPoint(0.0f), mClosestTetId(-1)
{
initialize(tetrahedra, points, nodes);
}
void initialize(const PxU32* tetrahedra, const PxVec3* points, Gu::BVHNode* nodes)
{
mTetrahedra = tetrahedra;
mPoints = points;
mNodes = nodes;
mQueryPoint = PxVec3(0.0f);
mClosestPoint = PxVec3(0.0f);
mClosestTetId = -1;
mClosestDistanceSquared = PX_MAX_F32;
}
PX_FORCE_INLINE void setQueryPoint(const PxVec3& queryPoint)
{
this->mQueryPoint = queryPoint;
mClosestDistanceSquared = FLT_MAX;
mClosestPoint = PxVec3(0.0f);
mClosestTetId = -1;
}
PX_FORCE_INLINE const PxVec3& getClosestPoint() const
{
return mClosestPoint;
}
PX_FORCE_INLINE PxReal distancePointBoxSquared(const PxBounds3& box, const PxVec3& point)
{
PxVec3 closestPt = box.minimum.maximum(box.maximum.minimum(point));
return (closestPt - point).magnitudeSquared();
}
PX_FORCE_INLINE Gu::TraversalControl::Enum analyze(const Gu::BVHNode& node, PxI32)
{
if (distancePointBoxSquared(node.mBV, mQueryPoint) >= mClosestDistanceSquared)
return Gu::TraversalControl::eDontGoDeeper;
if (node.isLeaf())
{
const PxI32 j = node.getPrimitiveIndex();
const PxU32* tet = &mTetrahedra[4 * j];
PxVec4 bary;
computeBarycentric(mPoints[tet[0]], mPoints[tet[1]], mPoints[tet[2]], mPoints[tet[3]], mQueryPoint, bary);
const PxReal tolerance = 0.0f;
if (bary.x >= -tolerance && bary.x <= 1 + tolerance && bary.y >= -tolerance && bary.y <= 1 + tolerance &&
bary.z >= -tolerance && bary.z <= 1 + tolerance && bary.w >= -tolerance && bary.w <= 1 + tolerance)
{
mClosestDistanceSquared = 0;
mClosestTetId = j;
mClosestPoint = mQueryPoint;
return Gu::TraversalControl::eAbort;
}
PxVec3 closest = Gu::closestPtPointTetrahedron(mQueryPoint, mPoints[tet[0]], mPoints[tet[1]], mPoints[tet[2]], mPoints[tet[3]]);
PxReal d2 = (closest - mQueryPoint).magnitudeSquared();
if (d2 < mClosestDistanceSquared)
{
mClosestDistanceSquared = d2;
mClosestTetId = j;
mClosestPoint = closest;
}
return Gu::TraversalControl::eDontGoDeeper;
}
const Gu::BVHNode& nodePos = mNodes[node.getPosIndex()];
const PxReal distSquaredPos = distancePointBoxSquared(nodePos.mBV, mQueryPoint);
const Gu::BVHNode& nodeNeg = mNodes[node.getNegIndex()];
const PxReal distSquaredNeg = distancePointBoxSquared(nodeNeg.mBV, mQueryPoint);
if (distSquaredPos < distSquaredNeg)
{
if (distSquaredPos < mClosestDistanceSquared)
return Gu::TraversalControl::eGoDeeper;
}
else
{
if (distSquaredNeg < mClosestDistanceSquared)
return Gu::TraversalControl::eGoDeeperNegFirst;
}
return Gu::TraversalControl::eDontGoDeeper;
}
PxI32 getClosestTetId() const { return mClosestTetId; }
void setClosestStart(const PxReal closestDistanceSquared, PxI32 closestTetrahedron, const PxVec3& closestPoint)
{
mClosestDistanceSquared = closestDistanceSquared;
mClosestTetId = closestTetrahedron;
mClosestPoint = closestPoint;
}
private:
PX_NOCOPY(ClosestDistanceToTetmeshTraversalController)
};
static void buildTree(const PxU32* tetrahedra, const PxU32 numTetrahedra, const PxVec3* points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f)
{
//Computes a bounding box for every triangle in triangles
Gu::AABBTreeBounds boxes;
boxes.init(numTetrahedra);
for (PxU32 i = 0; i < numTetrahedra; ++i)
{
const PxU32* tri = &tetrahedra[4 * i];
PxBounds3 box = PxBounds3::empty();
box.include(points[tri[0]]);
box.include(points[tri[1]]);
box.include(points[tri[2]]);
box.include(points[tri[3]]);
box.fattenFast(enlargement);
boxes.getBounds()[i] = box;
}
Gu::buildAABBTree(numTetrahedra, boxes, tree);
}
void PxTetrahedronMeshExt::createPointsToTetrahedronMap(const PxArray<PxVec3>& tetMeshVertices, const PxArray<PxU32>& tetMeshIndices,
const PxArray<PxVec3>& pointsToEmbed, PxArray<PxVec4>& barycentricCoordinates, PxArray<PxU32>& tetLinks)
{
PxArray<Gu::BVHNode> tree;
buildTree(tetMeshIndices.begin(), tetMeshIndices.size() / 4, tetMeshVertices.begin(), tree);
ClosestDistanceToTetmeshTraversalController cd(tetMeshIndices.begin(), tetMeshVertices.begin(), tree.begin());
barycentricCoordinates.resize(pointsToEmbed.size());
tetLinks.resize(pointsToEmbed.size());
for (PxU32 i = 0; i < pointsToEmbed.size(); ++i)
{
cd.setQueryPoint(pointsToEmbed[i]);
Gu::traverseBVH(tree.begin(), cd);
const PxU32* tet = &tetMeshIndices[4 * cd.getClosestTetId()];
PxVec4 bary;
computeBarycentric(tetMeshVertices[tet[0]], tetMeshVertices[tet[1]], tetMeshVertices[tet[2]], tetMeshVertices[tet[3]], cd.getClosestPoint(), bary);
barycentricCoordinates[i] = bary;
tetLinks[i] = cd.getClosestTetId();
}
}
struct SortedTriangle
{
public:
PxU32 A;
PxU32 B;
PxU32 C;
PxI32 TetIndex;
bool Flipped;
PX_FORCE_INLINE SortedTriangle(PxU32 a, PxU32 b, PxU32 c, PxI32 tetIndex = -1)
{
A = a; B = b; C = c; Flipped = false; TetIndex = tetIndex;
if (A > B) { PxSwap(A, B); Flipped = !Flipped; }
if (B > C) { PxSwap(B, C); Flipped = !Flipped; }
if (A > B) { PxSwap(A, B); Flipped = !Flipped; }
}
};
struct TriangleHash
{
PX_FORCE_INLINE std::size_t operator()(const SortedTriangle& k) const
{
return k.A ^ k.B ^ k.C;
}
PX_FORCE_INLINE bool equal(const SortedTriangle& first, const SortedTriangle& second) const
{
return first.A == second.A && first.B == second.B && first.C == second.C;
}
};
static const PxU32 tetFaces[4][3] = { {0, 2, 1}, {0, 1, 3}, {0, 3, 2}, {1, 2, 3} };
void PxTetrahedronMeshExt::extractTetMeshSurface(const void* tetrahedra, PxU32 numTetrahedra, bool sixteenBitIndices, PxArray<PxU32>& surfaceTriangles, PxArray<PxU32>* surfaceTriangleToTet, bool flipTriangleOrientation)
{
PxHashMap<SortedTriangle, PxU32, TriangleHash> tris;
const PxU32* tets32 = reinterpret_cast<const PxU32*>(tetrahedra);
const PxU16* tets16 = reinterpret_cast<const PxU16*>(tetrahedra);
PxU32 l = 4 * numTetrahedra;
for (PxU32 i = 0; i < l; i += 4)
{
for (PxU32 j = 0; j < 4; ++j)
{
SortedTriangle tri(sixteenBitIndices ? tets16[i + tetFaces[j][0]] : tets32[i + tetFaces[j][0]],
sixteenBitIndices ? tets16[i + tetFaces[j][1]] : tets32[i + tetFaces[j][1]],
sixteenBitIndices ? tets16[i + tetFaces[j][2]] : tets32[i + tetFaces[j][2]], i);
if (const PxPair<const SortedTriangle, PxU32>* ptr = tris.find(tri))
tris[tri] = ptr->second + 1;
else
tris.insert(tri, 1);
}
}
surfaceTriangles.clear();
if (surfaceTriangleToTet)
surfaceTriangleToTet->clear();
for (PxHashMap<SortedTriangle, PxU32, TriangleHash>::Iterator iter = tris.getIterator(); !iter.done(); ++iter)
{
if (iter->second == 1) {
surfaceTriangles.pushBack(iter->first.A);
if (iter->first.Flipped != flipTriangleOrientation)
{
surfaceTriangles.pushBack(iter->first.C);
surfaceTriangles.pushBack(iter->first.B);
}
else
{
surfaceTriangles.pushBack(iter->first.B);
surfaceTriangles.pushBack(iter->first.C);
}
if (surfaceTriangleToTet)
surfaceTriangleToTet->pushBack(iter->first.TetIndex);
}
}
}
void PxTetrahedronMeshExt::extractTetMeshSurface(const PxTetrahedronMesh* mesh, PxArray<PxU32>& surfaceTriangles, PxArray<PxU32>* surfaceTriangleToTet, bool flipTriangleOrientation)
{
extractTetMeshSurface(mesh->getTetrahedrons(), mesh->getNbTetrahedrons(), mesh->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES, surfaceTriangles, surfaceTriangleToTet, flipTriangleOrientation);
}
}
| 16,167 | C++ | 35.089286 | 220 | 0.705326 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtTetMakerExt.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 "tet/ExtDelaunayBoundaryInserter.h"
#include "extensions/PxTetMakerExt.h"
#include "cooking/PxTetrahedronMeshDesc.h"
#include "geometry/PxTriangleMesh.h"
#include "tet/ExtMeshSimplificator.h"
#include "tet/ExtRemesher.h"
#include "tet/ExtOctreeTetrahedralizer.h"
#include "tet/ExtVoxelTetrahedralizer.h"
#include "foundation/PxMat33.h"
#include <stdio.h>
using namespace physx;
PX_FORCE_INLINE PxReal computeTetrahedronVolume(const PxVec3& x0, const PxVec3& x1, const PxVec3& x2, const PxVec3& x3)
{
const PxVec3 u1 = x1 - x0;
const PxVec3 u2 = x2 - x0;
const PxVec3 u3 = x3 - x0;
PxMat33 edgeMatrix = PxMat33(u1, u2, u3);
const PxReal det = edgeMatrix.getDeterminant();
const PxReal volume = det / 6.0f;
return volume;
}
//Remove tets with small volume
void removeSmallVolumeTetrahedra(PxArray<::physx::PxVec3>& vertices, PxArray<PxU32>& indices, PxReal volumeThreshold = 1e-8f)
{
uint32_t indexer = 0;
for (uint32_t i = 0; i < indices.size(); i += 4)
{
for (uint32_t j = 0; j < 4; ++j)
{
indices[indexer + j] = indices[i + j];
}
if (computeTetrahedronVolume(vertices[indices[i]], vertices[indices[i + 1]], vertices[indices[i + 2]], vertices[indices[i + 3]]) >= volumeThreshold)
{
indexer += 4;
}
}
if (indexer < indices.size())
{
indices.removeRange(indexer, indices.size() - indexer);
}
}
//Removes vertices not referenced by any tetrahedron and maps the tet's indices to match the compacted vertex list
void removeUnusedVertices(PxArray<::physx::PxVec3>& vertices, PxArray<PxU32>& tets, PxU32 numPointsToKeepAtBeginning = 0)
{
PxArray<PxI32> compressorMap;
compressorMap.resize(vertices.size());
for (PxU32 i = 0; i < numPointsToKeepAtBeginning; ++i)
compressorMap[i] = 0;
for (PxU32 i = numPointsToKeepAtBeginning; i < compressorMap.size(); ++i)
compressorMap[i] = -1;
for (PxU32 i = 0; i < tets.size(); i += 4)
{
const PxU32* tet = &tets[i];
if (tet[0] == 0xFFFFFFFFu)
continue;
compressorMap[tet[0]] = 0;
compressorMap[tet[1]] = 0;
compressorMap[tet[2]] = 0;
compressorMap[tet[3]] = 0;
}
PxU32 indexer = 0;
for (PxU32 i = 0; i < compressorMap.size(); ++i)
{
if (compressorMap[i] >= 0)
{
compressorMap[i] = indexer;
vertices[indexer] = vertices[i];
indexer++;
}
}
for (PxU32 i = 0; i < tets.size(); i += 4)
{
PxU32* tet = &tets[i];
if (tet[0] == 0xFFFFFFFFu)
continue;
tet[0] = compressorMap[tet[0]];
tet[1] = compressorMap[tet[1]];
tet[2] = compressorMap[tet[2]];
tet[3] = compressorMap[tet[3]];
}
if (indexer < vertices.size())
vertices.removeRange(indexer, vertices.size() - indexer);
}
PX_FORCE_INLINE PxU64 buildKey(PxI32 a, PxI32 b)
{
if (a < b)
return ((PxU64(a)) << 32) | (PxU64(b));
else
return ((PxU64(b)) << 32) | (PxU64(a));
}
static const PxI32 neighborEdgeList[3][2] = { { 0, 1 }, { 0, 2 }, { 1, 2 } };
static void buildTriangleNeighborhood(const PxI32* tris, PxU32 numTris, PxArray<PxI32>& result)
{
PxU32 l = 4 * numTris; //Waste one element in neighborhood info but allow bit shift access instead
result.clear();
result.resize(l, -1);
PxHashMap<PxU64, PxI32> faces;
for (PxU32 i = 0; i < numTris; ++i)
{
const PxI32* tri = &tris[3 * i];
if (tris[0] < 0)
continue;
for (PxI32 j = 0; j < 3; ++j)
{
PxU64 key = buildKey(tri[neighborEdgeList[j][0]], tri[neighborEdgeList[j][1]]);
if (const PxPair<const PxU64, PxI32>* ptr = faces.find(key))
{
if (ptr->second < 0)
{
//PX_ASSERT(false); //Invalid tetmesh since a face is shared by more than 2 tetrahedra
continue;
}
result[4 * i + j] = ptr->second;
result[ptr->second] = 4 * i + j;
faces[key] = -1;
}
else
faces.insert(key, 4 * i + j);
}
}
}
void PxTetMaker::detectTriangleIslands(const PxI32* triangles, PxU32 numTriangles, PxArray<PxU32>& islandIndexPerTriangle)
{
//Detect islands
PxArray<PxI32> neighborhood;
buildTriangleNeighborhood(triangles, numTriangles, neighborhood);
const PxU32 noIslandAssignedMarker = 0xFFFFFFFF;
islandIndexPerTriangle.resize(numTriangles, noIslandAssignedMarker);
PxU32 start = 0;
PxI32 color = -1;
PxArray<PxI32> stack;
while (true)
{
stack.clear();
while (start < islandIndexPerTriangle.size())
{
if (islandIndexPerTriangle[start] == noIslandAssignedMarker)
{
stack.pushBack(start);
++color;
islandIndexPerTriangle[start] = color;
break;
}
++start;
}
if (start == islandIndexPerTriangle.size())
break;
while (stack.size() > 0)
{
PxI32 id = stack.popBack();
for (PxI32 i = 0; i < 3; ++i)
{
PxI32 a = neighborhood[4 * id + i];
PxI32 tetId = a >> 2;
if (tetId >= 0 && islandIndexPerTriangle[tetId] == noIslandAssignedMarker)
{
stack.pushBack(tetId);
islandIndexPerTriangle[tetId] = color;
}
}
}
}
}
PxU32 PxTetMaker::findLargestIslandId(const PxU32* islandIndexPerTriangle, PxU32 numTriangles)
{
PxU32 numIslands = 0;
for (PxU32 i = 0; i < numTriangles; ++i)
numIslands = PxMax(numIslands, islandIndexPerTriangle[i]);
++numIslands;
PxArray<PxU32> numEntriesPerColor;
numEntriesPerColor.resize(numIslands, 0);
for (PxU32 i = 0; i < numTriangles; ++i)
numEntriesPerColor[islandIndexPerTriangle[i]] += 1;
PxU32 colorWithHighestTetCount = 0;
for (PxU32 i = 1; i < numEntriesPerColor.size(); ++i)
if (numEntriesPerColor[i] > numEntriesPerColor[colorWithHighestTetCount])
colorWithHighestTetCount = i;
return colorWithHighestTetCount;
}
bool PxTetMaker::createConformingTetrahedronMesh(const PxSimpleTriangleMesh& triangleMesh,
physx::PxArray<physx::PxVec3>& outVertices, physx::PxArray<physx::PxU32>& outTetIndices, const bool validate, PxReal volumeThreshold)
{
if (validate)
{
PxTriangleMeshAnalysisResults result = PxTetMaker::validateTriangleMesh(triangleMesh);
if (result & PxTriangleMeshAnalysisResult::eMESH_IS_INVALID)
{
PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "createConformingTetrahedronMesh(): Input triangle mesh is not suited to create a tetmesh due to deficiencies. Please call PxTetMaker::validateTriangleMesh(triangleMesh) for more details.");
return false;
}
}
Ext::generateTetmesh(triangleMesh.points, triangleMesh.triangles, triangleMesh.flags & PxMeshFlag::e16_BIT_INDICES, outVertices, outTetIndices);
if (volumeThreshold > 0.0f)
removeSmallVolumeTetrahedra(outVertices, outTetIndices, volumeThreshold);
PxU32 numRemoveAtEnd = Ext::removeDisconnectedIslands(reinterpret_cast<PxI32*>(outTetIndices.begin()), outTetIndices.size() / 4);
if (numRemoveAtEnd > 0)
outTetIndices.removeRange(outTetIndices.size() - 4 * numRemoveAtEnd, 4 * numRemoveAtEnd);
removeUnusedVertices(outVertices, outTetIndices, triangleMesh.points.count);
return true;
}
bool PxTetMaker::createVoxelTetrahedronMesh(const PxTetrahedronMeshDesc& tetMesh,
const PxU32 numVoxelsAlongLongestBoundingBoxAxis, physx::PxArray<physx::PxVec3>& outVertices, physx::PxArray<physx::PxU32>& outTetIndices,
PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel)
{
//numTetsPerVoxel has only two valid values.
if (numTetsPerVoxel != 5 && numTetsPerVoxel != 6)
numTetsPerVoxel = 5;
Ext::generateVoxelTetmesh(tetMesh.points, tetMesh.tetrahedrons, numVoxelsAlongLongestBoundingBoxAxis, outVertices, outTetIndices, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel);
return true;
}
bool PxTetMaker::createVoxelTetrahedronMeshFromEdgeLength(const PxTetrahedronMeshDesc& tetMesh,
const PxReal voxelEdgeLength, physx::PxArray<physx::PxVec3>& outVertices, physx::PxArray<physx::PxU32>& outTetIndices,
PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel)
{
//numTetsPerVoxel has only two valid values.
if (numTetsPerVoxel != 5 && numTetsPerVoxel != 6)
numTetsPerVoxel = 5;
Ext::generateVoxelTetmesh(tetMesh.points, tetMesh.tetrahedrons, voxelEdgeLength, outVertices, outTetIndices, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel);
return true;
}
PxTriangleMeshAnalysisResults PxTetMaker::validateTriangleMesh(const PxSimpleTriangleMesh& triangleMesh, const PxReal minVolumeThreshold, const PxReal minTriangleAngleRadians)
{
return Ext::validateTriangleMesh(triangleMesh.points, triangleMesh.triangles, triangleMesh.flags & PxMeshFlag::e16_BIT_INDICES, minVolumeThreshold, minTriangleAngleRadians);
}
PxTetrahedronMeshAnalysisResults PxTetMaker::validateTetrahedronMesh(const PxBoundedData& points, const PxBoundedData& tetrahedra, const PxReal minTetVolumeThreshold)
{
return Ext::validateTetrahedronMesh(points, tetrahedra, false, minTetVolumeThreshold);
}
void PxTetMaker::simplifyTriangleMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices, int targetTriangleCount, PxF32 maximalEdgeLength,
PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices,
PxArray<PxU32> *vertexMap, PxReal edgeLengthCostWeight, PxReal flatnessDetectionThreshold,
bool projectSimplifiedPointsOnInputMeshSurface, PxArray<PxU32>* outputVertexToInputTriangle, bool removeDisconnectedPatches)
{
Ext::MeshSimplificator ms;
PxArray<PxU32> indexMapToFullTriangleSet;
if (removeDisconnectedPatches)
{
PxU32 numTriangles = inputIndices.size() / 3;
PxArray<PxU32> islandIndexPerTriangle;
PxTetMaker::detectTriangleIslands(reinterpret_cast<const PxI32*>(inputIndices.begin()), numTriangles, islandIndexPerTriangle);
PxU32 biggestIslandIndex = PxTetMaker::findLargestIslandId(islandIndexPerTriangle.begin(), islandIndexPerTriangle.size());
PxArray<PxU32> connectedTriangleSet;
for (PxU32 i = 0; i < numTriangles; ++i)
{
if (islandIndexPerTriangle[i] == biggestIslandIndex)
{
for (PxU32 j = 0; j < 3; ++j)
connectedTriangleSet.pushBack(inputIndices[3 * i + j]);
indexMapToFullTriangleSet.pushBack(i);
}
}
ms.init(inputVertices, connectedTriangleSet, edgeLengthCostWeight, flatnessDetectionThreshold, projectSimplifiedPointsOnInputMeshSurface);
ms.decimateBySize(targetTriangleCount, maximalEdgeLength);
ms.readBack(outputVertices, outputIndices, vertexMap, outputVertexToInputTriangle);
}
else
{
ms.init(inputVertices, inputIndices, edgeLengthCostWeight, flatnessDetectionThreshold, projectSimplifiedPointsOnInputMeshSurface);
ms.decimateBySize(targetTriangleCount, maximalEdgeLength);
ms.readBack(outputVertices, outputIndices, vertexMap, outputVertexToInputTriangle);
}
if (removeDisconnectedPatches && projectSimplifiedPointsOnInputMeshSurface && outputVertexToInputTriangle)
{
for (PxU32 i = 0; i < outputVertexToInputTriangle->size(); ++i)
(*outputVertexToInputTriangle)[i] = indexMapToFullTriangleSet[(*outputVertexToInputTriangle)[i]];
}
}
void PxTetMaker::remeshTriangleMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices, PxU32 gridResolution,
PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxArray<PxU32> *vertexMap)
{
Ext::Remesher rm;
rm.remesh(inputVertices, inputIndices, gridResolution, vertexMap);
rm.readBack(outputVertices, outputIndices);
}
void PxTetMaker::remeshTriangleMesh(const PxVec3* inputVertices, PxU32 nbVertices, const PxU32* inputIndices, PxU32 nbIndices, PxU32 gridResolution,
PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxArray<PxU32> *vertexMap)
{
Ext::Remesher rm;
rm.remesh(inputVertices, nbVertices, inputIndices, nbIndices, gridResolution, vertexMap);
rm.readBack(outputVertices, outputIndices);
}
void PxTetMaker::createTreeBasedTetrahedralMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices,
bool useTreeNodes, PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxReal volumeThreshold)
{
Ext::OctreeTetrahedralizer ot;
ot.createTetMesh(inputVertices, inputIndices, useTreeNodes);
ot.readBack(outputVertices, outputIndices);
if (volumeThreshold > 0.0f)
removeSmallVolumeTetrahedra(outputVertices, outputIndices, volumeThreshold);
PxU32 numRemoveAtEnd = Ext::removeDisconnectedIslands(reinterpret_cast<PxI32*>(outputIndices.begin()), outputIndices.size() / 4);
if (numRemoveAtEnd > 0)
outputIndices.removeRange(outputIndices.size() - 4 * numRemoveAtEnd, 4 * numRemoveAtEnd);
removeUnusedVertices(outputVertices, outputIndices, inputVertices.size());
}
void PxTetMaker::createRelaxedVoxelTetrahedralMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices,
PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices,
PxI32 resolution, PxI32 numRelaxationIters, PxF32 relMinTetVolume)
{
Ext::VoxelTetrahedralizer vt;
vt.createTetMesh(inputVertices, inputIndices, resolution, numRelaxationIters, relMinTetVolume);
vt.readBack(outputVertices, outputIndices);
}
| 14,404 | C++ | 36.415584 | 250 | 0.752152 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRevoluteJoint.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 "ExtRevoluteJoint.h"
#include "ExtConstraintHelper.h"
#include "omnipvd/ExtOmniPvdSetData.h"
using namespace physx;
using namespace Ext;
RevoluteJoint::RevoluteJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) :
RevoluteJointT(PxJointConcreteType::eREVOLUTE, actor0, localFrame0, actor1, localFrame1, "RevoluteJointData")
{
RevoluteJointData* data = static_cast<RevoluteJointData*>(mData);
data->driveForceLimit = PX_MAX_F32;
data->driveVelocity = 0.0f;
data->driveGearRatio = 1.0f;
data->limit = PxJointAngularLimitPair(-PxPi/2, PxPi/2);
data->jointFlags = PxRevoluteJointFlags();
}
PxReal RevoluteJoint::getAngle() const
{
return getTwistAngle_Internal();
}
PxReal RevoluteJoint::getVelocity() const
{
return getRelativeAngularVelocity().magnitude();
}
PxJointAngularLimitPair RevoluteJoint::getLimit() const
{
return data().limit;
}
void RevoluteJoint::setLimit(const PxJointAngularLimitPair& limit)
{
PX_CHECK_AND_RETURN(limit.isValid(), "PxRevoluteJoint::setLimit: limit invalid");
PX_CHECK_AND_RETURN(limit.lower>-PxTwoPi && limit.upper<PxTwoPi , "PxRevoluteJoint::twist limit must be strictly between -2*PI and 2*PI");
data().limit = limit;
markDirty();
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxRevoluteJoint& j = static_cast<PxRevoluteJoint&>(*this);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitLower, j, limit.lower)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitUpper, j, limit.upper)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitRestitution, j, limit.restitution)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitBounceThreshold, j, limit.bounceThreshold)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitStiffness, j, limit.stiffness)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitDamping, j, limit.damping)
OMNI_PVD_WRITE_SCOPE_END
#endif
}
PxReal RevoluteJoint::getDriveVelocity() const
{
return data().driveVelocity;
}
void RevoluteJoint::setDriveVelocity(PxReal velocity, bool autowake)
{
PX_CHECK_AND_RETURN(PxIsFinite(velocity), "PxRevoluteJoint::setDriveVelocity: invalid parameter");
data().driveVelocity = velocity;
if(autowake)
wakeUpActors();
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveVelocity, static_cast<PxRevoluteJoint&>(*this), velocity)
}
PxReal RevoluteJoint::getDriveForceLimit() const
{
return data().driveForceLimit;
}
void RevoluteJoint::setDriveForceLimit(PxReal forceLimit)
{
PX_CHECK_AND_RETURN(PxIsFinite(forceLimit), "PxRevoluteJoint::setDriveForceLimit: invalid parameter");
data().driveForceLimit = forceLimit;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveForceLimit, static_cast<PxRevoluteJoint&>(*this), forceLimit)
}
PxReal RevoluteJoint::getDriveGearRatio() const
{
return data().driveGearRatio;
}
void RevoluteJoint::setDriveGearRatio(PxReal gearRatio)
{
PX_CHECK_AND_RETURN(PxIsFinite(gearRatio) && gearRatio>0, "PxRevoluteJoint::setDriveGearRatio: invalid parameter");
data().driveGearRatio = gearRatio;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveGearRatio, static_cast<PxRevoluteJoint&>(*this), gearRatio)
}
PxRevoluteJointFlags RevoluteJoint::getRevoluteJointFlags(void) const
{
return data().jointFlags;
}
void RevoluteJoint::setRevoluteJointFlags(PxRevoluteJointFlags flags)
{
data().jointFlags = flags;
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, jointFlags, static_cast<PxRevoluteJoint&>(*this), flags)
}
void RevoluteJoint::setRevoluteJointFlag(PxRevoluteJointFlag::Enum flag, bool value)
{
if(value)
data().jointFlags |= flag;
else
data().jointFlags &= ~flag;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, jointFlags, static_cast<PxRevoluteJoint&>(*this), getRevoluteJointFlags())
}
static PxQuat computeTwist(const PxTransform& cA2w, const PxTransform& cB2w)
{
// PT: following code is the same as this part of the "getAngle" function:
// const PxQuat q = getRelativeTransform().q;
// PxQuat swing, twist;
// PxSeparateSwingTwist(q, swing, twist);
// But it's done a little bit more efficiently since we don't need the swing quat.
// PT: rotation part of "const PxTransform cB2cA = cA2w.transformInv(cB2w);"
const PxQuat cB2cAq = cA2w.q.getConjugate() * cB2w.q;
// PT: twist part of "PxSeparateSwingTwist(cB2cAq,swing,twist)" (more or less)
return PxQuat(cB2cAq.x, 0.0f, 0.0f, cB2cAq.w);
}
// PT: this version is similar to the "getAngle" function, but the twist is computed slightly differently.
static PX_FORCE_INLINE PxReal computePhi(const PxTransform& cA2w, const PxTransform& cB2w)
{
PxQuat twist = computeTwist(cA2w, cB2w);
twist.normalize();
PxReal angle = twist.getAngle();
if(twist.x<0.0f)
angle = -angle;
return angle;
}
static void RevoluteJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags)
{
const RevoluteJointData& data = *reinterpret_cast<const RevoluteJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform);
if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES)
viz.visualizeJointFrames(cA2w, cB2w);
if((data.jointFlags & PxRevoluteJointFlag::eLIMIT_ENABLED) && (flags & PxConstraintVisualizationFlag::eLIMITS))
viz.visualizeAngularLimit(cA2w, data.limit.lower, data.limit.upper);
}
//TAG:solverprepshader
static PxU32 RevoluteJointSolverPrep(Px1DConstraint* constraints,
PxVec3p& body0WorldOffset,
PxU32 /*maxConstraints*/,
PxConstraintInvMassScale& invMassScale,
const void* constantBlock,
const PxTransform& bA2w,
const PxTransform& bB2w,
bool useExtendedLimits,
PxVec3p& cA2wOut, PxVec3p& cB2wOut)
{
const RevoluteJointData& data = *reinterpret_cast<const RevoluteJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w);
const PxJointAngularLimitPair& limit = data.limit;
const bool limitEnabled = data.jointFlags & PxRevoluteJointFlag::eLIMIT_ENABLED;
const bool limitIsLocked = limitEnabled && limit.lower >= limit.upper;
// PT: it is a mistake to use the neighborhood operator since it
// prevents us from using the quat's double-cover feature.
if(!useExtendedLimits)
joint::applyNeighborhoodOperator(cA2w, cB2w);
PxVec3 ra, rb, axis;
ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, PxU32(limitIsLocked ? 7 : 6), ra, rb, &axis);
cA2wOut = ra + bA2w.p;
cB2wOut = rb + bB2w.p;
if(limitIsLocked)
return ch.getCount();
if(data.jointFlags & PxRevoluteJointFlag::eDRIVE_ENABLED)
{
Px1DConstraint* c = ch.getConstraintRow();
c->solveHint = PxConstraintSolveHint::eNONE;
c->linear0 = PxVec3(0.0f);
c->angular0 = -axis;
c->linear1 = PxVec3(0.0f);
c->angular1 = -axis * data.driveGearRatio;
c->velocityTarget = data.driveVelocity;
c->minImpulse = -data.driveForceLimit;
c->maxImpulse = data.driveForceLimit;
c->flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT;
if(data.jointFlags & PxRevoluteJointFlag::eDRIVE_FREESPIN)
{
if(data.driveVelocity > 0.0f)
c->minImpulse = 0.0f;
if(data.driveVelocity < 0.0f)
c->maxImpulse = 0.0f;
}
c->flags |= Px1DConstraintFlag::eHAS_DRIVE_LIMIT;
}
if(limitEnabled)
{
const PxReal phi = computePhi(cA2w, cB2w);
ch.anglePair(phi, data.limit.lower, data.limit.upper, axis, limit);
}
return ch.getCount();
}
///////////////////////////////////////////////////////////////////////////////
static PxConstraintShaderTable gRevoluteJointShaders = { RevoluteJointSolverPrep, RevoluteJointVisualize, PxConstraintFlag::Enum(0) };
PxConstraintSolverPrep RevoluteJoint::getPrep() const { return gRevoluteJointShaders.solverPrep; }
// PT: for tests / benchmarks
PxConstraintSolverPrep getRevoluteJointPrep() { return gRevoluteJointShaders.solverPrep; }
PxRevoluteJoint* physx::PxRevoluteJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1)
{
PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxRevoluteJointCreate: local frame 0 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxRevoluteJointCreate: local frame 1 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxRevoluteJointCreate: actors must be different");
PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxRevoluteJointCreate: at least one actor must be dynamic");
return createJointT<RevoluteJoint, RevoluteJointData>(physics, actor0, localFrame0, actor1, localFrame1, gRevoluteJointShaders);
}
// PX_SERIALIZATION
void RevoluteJoint::resolveReferences(PxDeserializationContext& context)
{
mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gRevoluteJointShaders);
}
//~PX_SERIALIZATION
#if PX_SUPPORT_OMNI_PVD
void RevoluteJoint::updateOmniPvdProperties() const
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
const PxRevoluteJoint& j = static_cast<const PxRevoluteJoint&>(*this);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, angle, j, getAngle())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, velocity, j, getVelocity())
OMNI_PVD_WRITE_SCOPE_END
}
template<>
void physx::Ext::omniPvdInitJoint<RevoluteJoint>(RevoluteJoint& joint)
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxRevoluteJoint& j = static_cast<PxRevoluteJoint&>(joint);
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, j);
omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eREVOLUTE);
PxJointAngularLimitPair limit = joint.getLimit();
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitLower, j, limit.lower)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitUpper, j, limit.upper)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitRestitution, j, limit.restitution)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitBounceThreshold, j, limit.bounceThreshold)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitStiffness, j, limit.stiffness)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitDamping, j, limit.damping)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveVelocity, j, joint.getDriveVelocity())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveForceLimit, j, joint.getDriveForceLimit())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveGearRatio, j, joint.getDriveGearRatio())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, jointFlags, j, joint.getRevoluteJointFlags())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, angle, j, joint.getAngle())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, velocity, j, joint.getVelocity())
OMNI_PVD_WRITE_SCOPE_END
}
#endif
| 13,481 | C++ | 40.103658 | 175 | 0.768563 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtPrismaticJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_PRISMATIC_JOINT_H
#define EXT_PRISMATIC_JOINT_H
#include "common/PxTolerancesScale.h"
#include "extensions/PxPrismaticJoint.h"
#include "ExtJoint.h"
#include "CmUtils.h"
namespace physx
{
struct PxPrismaticJointGeneratedValues;
namespace Ext
{
struct PrismaticJointData : public JointData
{
PxJointLinearLimitPair limit;
PxPrismaticJointFlags jointFlags;
private:
PrismaticJointData(const PxJointLinearLimitPair& pair) : limit(pair) {}
};
typedef JointT<PxPrismaticJoint, PrismaticJointData, PxPrismaticJointGeneratedValues> PrismaticJointT;
class PrismaticJoint : public PrismaticJointT
{
public:
// PX_SERIALIZATION
PrismaticJoint(PxBaseFlags baseFlags) : PrismaticJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static PrismaticJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<PrismaticJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
PrismaticJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxPrismaticJoint
virtual PxReal getPosition() const PX_OVERRIDE { return getRelativeTransform().p.x; }
virtual PxReal getVelocity() const PX_OVERRIDE { return getRelativeLinearVelocity().x; }
virtual void setLimit(const PxJointLinearLimitPair& limit) PX_OVERRIDE;
virtual PxJointLinearLimitPair getLimit() const PX_OVERRIDE;
virtual void setPrismaticJointFlags(PxPrismaticJointFlags flags) PX_OVERRIDE;
virtual void setPrismaticJointFlag(PxPrismaticJointFlag::Enum flag, bool value) PX_OVERRIDE;
virtual PxPrismaticJointFlags getPrismaticJointFlags() const PX_OVERRIDE;
//~PxPrismaticJoint
// PxConstraintConnector
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
#if PX_SUPPORT_OMNI_PVD
virtual void updateOmniPvdProperties() const PX_OVERRIDE;
#endif
//~PxConstraintConnector
};
} // namespace Ext
} // namespace physx
#endif
| 3,798 | C | 42.666666 | 165 | 0.775145 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSharedQueueEntryPool.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_SHARED_QUEUE_ENTRY_POOL_H
#define EXT_SHARED_QUEUE_ENTRY_POOL_H
#include "foundation/PxAllocator.h"
#include "foundation/PxArray.h"
#include "foundation/PxSList.h"
namespace physx
{
namespace Ext
{
class SharedQueueEntry : public PxSListEntry
{
public:
SharedQueueEntry(void* objectRef) : mObjectRef(objectRef), mPooledEntry(false) {}
SharedQueueEntry() : mObjectRef(NULL), mPooledEntry(true) {}
public:
void* mObjectRef;
bool mPooledEntry; // True if the entry was preallocated in a pool
};
#if PX_VC
#pragma warning(push)
#pragma warning(disable:4324) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif // Because of the SList member I assume*/
template<class Alloc = typename PxAllocatorTraits<SharedQueueEntry>::Type >
class SharedQueueEntryPool : private Alloc
{
public:
SharedQueueEntryPool(PxU32 poolSize, const Alloc& alloc = Alloc("SharedQueueEntryPool"));
~SharedQueueEntryPool();
SharedQueueEntry* getEntry(void* objectRef);
void putEntry(SharedQueueEntry& entry);
private:
SharedQueueEntry* mTaskEntryPool;
PxSList mTaskEntryPtrPool;
};
#if PX_VC
#pragma warning(pop)
#endif
template <class Alloc>
SharedQueueEntryPool<Alloc>::SharedQueueEntryPool(PxU32 poolSize, const Alloc& alloc)
: Alloc(alloc)
{
PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc("SharedQueueEntryPool");
mTaskEntryPool = poolSize ? reinterpret_cast<SharedQueueEntry*>(alignedAlloc.allocate(sizeof(SharedQueueEntry) * poolSize, PX_FL)) : NULL;
if (mTaskEntryPool)
{
for(PxU32 i=0; i < poolSize; i++)
{
PX_ASSERT((size_t(&mTaskEntryPool[i]) & (PX_SLIST_ALIGNMENT-1)) == 0); // The SList entry must be aligned according to PX_SLIST_ALIGNMENT
PX_PLACEMENT_NEW(&mTaskEntryPool[i], SharedQueueEntry)();
PX_ASSERT(mTaskEntryPool[i].mPooledEntry == true);
mTaskEntryPtrPool.push(mTaskEntryPool[i]);
}
}
}
template <class Alloc>
SharedQueueEntryPool<Alloc>::~SharedQueueEntryPool()
{
if (mTaskEntryPool)
{
PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc("SharedQueueEntryPool");
alignedAlloc.deallocate(mTaskEntryPool);
}
}
template <class Alloc>
SharedQueueEntry* SharedQueueEntryPool<Alloc>::getEntry(void* objectRef)
{
SharedQueueEntry* e = static_cast<SharedQueueEntry*>(mTaskEntryPtrPool.pop());
if (e)
{
PX_ASSERT(e->mPooledEntry == true);
e->mObjectRef = objectRef;
return e;
}
else
{
PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc;
e = reinterpret_cast<SharedQueueEntry*>(alignedAlloc.allocate(sizeof(SharedQueueEntry), PX_FL));
if (e)
{
PX_PLACEMENT_NEW(e, SharedQueueEntry)(objectRef);
PX_ASSERT(e->mPooledEntry == false);
}
return e;
}
}
template <class Alloc>
void SharedQueueEntryPool<Alloc>::putEntry(SharedQueueEntry& entry)
{
if (entry.mPooledEntry)
{
entry.mObjectRef = NULL;
mTaskEntryPtrPool.push(entry);
}
else
{
PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc;
alignedAlloc.deallocate(&entry);
}
}
} // namespace Ext
} // namespace physx
#endif
| 4,780 | C | 30.453947 | 141 | 0.748954 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqQuery.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_SQ_QUERY_H
#define EXT_SQ_QUERY_H
#include "foundation/PxSimpleTypes.h"
#include "geometry/PxGeometryQueryFlags.h"
#include "ExtSqManager.h"
#include "PxQueryReport.h"
#include "GuCachedFuncs.h"
namespace physx
{
class PxGeometry;
struct PxQueryFilterData;
struct PxFilterData;
class PxQueryFilterCallback;
namespace Sq
{
struct ExtMultiQueryInput;
class ExtPVDCapture
{
public:
ExtPVDCapture() {}
virtual ~ExtPVDCapture() {}
virtual bool transmitSceneQueries() = 0;
virtual void raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) = 0;
virtual void sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) = 0;
virtual void overlap(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData) = 0;
};
// SceneQueries-level adapter. Augments the PrunerManager-level adapter with functions needed to perform queries.
class ExtQueryAdapter : public Adapter
{
public:
ExtQueryAdapter() {}
virtual ~ExtQueryAdapter() {}
// PT: TODO: decouple from PxQueryCache?
virtual Gu::PrunerHandle findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const = 0;
// PT: TODO: return reference? but this version is at least consistent with getActorShape
virtual void getFilterData(const Gu::PrunerPayload& payload, PxFilterData& filterData) const = 0;
virtual void getActorShape(const Gu::PrunerPayload& payload, PxActorShape& actorShape) const = 0;
// PT: new for this customized version: a function to perform per-pruner filtering
virtual bool processPruner(PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const = 0;
};
}
// PT: this is a customized version of physx::Sq::SceneQueries that supports more than 2 hardcoded pruners.
// It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners.
class ExtSceneQueries
{
PX_NOCOPY(ExtSceneQueries)
public:
ExtSceneQueries(Sq::ExtPVDCapture* pvd, PxU64 contextID,
float inflation, const Sq::ExtQueryAdapter& adapter, bool usesTreeOfPruners);
~ExtSceneQueries();
PX_FORCE_INLINE Sq::ExtPrunerManager& getPrunerManagerFast() { return mSQManager; }
PX_FORCE_INLINE const Sq::ExtPrunerManager& getPrunerManagerFast() const { return mSQManager; }
template<typename QueryHit>
bool multiQuery(
const Sq::ExtMultiQueryInput& in,
PxHitCallback<QueryHit>& hits, PxHitFlags hitFlags, const PxQueryCache*,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const;
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;
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;
bool _overlap(
const PxGeometry& geometry, const PxTransform& transform, // GeomObject data
PxOverlapCallback& hitCall,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall,
const PxQueryCache* cache, PxGeometryQueryFlags flags) const;
PX_FORCE_INLINE PxU64 getContextId() const { return mSQManager.getContextId(); }
Sq::ExtPrunerManager mSQManager;
public:
Gu::CachedFuncs mCachedFuncs;
Sq::ExtPVDCapture* mPVD;
};
#if PX_SUPPORT_EXTERN_TEMPLATE
//explicit template instantiation declaration
extern template
bool ExtSceneQueries::multiQuery<PxRaycastHit>(const Sq::ExtMultiQueryInput&, PxHitCallback<PxRaycastHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const;
extern template
bool ExtSceneQueries::multiQuery<PxOverlapHit>(const Sq::ExtMultiQueryInput&, PxHitCallback<PxOverlapHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const;
extern template
bool ExtSceneQueries::multiQuery<PxSweepHit>(const Sq::ExtMultiQueryInput&, PxHitCallback<PxSweepHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const;
#endif
}
#endif
| 6,787 | C | 46.468531 | 212 | 0.741565 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtFixedJoint.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 "ExtFixedJoint.h"
#include "ExtConstraintHelper.h"
#include "omnipvd/ExtOmniPvdSetData.h"
using namespace physx;
using namespace Ext;
FixedJoint::FixedJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) :
FixedJointT(PxJointConcreteType::eFIXED, actor0, localFrame0, actor1, localFrame1, "FixedJointData")
{
// FixedJointData* data = static_cast<FixedJointData*>(mData);
}
static void FixedJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags)
{
if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES)
{
const FixedJointData& data = *reinterpret_cast<const FixedJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform);
viz.visualizeJointFrames(cA2w, cB2w);
}
}
//TAG:solverprepshader
static PxU32 FixedJointSolverPrep(Px1DConstraint* constraints,
PxVec3p& body0WorldOffset,
PxU32 /*maxConstraints*/,
PxConstraintInvMassScale& invMassScale,
const void* constantBlock,
const PxTransform& bA2w,
const PxTransform& bB2w,
bool /*useExtendedLimits*/,
PxVec3p& cA2wOut, PxVec3p& cB2wOut)
{
const FixedJointData& data = *reinterpret_cast<const FixedJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w);
joint::applyNeighborhoodOperator(cA2w, cB2w);
PxVec3 ra, rb;
ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, 7, ra, rb);
cA2wOut = ra + bA2w.p;
cB2wOut = rb + bB2w.p;
return ch.getCount();
}
///////////////////////////////////////////////////////////////////////////////
static PxConstraintShaderTable gFixedJointShaders = { FixedJointSolverPrep, FixedJointVisualize, PxConstraintFlag::Enum(0) };
PxConstraintSolverPrep FixedJoint::getPrep() const { return gFixedJointShaders.solverPrep; }
PxFixedJoint* physx::PxFixedJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1)
{
PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxFixedJointCreate: local frame 0 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxFixedJointCreate: local frame 1 is not a valid transform");
PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxFixedJointCreate: at least one actor must be dynamic");
PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxFixedJointCreate: actors must be different");
return createJointT<FixedJoint, FixedJointData>(physics, actor0, localFrame0, actor1, localFrame1, gFixedJointShaders);
}
// PX_SERIALIZATION
void FixedJoint::resolveReferences(PxDeserializationContext& context)
{
mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gFixedJointShaders);
}
//~PX_SERIALIZATION
#if PX_SUPPORT_OMNI_PVD
template<>
void physx::Ext::omniPvdInitJoint<FixedJoint>(FixedJoint& joint)
{
PxFixedJoint& j = static_cast<PxFixedJoint&>(joint);
OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxFixedJoint, j);
omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eFIXED);
}
#endif
| 5,026 | C++ | 42.713043 | 170 | 0.764823 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultStreams.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxAssert.h"
#include "foundation/PxAllocatorCallback.h"
#include "foundation/PxMemory.h"
#include "foundation/PxBitUtils.h"
#include "extensions/PxDefaultStreams.h"
#include "SnFile.h"
#include "foundation/PxUtilities.h"
#include <errno.h>
using namespace physx;
PxDefaultMemoryOutputStream::PxDefaultMemoryOutputStream(PxAllocatorCallback &allocator)
: mAllocator (allocator)
, mData (NULL)
, mSize (0)
, mCapacity (0)
{
}
PxDefaultMemoryOutputStream::~PxDefaultMemoryOutputStream()
{
if(mData)
mAllocator.deallocate(mData);
}
PxU32 PxDefaultMemoryOutputStream::write(const void* src, PxU32 size)
{
PxU32 expectedSize = mSize + size;
if(expectedSize > mCapacity)
{
mCapacity = PxMax(PxNextPowerOfTwo(expectedSize), 4096u);
PxU8* newData = reinterpret_cast<PxU8*>(mAllocator.allocate(mCapacity,"PxDefaultMemoryOutputStream",__FILE__,__LINE__));
PX_ASSERT(newData!=NULL);
PxMemCopy(newData, mData, mSize);
if(mData)
mAllocator.deallocate(mData);
mData = newData;
}
PxMemCopy(mData+mSize, src, size);
mSize += size;
return size;
}
///////////////////////////////////////////////////////////////////////////////
PxDefaultMemoryInputData::PxDefaultMemoryInputData(PxU8* data, PxU32 length) :
mSize (length),
mData (data),
mPos (0)
{
}
PxU32 PxDefaultMemoryInputData::read(void* dest, PxU32 count)
{
PxU32 length = PxMin<PxU32>(count, mSize-mPos);
PxMemCopy(dest, mData+mPos, length);
mPos += length;
return length;
}
PxU32 PxDefaultMemoryInputData::getLength() const
{
return mSize;
}
void PxDefaultMemoryInputData::seek(PxU32 offset)
{
mPos = PxMin<PxU32>(mSize, offset);
}
PxU32 PxDefaultMemoryInputData::tell() const
{
return mPos;
}
PxDefaultFileOutputStream::PxDefaultFileOutputStream(const char* filename)
{
mFile = NULL;
sn::fopen_s(&mFile, filename, "wb");
// PT: when this fails, check that:
// - the path is correct
// - the file does not already exist. If it does, check that it is not write protected.
if(NULL == mFile)
{
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL,
"Unable to open file %s, errno 0x%x\n",filename,errno);
}
PX_ASSERT(mFile);
}
PxDefaultFileOutputStream::~PxDefaultFileOutputStream()
{
if(mFile)
fclose(mFile);
mFile = NULL;
}
PxU32 PxDefaultFileOutputStream::write(const void* src, PxU32 count)
{
return mFile ? PxU32(fwrite(src, 1, count, mFile)) : 0;
}
bool PxDefaultFileOutputStream::isValid()
{
return mFile != NULL;
}
///////////////////////////////////////////////////////////////////////////////
PxDefaultFileInputData::PxDefaultFileInputData(const char* filename)
{
mFile = NULL;
sn::fopen_s(&mFile, filename, "rb");
if(mFile)
{
fseek(mFile, 0, SEEK_END);
mLength = PxU32(ftell(mFile));
fseek(mFile, 0, SEEK_SET);
}
else
{
mLength = 0;
}
}
PxDefaultFileInputData::~PxDefaultFileInputData()
{
if(mFile)
fclose(mFile);
}
PxU32 PxDefaultFileInputData::read(void* dest, PxU32 count)
{
PX_ASSERT(mFile);
const size_t size = fread(dest, 1, count, mFile);
// there should be no assert here since by spec of PxInputStream we can read fewer bytes than expected
return PxU32(size);
}
PxU32 PxDefaultFileInputData::getLength() const
{
return mLength;
}
void PxDefaultFileInputData::seek(PxU32 pos)
{
fseek(mFile, long(pos), SEEK_SET);
}
PxU32 PxDefaultFileInputData::tell() const
{
return PxU32(ftell(mFile));
}
bool PxDefaultFileInputData::isValid() const
{
return mFile != NULL;
}
| 5,195 | C++ | 25.783505 | 122 | 0.719346 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSceneQuerySystem.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 "extensions/PxSceneQuerySystemExt.h"
#include "extensions/PxShapeExt.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxUserAllocated.h"
#include "geometry/PxBVH.h"
#include "GuActorShapeMap.h"
#include "SqQuery.h"
#include "SqFactory.h"
#include "PxRigidActor.h"
#include "PxPruningStructure.h"
#include "PxSceneDesc.h" // PT: for PxSceneLimits TODO: remove
// PT: this file re-implements a scene-queries system for PxScene inside PxExtensions. All SQ-related calls from the PxScene API
// will be re-routed to this class. This version re-uses the same internal code as PhysX (most notably from SqQuery.h) so there is
// little differences between the internal PhysX version and this one except minor implementation details like what we store in the
// PrunerPayload. The whole API is available, it uses the same number of "pruners" for the queries, etc. This is a good working
// starting point for users who want to start tinkering with the system without starting from scratch.
using namespace physx;
using namespace Sq;
using namespace Gu;
#define EXT_PRUNER_EPSILON 0.005f
// PT: in this external implementation we'll use Px pointers instead of Np pointers in the payload.
static PX_FORCE_INLINE void setPayload(PrunerPayload& pp, const PxShape* shape, const PxRigidActor* actor)
{
pp.data[0] = size_t(shape);
pp.data[1] = size_t(actor);
}
static PX_FORCE_INLINE PxShape* getShapeFromPayload(const PrunerPayload& payload)
{
return reinterpret_cast<PxShape*>(payload.data[0]);
}
static PX_FORCE_INLINE PxRigidActor* getActorFromPayload(const PrunerPayload& payload)
{
return reinterpret_cast<PxRigidActor*>(payload.data[1]);
}
static PX_FORCE_INLINE bool isDynamicActor(const PxRigidActor& actor)
{
const PxType actorType = actor.getConcreteType();
return actorType != PxConcreteType::eRIGID_STATIC;
}
///////////////////////////////////////////////////////////////////////////////
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 ExtSqAdapter : public QueryAdapter
{
public:
ExtSqAdapter() {}
virtual ~ExtSqAdapter() {}
// 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;
};
}
const PxGeometry& ExtSqAdapter::getGeometry(const PrunerPayload& payload) const
{
PxShape* shape = getShapeFromPayload(payload);
return shape->getGeometry();
}
PrunerHandle ExtSqAdapter::findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const
{
const PxU32 actorIndex = cache.actor->getInternalActorIndex();
PX_ASSERT(actorIndex!=0xffffffff);
const ActorShapeData actorShapeData = mDatabase.find(actorIndex, cache.actor, cache.shape);
const PrunerData prunerData = getPrunerData(actorShapeData);
compoundId = getCompoundID(actorShapeData);
prunerIndex = getPrunerIndex(prunerData);
return getPrunerHandle(prunerData);
}
void ExtSqAdapter::getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const
{
PxShape* shape = getShapeFromPayload(payload);
filterData = shape->getQueryFilterData();
}
void ExtSqAdapter::getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const
{
actorShape.actor = getActorFromPayload(payload);
actorShape.shape = getShapeFromPayload(payload);
}
///////////////////////////////////////////////////////////////////////////////
namespace
{
class ExternalPxSQ : public PxSceneQuerySystem, public PxUserAllocated
{
public:
ExternalPxSQ(PVDCapture* pvd, PxU64 contextID, Pruner* staticPruner, Pruner* dynamicPruner,
PxU32 dynamicTreeRebuildRateHint, PxSceneQueryUpdateMode::Enum mode, const PxSceneLimits& limits) :
mQueries (pvd, contextID, staticPruner, dynamicPruner, dynamicTreeRebuildRateHint, EXT_PRUNER_EPSILON, limits, mExtAdapter),
mUpdateMode (mode),
mRefCount (1)
{}
virtual ~ExternalPxSQ() {}
virtual void release();
virtual void acquireReference();
virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) { SQ().preallocate(prunerIndex, nbShapes); }
virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds,
const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure);
virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape);
virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform);
virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& pxbvh, const PxTransform* transforms);
virtual void removeSQCompound(PxSQCompoundHandle compoundHandle);
virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& 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);
virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle);
virtual void finalizeUpdates();
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 merge(const PxPruningStructure& pxps);
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;
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;
virtual bool overlap(const PxGeometry& geometry, const PxTransform& transform,
PxOverlapCallback& hitCall,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall,
const PxQueryCache* cache, PxGeometryQueryFlags flags) const;
virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const;
virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds,
const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices);
PX_FORCE_INLINE PrunerManager& SQ() { return mQueries.mSQManager; }
PX_FORCE_INLINE const PrunerManager& SQ() const { return mQueries.mSQManager; }
ExtSqAdapter mExtAdapter;
SceneQueries mQueries;
PxSceneQueryUpdateMode::Enum mUpdateMode;
PxU32 mRefCount;
};
}
///////////////////////////////////////////////////////////////////////////////
void addExternalSQ(PxSceneQuerySystem* added);
void removeExternalSQ(PxSceneQuerySystem* removed);
void ExternalPxSQ::release()
{
mRefCount--;
if(!mRefCount)
{
removeExternalSQ(this);
PX_DELETE_THIS;
}
}
void ExternalPxSQ::acquireReference()
{
mRefCount++;
}
void ExternalPxSQ::addSQShape(const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure)
{
PrunerPayload payload;
setPayload(payload, &shape, &actor);
const PrunerCompoundId cid = compoundHandle ? PrunerCompoundId(*compoundHandle) : INVALID_COMPOUND_ID;
const PrunerData prunerData = SQ().addPrunerShape(payload, isDynamicActor(actor), cid, bounds, transform, hasPruningStructure);
const PxU32 actorIndex = actor.getInternalActorIndex();
PX_ASSERT(actorIndex!=0xffffffff);
mExtAdapter.mDatabase.add(actorIndex, &actor, &shape, createActorShapeData(prunerData, cid));
}
namespace
{
struct DatabaseCleaner : PrunerPayloadRemovalCallback
{
DatabaseCleaner(ExtSqAdapter& adapter) : mAdapter(adapter){}
virtual void invoke(PxU32 nbRemoved, const PrunerPayload* removed)
{
PxU32 actorIndex = 0xffffffff;
const PxRigidActor* cachedActor = NULL;
while(nbRemoved--)
{
const PrunerPayload& payload = *removed++;
const PxRigidActor* actor = getActorFromPayload(payload);
if(actor!=cachedActor)
{
actorIndex = actor->getInternalActorIndex();
cachedActor = actor;
}
PX_ASSERT(actorIndex!=0xffffffff);
bool status = mAdapter.mDatabase.remove(actorIndex, actor, getShapeFromPayload(payload), NULL);
PX_ASSERT(status);
PX_UNUSED(status);
}
}
ExtSqAdapter& mAdapter;
PX_NOCOPY(DatabaseCleaner)
};
}
void ExternalPxSQ::removeSQShape(const PxRigidActor& actor, const PxShape& shape)
{
const PxU32 actorIndex = actor.getInternalActorIndex();
PX_ASSERT(actorIndex!=0xffffffff);
ActorShapeData actorShapeData;
mExtAdapter.mDatabase.remove(actorIndex, &actor, &shape, &actorShapeData);
const PrunerData data = getPrunerData(actorShapeData);
const PrunerCompoundId compoundId = getCompoundID(actorShapeData);
SQ().removePrunerShape(compoundId, data, NULL);
}
void ExternalPxSQ::updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform)
{
const PxU32 actorIndex = actor.getInternalActorIndex();
PX_ASSERT(actorIndex!=0xffffffff);
const ActorShapeData actorShapeData = mExtAdapter.mDatabase.find(actorIndex, &actor, &shape);
const PrunerData shapeHandle = getPrunerData(actorShapeData);
const PrunerCompoundId cid = getCompoundID(actorShapeData);
SQ().markForUpdate(cid, shapeHandle, transform);
}
PxSQCompoundHandle ExternalPxSQ::addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms)
{
const PxU32 numSqShapes = bvh.getNbBounds();
PX_ALLOCA(payloads, PrunerPayload, numSqShapes);
for(PxU32 i=0; i<numSqShapes; i++)
setPayload(payloads[i], shapes[i], &actor);
const PxU32 actorIndex = actor.getInternalActorIndex();
PX_ASSERT(actorIndex!=0xffffffff);
PX_ALLOCA(shapeHandles, PrunerData, numSqShapes);
SQ().addCompoundShape(bvh, actorIndex, actor.getGlobalPose(), shapeHandles, payloads, transforms, isDynamicActor(actor));
for(PxU32 i=0; i<numSqShapes; i++)
{
// PT: TODO: actorIndex is now redundant!
mExtAdapter.mDatabase.add(actorIndex, &actor, shapes[i], createActorShapeData(shapeHandles[i], actorIndex));
}
return PxSQCompoundHandle(actorIndex);
}
void ExternalPxSQ::removeSQCompound(PxSQCompoundHandle compoundHandle)
{
DatabaseCleaner cleaner(mExtAdapter);
SQ().removeCompoundActor(PrunerCompoundId(compoundHandle), &cleaner);
}
void ExternalPxSQ::updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform)
{
SQ().updateCompoundActor(PrunerCompoundId(compoundHandle), compoundTransform);
}
PxSQBuildStepHandle ExternalPxSQ::prepareSceneQueryBuildStep(PxU32 prunerIndex)
{
return SQ().prepareSceneQueriesUpdate(PruningIndex::Enum(prunerIndex));
}
void ExternalPxSQ::sceneQueryBuildStep(PxSQBuildStepHandle handle)
{
SQ().sceneQueryBuildStep(handle);
}
void ExternalPxSQ::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;
}
}
void ExternalPxSQ::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());
}
bool ExternalPxSQ::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);
}
bool ExternalPxSQ::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);
}
bool ExternalPxSQ::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);
}
PxSQPrunerHandle ExternalPxSQ::getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const
{
const PxU32 actorIndex = actor.getInternalActorIndex();
PX_ASSERT(actorIndex!=0xffffffff);
const ActorShapeData actorShapeData = mExtAdapter.mDatabase.find(actorIndex, &actor, &shape);
const PrunerData prunerData = getPrunerData(actorShapeData);
prunerIndex = getPrunerIndex(prunerData);
return PxSQPrunerHandle(getPrunerHandle(prunerData));
}
void ExternalPxSQ::sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds,
const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices)
{
PX_ASSERT(prunerIndex==PruningIndex::eDYNAMIC);
if(prunerIndex==PruningIndex::eDYNAMIC)
SQ().sync(handles, indices, bounds, transforms, count, ignoredIndices);
}
///////////////////////////////////////////////////////////////////////////////
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)
{
// if(0)
// 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; }
case PxPruningStructureType::eLAST: break;
}
return pruner;
}
PxSceneQuerySystem* physx::PxCreateExternalSceneQuerySystem(const PxSceneQueryDesc& desc, PxU64 contextID)
{
PVDCapture* pvd = NULL;
Pruner* staticPruner = create(desc.staticStructure, contextID, desc.dynamicTreeSecondaryPruner, desc.staticBVHBuildStrategy, desc.staticNbObjectsPerNode);
Pruner* dynamicPruner = create(desc.dynamicStructure, contextID, desc.dynamicTreeSecondaryPruner, desc.dynamicBVHBuildStrategy, desc.dynamicNbObjectsPerNode);
ExternalPxSQ* pxsq = PX_NEW(ExternalPxSQ)(pvd, contextID, staticPruner, dynamicPruner, desc.dynamicTreeRebuildRateHint, desc.sceneQueryUpdateMode, PxSceneLimits());
addExternalSQ(pxsq);
return pxsq;
}
| 20,079 | C++ | 41.723404 | 201 | 0.744459 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_JOINT_H
#define EXT_JOINT_H
#include "PxPhysics.h"
#include "extensions/PxConstraintExt.h"
#include "PxRigidStatic.h"
#include "PxRigidDynamic.h"
#include "PxArticulationLink.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxScene.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxMathUtils.h"
#include "CmUtils.h"
#include "ExtJointData.h"
#if PX_SUPPORT_PVD
#include "pvd/PxPvdSceneClient.h"
#include "ExtPvd.h"
#include "PxPvdClient.h"
#endif
#include "omnipvd/ExtOmniPvdSetData.h"
namespace physx
{
// PX_SERIALIZATION
class PxDeserializationContext;
PxConstraint* resolveConstraintPtr(PxDeserializationContext& v, PxConstraint* old, PxConstraintConnector* connector, PxConstraintShaderTable& shaders);
// ~PX_SERIALIZATION
namespace Ext
{
PX_FORCE_INLINE float computeSwingAngle(float swingYZ, float swingW)
{
return 4.0f * PxAtan2(swingYZ, 1.0f + swingW); // tan (t/2) = sin(t)/(1+cos t), so this is the quarter angle
}
template<class JointType, class DataType>
PX_FORCE_INLINE JointType* createJointT(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1, const PxConstraintShaderTable& shaders)
{
JointType* j;
PX_NEW_SERIALIZED(j, JointType)(physics.getTolerancesScale(), actor0, localFrame0, actor1, localFrame1);
if(!physics.createConstraint(actor0, actor1, *j, shaders, sizeof(DataType)))
PX_DELETE(j);
#if PX_SUPPORT_OMNI_PVD
if (j)
{
omniPvdInitJoint(*j);
}
#endif
return j;
}
// PX_SERIALIZATION
template<class JointType>
PX_FORCE_INLINE JointType* createJointObject(PxU8*& address, PxDeserializationContext& context)
{
JointType* obj = PX_PLACEMENT_NEW(address, JointType(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(JointType);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
//~PX_SERIALIZATION
template <class Base, class DataClass, class ValueStruct>
class JointT : public Base, public PxConstraintConnector, public PxUserAllocated
{
public:
// PX_SERIALIZATION
JointT(PxBaseFlags baseFlags) : Base(baseFlags) {}
void exportExtraData(PxSerializationContext& stream)
{
if(mData)
{
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(mData, sizeof(DataClass));
}
stream.writeName(mName);
}
void importExtraData(PxDeserializationContext& context)
{
if(mData)
mData = context.readExtraData<DataClass, PX_SERIAL_ALIGN>();
context.readName(mName);
}
virtual void preExportDataReset(){}
virtual void requiresObjects(PxProcessPxBaseCallback& c)
{
c.process(*mPxConstraint);
{
PxRigidActor* a0 = NULL;
PxRigidActor* a1 = NULL;
mPxConstraint->getActors(a0,a1);
if (a0)
{
c.process(*a0);
}
if (a1)
{
c.process(*a1);
}
}
}
//~PX_SERIALIZATION
#if PX_SUPPORT_PVD
// PxConstraintConnector
virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream& pvdConnection, const PxConstraint* c, PxPvdUpdateType::Enum updateType) const PX_OVERRIDE
{
if(updateType == PxPvdUpdateType::UPDATE_SIM_PROPERTIES)
{
Ext::Pvd::simUpdate<Base>(pvdConnection, *this);
return true;
}
else if(updateType == PxPvdUpdateType::UPDATE_ALL_PROPERTIES)
{
Ext::Pvd::updatePvdProperties<Base, ValueStruct>(pvdConnection, *this);
return true;
}
else if(updateType == PxPvdUpdateType::CREATE_INSTANCE)
{
Ext::Pvd::createPvdInstance<Base>(pvdConnection, *c, *this);
return true;
}
else if(updateType == PxPvdUpdateType::RELEASE_INSTANCE)
{
Ext::Pvd::releasePvdInstance(pvdConnection, *c, *this);
return true;
}
return false;
}
#else
virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream&, const PxConstraint*, PxPvdUpdateType::Enum) const PX_OVERRIDE
{
return false;
}
#endif
// PxConstraintConnector
virtual void updateOmniPvdProperties() const PX_OVERRIDE
{
}
// PxJoint
virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) PX_OVERRIDE
{
//TODO SDK-DEV
//You can get the debugger stream from the NpScene
//Ext::Pvd::setActors( stream, this, mPxConstraint, actor0, actor1 );
PX_CHECK_AND_RETURN(actor0 != actor1, "PxJoint::setActors: actors must be different");
PX_CHECK_AND_RETURN((actor0 && !actor0->is<PxRigidStatic>()) || (actor1 && !actor1->is<PxRigidStatic>()), "PxJoint::setActors: at least one actor must be non-static");
#if PX_SUPPORT_PVD
PxScene* scene = getScene();
if(scene)
{
//if pvd not connect data stream is NULL
physx::pvdsdk::PvdDataStream* conn = scene->getScenePvdClient()->getClientInternal()->getDataStream();
if( conn != NULL )
Ext::Pvd::setActors(
*conn,
*this,
*mPxConstraint,
actor0,
actor1
);
}
#endif
mPxConstraint->setActors(actor0, actor1);
mData->c2b[0] = getCom(actor0).transformInv(mLocalPose[0]);
mData->c2b[1] = getCom(actor1).transformInv(mLocalPose[1]);
mPxConstraint->markDirty();
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0, static_cast<PxJoint&>(*this), actor0)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1, static_cast<PxJoint&>(*this), actor1)
OMNI_PVD_WRITE_SCOPE_END
}
// PxJoint
virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const PX_OVERRIDE
{
if(mPxConstraint)
mPxConstraint->getActors(actor0,actor1);
else
{
actor0 = NULL;
actor1 = NULL;
}
}
// this is the local pose relative to the actor, and we store internally the local
// pose relative to the body
// PxJoint
virtual void setLocalPose(PxJointActorIndex::Enum actor, const PxTransform& pose) PX_OVERRIDE
{
PX_CHECK_AND_RETURN(pose.isSane(), "PxJoint::setLocalPose: transform is invalid");
const PxTransform p = pose.getNormalized();
mLocalPose[actor] = p;
mData->c2b[actor] = getCom(actor).transformInv(p);
mPxConstraint->markDirty();
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0LocalPose, static_cast<PxJoint&>(*this), mLocalPose[0])
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1LocalPose, static_cast<PxJoint&>(*this), mLocalPose[1])
OMNI_PVD_WRITE_SCOPE_END
}
// PxJoint
virtual PxTransform getLocalPose(PxJointActorIndex::Enum actor) const PX_OVERRIDE
{
return mLocalPose[actor];
}
static PxTransform getGlobalPose(const PxRigidActor* actor)
{
if(!actor)
return PxTransform(PxIdentity);
return actor->getGlobalPose();
}
static void getActorVelocity(const PxRigidActor* actor, PxVec3& linear, PxVec3& angular)
{
if(!actor || actor->is<PxRigidStatic>())
{
linear = angular = PxVec3(0.0f);
return;
}
linear = static_cast<const PxRigidBody*>(actor)->getLinearVelocity();
angular = static_cast<const PxRigidBody*>(actor)->getAngularVelocity();
}
// PxJoint
virtual PxTransform getRelativeTransform() const PX_OVERRIDE
{
PxRigidActor* actor0, * actor1;
mPxConstraint->getActors(actor0, actor1);
const PxTransform t0 = getGlobalPose(actor0) * mLocalPose[0];
const PxTransform t1 = getGlobalPose(actor1) * mLocalPose[1];
return t0.transformInv(t1);
}
// PxJoint
virtual PxVec3 getRelativeLinearVelocity() const PX_OVERRIDE
{
PxRigidActor* actor0, * actor1;
PxVec3 l0, a0, l1, a1;
mPxConstraint->getActors(actor0, actor1);
PxTransform t0 = getCom(actor0), t1 = getCom(actor1);
getActorVelocity(actor0, l0, a0);
getActorVelocity(actor1, l1, a1);
PxVec3 p0 = t0.q.rotate(mLocalPose[0].p),
p1 = t1.q.rotate(mLocalPose[1].p);
return t0.transformInv(l1 - a1.cross(p1) - l0 + a0.cross(p0));
}
// PxJoint
virtual PxVec3 getRelativeAngularVelocity() const PX_OVERRIDE
{
PxRigidActor* actor0, * actor1;
PxVec3 l0, a0, l1, a1;
mPxConstraint->getActors(actor0, actor1);
PxTransform t0 = getCom(actor0);
getActorVelocity(actor0, l0, a0);
getActorVelocity(actor1, l1, a1);
return t0.transformInv(a1 - a0);
}
// PxJoint
virtual void setBreakForce(PxReal force, PxReal torque) PX_OVERRIDE
{
PX_CHECK_AND_RETURN(PxIsFinite(force) && PxIsFinite(torque), "PxJoint::setBreakForce: invalid float");
mPxConstraint->setBreakForce(force,torque);
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakForce, static_cast<PxJoint&>(*this), force)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakTorque, static_cast<PxJoint&>(*this), torque)
OMNI_PVD_WRITE_SCOPE_END
}
// PxJoint
virtual void getBreakForce(PxReal& force, PxReal& torque) const PX_OVERRIDE
{
mPxConstraint->getBreakForce(force,torque);
}
// PxJoint
virtual void setConstraintFlags(PxConstraintFlags flags) PX_OVERRIDE
{
mPxConstraint->setFlags(flags);
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, constraintFlags, static_cast<PxJoint&>(*this), flags)
}
// PxJoint
virtual void setConstraintFlag(PxConstraintFlag::Enum flag, bool value) PX_OVERRIDE
{
mPxConstraint->setFlag(flag, value);
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, constraintFlags, static_cast<PxJoint&>(*this), getConstraintFlags())
}
// PxJoint
virtual PxConstraintFlags getConstraintFlags() const PX_OVERRIDE
{
return mPxConstraint->getFlags();
}
// PxJoint
virtual void setInvMassScale0(PxReal invMassScale) PX_OVERRIDE
{
PX_CHECK_AND_RETURN(PxIsFinite(invMassScale) && invMassScale>=0, "PxJoint::setInvMassScale0: scale must be non-negative");
mData->invMassScale.linear0 = invMassScale;
mPxConstraint->markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale0, static_cast<PxJoint&>(*this), invMassScale)
}
// PxJoint
virtual PxReal getInvMassScale0() const PX_OVERRIDE
{
return mData->invMassScale.linear0;
}
// PxJoint
virtual void setInvInertiaScale0(PxReal invInertiaScale) PX_OVERRIDE
{
PX_CHECK_AND_RETURN(PxIsFinite(invInertiaScale) && invInertiaScale>=0, "PxJoint::setInvInertiaScale0: scale must be non-negative");
mData->invMassScale.angular0 = invInertiaScale;
mPxConstraint->markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale0, static_cast<PxJoint&>(*this), invInertiaScale)
}
// PxJoint
virtual PxReal getInvInertiaScale0() const PX_OVERRIDE
{
return mData->invMassScale.angular0;
}
// PxJoint
virtual void setInvMassScale1(PxReal invMassScale) PX_OVERRIDE
{
PX_CHECK_AND_RETURN(PxIsFinite(invMassScale) && invMassScale>=0, "PxJoint::setInvMassScale1: scale must be non-negative");
mData->invMassScale.linear1 = invMassScale;
mPxConstraint->markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale1, static_cast<PxJoint&>(*this), invMassScale)
}
// PxJoint
virtual PxReal getInvMassScale1() const PX_OVERRIDE
{
return mData->invMassScale.linear1;
}
// PxJoint
virtual void setInvInertiaScale1(PxReal invInertiaScale) PX_OVERRIDE
{
PX_CHECK_AND_RETURN(PxIsFinite(invInertiaScale) && invInertiaScale>=0, "PxJoint::setInvInertiaScale: scale must be non-negative");
mData->invMassScale.angular1 = invInertiaScale;
mPxConstraint->markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale1, static_cast<PxJoint&>(*this), invInertiaScale)
}
// PxJoint
virtual PxReal getInvInertiaScale1() const PX_OVERRIDE
{
return mData->invMassScale.angular1;
}
// PxJoint
virtual PxConstraint* getConstraint() const PX_OVERRIDE
{
return mPxConstraint;
}
// PxJoint
virtual void setName(const char* name) PX_OVERRIDE
{
mName = name;
#if PX_SUPPORT_OMNI_PVD
const char* n = name ? name : "";
PxU32 nLen = PxU32(strlen(n)) + 1;
OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxJoint, name, static_cast<PxJoint&>(*this), n, nLen)
#endif
}
// PxJoint
virtual const char* getName() const PX_OVERRIDE
{
return mName;
}
// PxJoint
virtual void release() PX_OVERRIDE
{
mPxConstraint->release();
}
// PxJoint
virtual PxScene* getScene() const PX_OVERRIDE
{
return mPxConstraint ? mPxConstraint->getScene() : NULL;
}
// PxConstraintConnector
virtual void onComShift(PxU32 actor) PX_OVERRIDE
{
mData->c2b[actor] = getCom(actor).transformInv(mLocalPose[actor]);
markDirty();
}
// PxConstraintConnector
virtual void onOriginShift(const PxVec3& shift) PX_OVERRIDE
{
PxRigidActor* a[2];
mPxConstraint->getActors(a[0], a[1]);
if (!a[0])
{
mLocalPose[0].p -= shift;
mData->c2b[0].p -= shift;
markDirty();
}
else if (!a[1])
{
mLocalPose[1].p -= shift;
mData->c2b[1].p -= shift;
markDirty();
}
}
// PxConstraintConnector
virtual void* prepareData() PX_OVERRIDE
{
return mData;
}
// PxConstraintConnector
virtual void* getExternalReference(PxU32& typeID) PX_OVERRIDE
{
typeID = PxConstraintExtIDs::eJOINT;
return static_cast<PxJoint*>( this );
}
// PxConstraintConnector
virtual PxBase* getSerializable() PX_OVERRIDE
{
return this;
}
// PxConstraintConnector
virtual void onConstraintRelease() PX_OVERRIDE
{
PX_FREE(mData);
PX_DELETE_THIS;
}
// PxConstraintConnector
virtual const void* getConstantBlock() const PX_OVERRIDE
{
return mData;
}
virtual void connectToConstraint(PxConstraint* c) PX_OVERRIDE
{
mPxConstraint = c;
}
private:
PxTransform getCom(PxU32 index) const
{
PxRigidActor* a[2];
mPxConstraint->getActors(a[0],a[1]);
return getCom(a[index]);
}
PxTransform getCom(PxRigidActor* actor) const
{
if (!actor)
return PxTransform(PxIdentity);
else if (actor->getType() == PxActorType::eRIGID_DYNAMIC || actor->getType() == PxActorType::eARTICULATION_LINK)
return static_cast<PxRigidBody*>(actor)->getCMassLocalPose();
else
{
PX_ASSERT(actor->getType() == PxActorType::eRIGID_STATIC);
return static_cast<PxRigidStatic*>(actor)->getGlobalPose().getInverse();
}
}
protected:
JointT(PxType concreteType, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1, const char* name) :
Base (concreteType, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mName (NULL),
mPxConstraint (NULL)
{
PX_UNUSED(name);
Base::userData = NULL;
const PxU32 size = sizeof(DataClass);
JointData* data = reinterpret_cast<JointData*>(PX_ALLOC(size, name));
PxMarkSerializedMemory(data, size);
mLocalPose[0] = localFrame0.getNormalized();
mLocalPose[1] = localFrame1.getNormalized();
data->c2b[0] = getCom(actor0).transformInv(mLocalPose[0]);
data->c2b[1] = getCom(actor1).transformInv(mLocalPose[1]);
data->invMassScale.linear0 = 1.0f;
data->invMassScale.angular0 = 1.0f;
data->invMassScale.linear1 = 1.0f;
data->invMassScale.angular1 = 1.0f;
mData = data;
}
virtual ~JointT()
{
if(Base::getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
PX_FREE(mData);
OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxJoint, static_cast<Base&>(*this))
}
PX_FORCE_INLINE DataClass& data() const
{
return *static_cast<DataClass*>(mData);
}
PX_FORCE_INLINE void markDirty()
{
mPxConstraint->markDirty();
}
void wakeUpActors()
{
PxRigidActor* a[2];
mPxConstraint->getActors(a[0], a[1]);
for(PxU32 i = 0; i < 2; i++)
{
if(a[i] && a[i]->getScene())
{
if(a[i]->getType() == PxActorType::eRIGID_DYNAMIC)
{
PxRigidDynamic* rd = static_cast<PxRigidDynamic*>(a[i]);
if(!(rd->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC))
{
const PxScene* scene = rd->getScene();
const PxReal wakeCounterResetValue = scene->getWakeCounterResetValue();
const PxReal wakeCounter = rd->getWakeCounter();
if(wakeCounter < wakeCounterResetValue)
{
rd->wakeUp();
}
}
}
else if(a[i]->getType() == PxActorType::eARTICULATION_LINK)
{
PxArticulationLink* link = reinterpret_cast<PxArticulationLink*>(a[i]);
PxArticulationReducedCoordinate& articulation = link->getArticulation();
const PxReal wakeCounter = articulation.getWakeCounter();
const PxScene* scene = link->getScene();
const PxReal wakeCounterResetValue = scene->getWakeCounterResetValue();
if(wakeCounter < wakeCounterResetValue)
{
articulation.wakeUp();
}
}
}
}
}
PX_FORCE_INLINE PxQuat getTwistOrSwing(bool needTwist) const
{
const PxQuat q = getRelativeTransform().q;
// PT: TODO: we don't need to compute both quats here
PxQuat swing, twist;
PxSeparateSwingTwist(q, swing, twist);
return needTwist ? twist : swing;
}
PxReal getTwistAngle_Internal() const
{
const PxQuat twist = getTwistOrSwing(true);
// PT: the angle-axis formulation creates the quat like this:
//
// const float a = angleRadians * 0.5f;
// const float s = PxSin(a);
// w = PxCos(a);
// x = unitAxis.x * s;
// y = unitAxis.y * s;
// z = unitAxis.z * s;
//
// With the twist axis = (1;0;0) this gives:
//
// w = PxCos(angleRadians * 0.5f);
// x = PxSin(angleRadians * 0.5f);
// y = 0.0f;
// z = 0.0f;
//
// Thus the quat's "getAngle" function returns:
//
// angle = PxAcos(w) * 2.0f;
//
// PxAcos will return an angle between 0 and PI in radians, so "getAngle" will return an angle between 0 and PI*2.
PxReal angle = twist.getAngle();
if(twist.x<0.0f)
angle = -angle;
return angle;
}
PxReal getSwingYAngle_Internal() const
{
PxQuat swing = getTwistOrSwing(false);
if(swing.w < 0.0f) // choose the shortest rotation
swing = -swing;
const PxReal angle = computeSwingAngle(swing.y, swing.w);
PX_ASSERT(angle>-PxPi && angle<=PxPi); // since |y| < w+1, the atan magnitude is < PI/4
return angle;
}
PxReal getSwingZAngle_Internal() const
{
PxQuat swing = getTwistOrSwing(false);
if(swing.w < 0.0f) // choose the shortest rotation
swing = -swing;
const PxReal angle = computeSwingAngle(swing.z, swing.w);
PX_ASSERT(angle>-PxPi && angle <= PxPi); // since |y| < w+1, the atan magnitude is < PI/4
return angle;
}
const char* mName;
PxTransform mLocalPose[2];
PxConstraint* mPxConstraint;
JointData* mData;
};
#if PX_SUPPORT_OMNI_PVD
void omniPvdSetBaseJointParams(PxJoint& joint, PxJointConcreteType::Enum cType);
template<typename JointType> void omniPvdInitJoint(JointType& joint);
#endif
} // namespace Ext
}
#endif
| 20,603 | C | 28.267045 | 208 | 0.697229 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtGearJoint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_GEAR_JOINT_H
#define EXT_GEAR_JOINT_H
#include "extensions/PxGearJoint.h"
#include "ExtJoint.h"
#include "CmUtils.h"
namespace physx
{
struct PxGearJointGeneratedValues;
namespace Ext
{
struct GearJointData : public JointData
{
const PxBase* hingeJoint0; //either PxJoint or PxArticulationJointReducedCoordinate
const PxBase* hingeJoint1; //either PxJoint or PxArticulationJointReducedCoordinate
float gearRatio;
float error;
};
typedef JointT<PxGearJoint, GearJointData, PxGearJointGeneratedValues> GearJointT;
class GearJoint : public GearJointT
{
public:
// PX_SERIALIZATION
GearJoint(PxBaseFlags baseFlags) : GearJointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static GearJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<GearJoint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
GearJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxGearJoint
virtual bool setHinges(const PxBase* hinge0, const PxBase* hinge1) PX_OVERRIDE;
virtual void getHinges(const PxBase*& hinge0, const PxBase*& hinge1) const PX_OVERRIDE;
virtual void setGearRatio(float ratio) PX_OVERRIDE;
virtual float getGearRatio() const PX_OVERRIDE;
//~PxGearJoint
// PxConstraintConnector
virtual void* prepareData() PX_OVERRIDE
{
updateError();
return mData;
}
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
//~PxConstraintConnector
private:
float mVirtualAngle0;
float mVirtualAngle1;
float mPersistentAngle0;
float mPersistentAngle1;
bool mInitDone;
void updateError();
void resetError();
};
} // namespace Ext
}
#endif
| 3,654 | C | 39.164835 | 164 | 0.74439 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtD6Joint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_D6_JOINT_H
#define EXT_D6_JOINT_H
#include "extensions/PxD6Joint.h"
#include "ExtJoint.h"
namespace physx
{
struct PxD6JointGeneratedValues;
namespace Ext
{
struct D6JointData : public JointData
{
PxD6Motion::Enum motion[6];
PxJointLinearLimit distanceLimit;
PxJointLinearLimitPair linearLimitX;
PxJointLinearLimitPair linearLimitY;
PxJointLinearLimitPair linearLimitZ;
PxJointAngularLimitPair twistLimit;
PxJointLimitCone swingLimit;
PxJointLimitPyramid pyramidSwingLimit;
PxD6JointDrive drive[PxD6Drive::eCOUNT];
PxTransform drivePosition;
PxVec3 driveLinearVelocity;
PxVec3 driveAngularVelocity;
// derived quantities
PxU32 locked; // bitmap of locked DOFs
PxU32 limited; // bitmap of limited DOFs
PxU32 driving; // bitmap of active drives (implies driven DOFs not locked)
PxReal distanceMinDist; // distance limit minimum distance to get a good direction
// PT: the PxD6Motion values are now shared for both kind of linear limits, so we need
// an extra bool to know which one(s) should be actually used.
bool mUseDistanceLimit;
bool mUseNewLinearLimits;
// PT: the swing limits can now be a cone or a pyramid, so we need
// an extra bool to know which one(s) should be actually used.
bool mUseConeLimit;
bool mUsePyramidLimits;
private:
D6JointData(const PxJointLinearLimit& distance,
const PxJointLinearLimitPair& linearX,
const PxJointLinearLimitPair& linearY,
const PxJointLinearLimitPair& linearZ,
const PxJointAngularLimitPair& twist,
const PxJointLimitCone& swing,
const PxJointLimitPyramid& pyramid) :
distanceLimit (distance),
linearLimitX (linearX),
linearLimitY (linearY),
linearLimitZ (linearZ),
twistLimit (twist),
swingLimit (swing),
pyramidSwingLimit (pyramid),
mUseDistanceLimit (false),
mUseNewLinearLimits (false),
mUseConeLimit (false),
mUsePyramidLimits (false)
{}
};
typedef JointT<PxD6Joint, D6JointData, PxD6JointGeneratedValues> D6JointT;
class D6Joint : public D6JointT
{
public:
// PX_SERIALIZATION
D6Joint(PxBaseFlags baseFlags) : D6JointT(baseFlags) {}
void resolveReferences(PxDeserializationContext& context);
static D6Joint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<D6Joint>(address, context); }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
D6Joint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1);
// PxD6Joint
virtual void setMotion(PxD6Axis::Enum index, PxD6Motion::Enum t) PX_OVERRIDE;
virtual PxD6Motion::Enum getMotion(PxD6Axis::Enum index) const PX_OVERRIDE;
virtual PxReal getTwistAngle() const PX_OVERRIDE;
virtual PxReal getSwingYAngle() const PX_OVERRIDE;
virtual PxReal getSwingZAngle() const PX_OVERRIDE;
virtual void setDistanceLimit(const PxJointLinearLimit& l) PX_OVERRIDE;
virtual PxJointLinearLimit getDistanceLimit() const PX_OVERRIDE;
virtual void setLinearLimit(PxD6Axis::Enum axis, const PxJointLinearLimitPair& limit) PX_OVERRIDE;
virtual PxJointLinearLimitPair getLinearLimit(PxD6Axis::Enum axis) const PX_OVERRIDE;
virtual void setTwistLimit(const PxJointAngularLimitPair& l) PX_OVERRIDE;
virtual PxJointAngularLimitPair getTwistLimit() const PX_OVERRIDE;
virtual void setSwingLimit(const PxJointLimitCone& l) PX_OVERRIDE;
virtual PxJointLimitCone getSwingLimit() const PX_OVERRIDE;
virtual void setPyramidSwingLimit(const PxJointLimitPyramid& limit) PX_OVERRIDE;
virtual PxJointLimitPyramid getPyramidSwingLimit() const PX_OVERRIDE;
virtual void setDrive(PxD6Drive::Enum index, const PxD6JointDrive& d) PX_OVERRIDE;
virtual PxD6JointDrive getDrive(PxD6Drive::Enum index) const PX_OVERRIDE;
virtual void setDrivePosition(const PxTransform& pose, bool autowake = true) PX_OVERRIDE;
virtual PxTransform getDrivePosition() const PX_OVERRIDE;
virtual void setDriveVelocity(const PxVec3& linear, const PxVec3& angular, bool autowake = true) PX_OVERRIDE;
virtual void getDriveVelocity(PxVec3& linear, PxVec3& angular) const PX_OVERRIDE;
//~PxD6Joint
// PxConstraintConnector
virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE;
virtual void* prepareData() PX_OVERRIDE;
#if PX_SUPPORT_OMNI_PVD
virtual void updateOmniPvdProperties() const PX_OVERRIDE;
#endif
//~PxConstraintConnector
private:
bool active(const PxD6Drive::Enum index) const
{
const PxD6JointDrive& d = data().drive[index];
return d.stiffness!=0 || d.damping != 0;
}
bool mRecomputeMotion;
bool mPadding[3]; // PT: padding from prev bool
};
} // namespace Ext
} // namespace physx
#endif
| 6,579 | C | 40.645569 | 158 | 0.755586 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtMetaData.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 "common/PxMetaData.h"
#include "extensions/PxJoint.h"
#include "ExtJoint.h"
#include "ExtD6Joint.h"
#include "ExtFixedJoint.h"
#include "ExtSphericalJoint.h"
#include "ExtDistanceJoint.h"
#include "ExtContactJoint.h"
#include "ExtRevoluteJoint.h"
#include "ExtPrismaticJoint.h"
#include "serialization/SnSerializationRegistry.h"
#include "serialization/Binary/SnSerializationContext.h"
using namespace physx;
using namespace Cm;
using namespace Ext;
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_JointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, JointData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, JointData, PxTransform32, c2b, 0)
PX_DEF_BIN_METADATA_ITEM(stream, JointData, PxConstraintInvMassScale, invMassScale, 0)
}
static void getBinaryMetaData_PxD6JointDrive(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxD6JointDriveFlags, PxU32)
PX_DEF_BIN_METADATA_CLASS(stream, PxD6JointDrive)
PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxReal, stiffness, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxReal, forceLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxD6JointDriveFlags, flags, 0)
}
static void getBinaryMetaData_PxJointLimitParameters(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxJointLimitParameters)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, restitution, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, bounceThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, stiffness, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, damping, 0)
}
static void getBinaryMetaData_PxJointLinearLimit(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxJointLinearLimit)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLinearLimit, PxJointLimitParameters)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLinearLimit, PxReal, value, 0)
}
static void getBinaryMetaData_PxJointLinearLimitPair(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxJointLinearLimitPair)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLinearLimitPair, PxJointLimitParameters)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLinearLimitPair, PxReal, upper, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLinearLimitPair, PxReal, lower, 0)
}
static void getBinaryMetaData_PxJointAngularLimitPair(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxJointAngularLimitPair)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointAngularLimitPair, PxJointLimitParameters)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointAngularLimitPair, PxReal, upper, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointAngularLimitPair, PxReal, lower, 0)
}
static void getBinaryMetaData_PxJointLimitCone(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxJointLimitCone)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLimitCone, PxJointLimitParameters)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitCone, PxReal, yAngle, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitCone, PxReal, zAngle, 0)
}
static void getBinaryMetaData_PxJointLimitPyramid(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxJointLimitPyramid)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLimitPyramid, PxJointLimitParameters)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, yAngleMin, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, yAngleMax, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, zAngleMin, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, zAngleMax, 0)
}
void PxJoint::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_VCLASS(stream, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJoint, PxBase)
PX_DEF_BIN_METADATA_ITEM(stream, PxJoint, void, userData, PxMetaDataFlag::ePTR)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_RevoluteJointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxRevoluteJointFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, RevoluteJointData)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, RevoluteJointData, JointData)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxReal, driveVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxReal, driveForceLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxReal, driveGearRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxJointAngularLimitPair,limit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxRevoluteJointFlags, jointFlags, 0)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING)
#endif
}
void RevoluteJoint::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_RevoluteJointData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, RevoluteJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, RevoluteJoint, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, RevoluteJoint, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJoint, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, RevoluteJoint, PxTransform, mLocalPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJoint, JointData, mData, PxMetaDataFlag::ePTR)
//------ Extra-data ------
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, RevoluteJoint, RevoluteJointData, mData, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, RevoluteJoint, mName, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_SphericalJointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxSphericalJointFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, SphericalJointData)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, SphericalJointData, JointData)
PX_DEF_BIN_METADATA_ITEM(stream, SphericalJointData, PxJointLimitCone, limit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, SphericalJointData, PxSphericalJointFlags, jointFlags, 0)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEM(stream, SphericalJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING)
#endif
}
void SphericalJoint::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_SphericalJointData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, SphericalJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, SphericalJoint, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, SphericalJoint, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, SphericalJoint, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, SphericalJoint, PxTransform, mLocalPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, SphericalJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, SphericalJoint, JointData, mData, PxMetaDataFlag::ePTR)
//------ Extra-data ------
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, SphericalJoint, SphericalJointData, mData, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, SphericalJoint, mName, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_DistanceJointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxDistanceJointFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, DistanceJointData)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, DistanceJointData, JointData)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, minDistance, 0)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, maxDistance, 0)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, tolerance, 0)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, stiffness, 0)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxDistanceJointFlags, jointFlags, 0)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING)
#endif
}
void DistanceJoint::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_DistanceJointData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, DistanceJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, DistanceJoint, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, DistanceJoint, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJoint, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, DistanceJoint, PxTransform, mLocalPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, DistanceJoint, JointData, mData, PxMetaDataFlag::ePTR)
//------ Extra-data ------
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, DistanceJoint, DistanceJointData, mData, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, DistanceJoint, mName, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_D6JointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxD6Motion::Enum, PxU32)
PX_DEF_BIN_METADATA_CLASS(stream, D6JointData)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, D6JointData, JointData)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6JointData, PxD6Motion::Enum, motion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimit, distanceLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimitPair, linearLimitX, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimitPair, linearLimitY, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimitPair, linearLimitZ, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointAngularLimitPair, twistLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLimitCone, swingLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLimitPyramid, pyramidSwingLimit, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6JointData, PxD6JointDrive, drive, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxTransform, drivePosition, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxVec3, driveLinearVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxVec3, driveAngularVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxU32, locked, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxU32, limited, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxU32, driving, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxReal, distanceMinDist, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUseDistanceLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUseNewLinearLimits, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUseConeLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUsePyramidLimits, 0)
}
void D6Joint::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_D6JointData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, D6Joint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, D6Joint, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, D6Joint, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6Joint, PxTransform, mLocalPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, JointData, mData, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, bool, mRecomputeMotion, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6Joint, bool, mPadding, PxMetaDataFlag::ePADDING)
//------ Extra-data ------
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, D6Joint, D6JointData, mData, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, D6Joint, mName, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_PrismaticJointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxPrismaticJointFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, PrismaticJointData)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PrismaticJointData, JointData)
PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJointData, PxJointLinearLimitPair, limit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJointData, PxPrismaticJointFlags, jointFlags, 0)
#ifdef EXPLICIT_PADDING_METADATA
PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING)
#endif
}
void PrismaticJoint::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_PrismaticJointData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, PrismaticJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PrismaticJoint, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PrismaticJoint, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJoint, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PrismaticJoint, PxTransform, mLocalPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJoint, JointData, mData, PxMetaDataFlag::ePTR)
//------ Extra-data ------
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, PrismaticJoint, PrismaticJointData, mData, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, PrismaticJoint, mName, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_FixedJointData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, FixedJointData)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, FixedJointData, JointData)
}
void FixedJoint::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_FixedJointData(stream);
PX_DEF_BIN_METADATA_VCLASS(stream, FixedJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, FixedJoint, PxJoint)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, FixedJoint, PxConstraintConnector)
PX_DEF_BIN_METADATA_ITEM(stream, FixedJoint, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, FixedJoint, PxTransform, mLocalPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, FixedJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, FixedJoint, JointData, mData, PxMetaDataFlag::ePTR)
//------ Extra-data ------
PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, FixedJoint, FixedJointData, mData, PX_SERIAL_ALIGN)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, FixedJoint, mName, 0)
}
void getBinaryMetaData_SerializationContext(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxSerialObjectId, PxU64)
PX_DEF_BIN_METADATA_TYPEDEF(stream, SerialObjectIndex, PxU32)
PX_DEF_BIN_METADATA_CLASS(stream, Sn::ManifestEntry)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::ManifestEntry, PxU32, offset, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::ManifestEntry, PxType, type, 0)
PX_DEF_BIN_METADATA_CLASS(stream, Sn::ImportReference)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::ImportReference, PxSerialObjectId, id, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::ImportReference, PxType, type, 0)
PX_DEF_BIN_METADATA_CLASS(stream, Sn::ExportReference)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::ExportReference, PxSerialObjectId, id, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::ExportReference, SerialObjectIndex, objIndex, 0)
PX_DEF_BIN_METADATA_CLASS(stream, Sn::InternalReferencePtr)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferencePtr, void, reference, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferencePtr, SerialObjectIndex, objIndex, 0)
PX_DEF_BIN_METADATA_CLASS(stream, Sn::InternalReferenceHandle16)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferenceHandle16, PxU16, reference, PxMetaDataFlag::eHANDLE)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferenceHandle16, PxU16, pad, PxMetaDataFlag::ePADDING)
PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferenceHandle16, SerialObjectIndex, objIndex, 0)
}
namespace physx
{
namespace Ext
{
void GetExtensionsBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_VCLASS(stream,PxConstraintConnector)
getBinaryMetaData_JointData(stream);
getBinaryMetaData_PxD6JointDrive(stream);
getBinaryMetaData_PxJointLimitParameters(stream);
getBinaryMetaData_PxJointLimitCone(stream);
getBinaryMetaData_PxJointLimitPyramid(stream);
getBinaryMetaData_PxJointLinearLimit(stream);
getBinaryMetaData_PxJointLinearLimitPair(stream);
getBinaryMetaData_PxJointAngularLimitPair(stream);
PxJoint::getBinaryMetaData(stream);
RevoluteJoint::getBinaryMetaData(stream);
SphericalJoint::getBinaryMetaData(stream);
DistanceJoint::getBinaryMetaData(stream);
D6Joint::getBinaryMetaData(stream);
PrismaticJoint::getBinaryMetaData(stream);
FixedJoint::getBinaryMetaData(stream);
getBinaryMetaData_SerializationContext(stream);
}
}
}
///////////////////////////////////////////////////////////////////////////////
| 19,509 | C++ | 44.584112 | 121 | 0.737352 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSphericalJoint.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 "ExtSphericalJoint.h"
#include "ExtConstraintHelper.h"
#include "CmConeLimitHelper.h"
#include "omnipvd/ExtOmniPvdSetData.h"
using namespace physx;
using namespace Ext;
SphericalJoint::SphericalJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) :
SphericalJointT(PxJointConcreteType::eSPHERICAL, actor0, localFrame0, actor1, localFrame1, "SphericalJointData")
{
SphericalJointData* data = static_cast<SphericalJointData*>(mData);
data->limit = PxJointLimitCone(PxPi/2, PxPi/2);
data->jointFlags = PxSphericalJointFlags();
}
void SphericalJoint::setLimitCone(const PxJointLimitCone &limit)
{
PX_CHECK_AND_RETURN(limit.isValid(), "PxSphericalJoint::setLimit: invalid parameter");
data().limit = limit;
markDirty();
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxSphericalJoint& j = static_cast<PxSphericalJoint&>(*this);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitYAngle, j, limit.yAngle)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitZAngle, j, limit.zAngle)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitRestitution, j, limit.restitution)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitBounceThreshold, j, limit.bounceThreshold)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitStiffness, j, limit.stiffness)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitDamping, j, limit.damping)
OMNI_PVD_WRITE_SCOPE_END
#endif
}
PxJointLimitCone SphericalJoint::getLimitCone() const
{
return data().limit;
}
PxSphericalJointFlags SphericalJoint::getSphericalJointFlags(void) const
{
return data().jointFlags;
}
void SphericalJoint::setSphericalJointFlags(PxSphericalJointFlags flags)
{
data().jointFlags = flags;
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, jointFlags, static_cast<PxSphericalJoint&>(*this), flags)
}
void SphericalJoint::setSphericalJointFlag(PxSphericalJointFlag::Enum flag, bool value)
{
if(value)
data().jointFlags |= flag;
else
data().jointFlags &= ~flag;
markDirty();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, jointFlags, static_cast<PxSphericalJoint&>(*this), getSphericalJointFlags())
}
PxReal SphericalJoint::getSwingYAngle() const
{
return getSwingYAngle_Internal();
}
PxReal SphericalJoint::getSwingZAngle() const
{
return getSwingZAngle_Internal();
}
static void SphericalJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags)
{
const SphericalJointData& data = *reinterpret_cast<const SphericalJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform);
if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES)
viz.visualizeJointFrames(cA2w, cB2w);
if((flags & PxConstraintVisualizationFlag::eLIMITS) && (data.jointFlags & PxSphericalJointFlag::eLIMIT_ENABLED))
{
joint::applyNeighborhoodOperator(cA2w, cB2w);
const PxTransform cB2cA = cA2w.transformInv(cB2w);
PxQuat swing, twist;
PxSeparateSwingTwist(cB2cA.q, swing, twist);
viz.visualizeLimitCone(cA2w, PxTan(data.limit.zAngle/4), PxTan(data.limit.yAngle/4));
}
}
//TAG:solverprepshader
static PxU32 SphericalJointSolverPrep(Px1DConstraint* constraints,
PxVec3p& body0WorldOffset,
PxU32 /*maxConstraints*/,
PxConstraintInvMassScale& invMassScale,
const void* constantBlock,
const PxTransform& bA2w,
const PxTransform& bB2w,
bool /*useExtendedLimits*/,
PxVec3p& cA2wOut, PxVec3p& cB2wOut)
{
const SphericalJointData& data = *reinterpret_cast<const SphericalJointData*>(constantBlock);
PxTransform32 cA2w, cB2w;
joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w);
joint::applyNeighborhoodOperator(cA2w, cB2w);
if(data.jointFlags & PxSphericalJointFlag::eLIMIT_ENABLED)
{
PxQuat swing, twist;
PxSeparateSwingTwist(cA2w.q.getConjugate() * cB2w.q, swing, twist);
PX_ASSERT(PxAbs(swing.x)<1e-6f);
PxVec3 axis;
PxReal error;
const Cm::ConeLimitHelperTanLess coneHelper(data.limit.yAngle, data.limit.zAngle);
coneHelper.getLimit(swing, axis, error);
ch.angularLimit(cA2w.rotate(axis), error, data.limit);
}
PxVec3 ra, rb;
ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, 0, ra, rb);
cA2wOut = ra + bA2w.p;
cB2wOut = rb + bB2w.p;
return ch.getCount();
}
///////////////////////////////////////////////////////////////////////////////
static PxConstraintShaderTable gSphericalJointShaders = { SphericalJointSolverPrep, SphericalJointVisualize, PxConstraintFlag::Enum(0) };
PxConstraintSolverPrep SphericalJoint::getPrep() const { return gSphericalJointShaders.solverPrep; }
PxSphericalJoint* physx::PxSphericalJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1)
{
PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxSphericalJointCreate: local frame 0 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxSphericalJointCreate: local frame 1 is not a valid transform");
PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxSphericalJointCreate: actors must be different");
PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxSphericalJointCreate: at least one actor must be dynamic");
return createJointT<SphericalJoint, SphericalJointData>(physics, actor0, localFrame0, actor1, localFrame1, gSphericalJointShaders);
}
// PX_SERIALIZATION
void SphericalJoint::resolveReferences(PxDeserializationContext& context)
{
mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gSphericalJointShaders);
}
//~PX_SERIALIZATION
#if PX_SUPPORT_OMNI_PVD
void SphericalJoint::updateOmniPvdProperties() const
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
const PxSphericalJoint& j = static_cast<const PxSphericalJoint&>(*this);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingYAngle, j, getSwingYAngle())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingZAngle, j, getSwingZAngle())
OMNI_PVD_WRITE_SCOPE_END
}
template<>
void physx::Ext::omniPvdInitJoint<SphericalJoint>(SphericalJoint& joint)
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxSphericalJoint& j = static_cast<PxSphericalJoint&>(joint);
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, j);
omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eSPHERICAL);
PxJointLimitCone limit = joint.getLimitCone();
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitYAngle, j, limit.yAngle)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitZAngle, j, limit.zAngle)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitRestitution, j, limit.restitution)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitBounceThreshold, j, limit.bounceThreshold)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitStiffness, j, limit.stiffness)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitDamping, j, limit.damping)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, jointFlags, j, joint.getSphericalJointFlags())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingYAngle, j, joint.getSwingYAngle())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingZAngle, j, joint.getSwingZAngle())
OMNI_PVD_WRITE_SCOPE_END
}
#endif
| 9,876 | C++ | 42.70354 | 176 | 0.777845 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRemeshingExt.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 "extensions/PxRemeshingExt.h"
#include "foundation/PxHashMap.h"
namespace physx
{
void assignTriangle(PxArray<PxU32>& triangles, PxU32 triIndex, PxU32 a, PxU32 b, PxU32 c)
{
triangles[3 * triIndex] = a;
triangles[3 * triIndex + 1] = b;
triangles[3 * triIndex + 2] = c;
}
void addTriangle(PxArray<PxU32>& triangles, PxU32 a, PxU32 b, PxU32 c)
{
triangles.pushBack(a);
triangles.pushBack(b);
triangles.pushBack(c);
}
void subdivideTriangle(int i, int ab, int bc, int ac, PxArray<PxU32>& triangles, PxArray<PxVec3>& points)
{
PxU32 tri[3] = { triangles[3 * i],triangles[3 * i + 1],triangles[3 * i + 2] };
if (ab >= 0 && bc >= 0 && ac >= 0)
{
addTriangle(triangles, tri[0], ab, ac);
addTriangle(triangles, tri[1], bc, ab);
addTriangle(triangles, tri[2], ac, bc);
assignTriangle(triangles, i, ab, bc, ac);
}
else if (ac >= 0 && ab >= 0)
{
float dB = (points[ac] - points[tri[1]]).magnitudeSquared();
float dC = (points[ab] - points[tri[2]]).magnitudeSquared();
if (dB < dC)
{
addTriangle(triangles, tri[1], tri[2], ac);
addTriangle(triangles, tri[1], ac, ab);
}
else
{
addTriangle(triangles, tri[1], tri[2], ab);
addTriangle(triangles, tri[2], ac, ab);
}
assignTriangle(triangles, i, tri[0], ab, ac);
}
else if (ab >= 0 && bc >= 0)
{
float dA = (points[bc] - points[tri[0]]).magnitudeSquared();
float dC = (points[ab] - points[tri[2]]).magnitudeSquared();
if (dC < dA)
{
addTriangle(triangles, tri[2], tri[0], ab);
addTriangle(triangles, tri[2], ab, bc);
}
else
{
addTriangle(triangles, tri[2], tri[0], bc);
addTriangle(triangles, tri[0], ab, bc);
}
assignTriangle(triangles, i, tri[1], bc, ab);
}
else if (bc >= 0 && ac >= 0)
{
float dA = (points[bc] - points[tri[0]]).magnitudeSquared();
float dB = (points[ac] - points[tri[1]]).magnitudeSquared();
if (dA < dB)
{
addTriangle(triangles, tri[0], tri[1], bc);
addTriangle(triangles, tri[0], bc, ac);
}
else
{
addTriangle(triangles, tri[0], tri[1], ac);
addTriangle(triangles, tri[1], bc, ac);
}
assignTriangle(triangles, i, tri[2], ac, bc);
}
else if (ab >= 0)
{
addTriangle(triangles, tri[1], tri[2], ab);
assignTriangle(triangles, i, tri[2], tri[0], ab);
}
else if (bc >= 0)
{
addTriangle(triangles, tri[2], tri[0], bc);
assignTriangle(triangles, i, tri[0], tri[1], bc);
}
else if (ac >= 0)
{
addTriangle(triangles, tri[1], tri[2], ac);
assignTriangle(triangles, i, tri[0], tri[1], ac);
}
}
PX_FORCE_INLINE PxU64 key(PxU32 a, PxU32 b)
{
if (a < b)
return ((PxU64(a)) << 32) | (PxU64(b));
else
return ((PxU64(b)) << 32) | (PxU64(a));
}
void checkEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, PxI32>& edges, PxArray<PxVec3>& points, PxReal maxEdgeLength)
{
if ((points[a] - points[b]).magnitudeSquared() < maxEdgeLength * maxEdgeLength)
return;
PxU64 k = key(a, b);
if (edges.find(k))
return;
edges.insert(k, points.size());
points.pushBack(0.5f * (points[a] + points[b]));
}
PX_FORCE_INLINE PxI32 getEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, PxI32>& edges)
{
if (const PxPair<const PxU64, PxI32>* ptr = edges.find(key(a, b)))
return ptr->second;
return -1;
}
struct Info
{
PxI32 StartIndex;
PxI32 Count;
Info(PxI32 startIndex, PxI32 count)
{
StartIndex = startIndex;
Count = count;
}
};
void checkEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, Info>& edges, PxArray<PxVec3>& points, PxReal maxEdgeLength)
{
if (a > b)
PxSwap(a, b);
PxReal l = (points[a] - points[b]).magnitudeSquared();
if (l < maxEdgeLength * maxEdgeLength)
return;
l = PxSqrt(l);
PxU32 numSubdivisions = (PxU32)(l / maxEdgeLength);
if (numSubdivisions <= 1)
return;
PxU64 k = key(a, b);
if (edges.find(k))
return;
edges.insert(k, Info(points.size(), numSubdivisions - 1));
for (PxU32 i = 1; i < numSubdivisions; ++i)
{
PxReal p = (PxReal)i / numSubdivisions;
points.pushBack((1 - p) * points[a] + p * points[b]);
}
}
PX_FORCE_INLINE Info getEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, Info>& edges)
{
const PxPair<const PxU64, Info>* value = edges.find(key(a, b));
if (value)
return value->second;
return Info(-1, -1);
}
PX_FORCE_INLINE void addPoints(PxArray<PxU32>& polygon, const Info& ab, bool reverse)
{
if (reverse)
{
for (PxI32 i = ab.Count - 1; i >= 0; --i)
polygon.pushBack(ab.StartIndex + i);
}
else
{
for (PxI32 i = 0; i < ab.Count; ++i)
polygon.pushBack(ab.StartIndex + i);
}
}
PX_FORCE_INLINE PxReal angle(const PxVec3& l, const PxVec3& r)
{
PxReal d = l.dot(r) / PxSqrt(l.magnitudeSquared() * r.magnitudeSquared());
if (d <= -1) return PxPi;
if (d >= 1) return 0.0f;
return PxAcos(d);
}
PX_FORCE_INLINE PxReal evaluateCost(const PxArray<PxVec3>& vertices, PxU32 a, PxU32 b, PxU32 c)
{
const PxVec3& aa = vertices[a];
const PxVec3& bb = vertices[b];
const PxVec3& cc = vertices[c];
PxReal a1 = angle(bb - aa, cc - aa);
PxReal a2 = angle(aa - bb, cc - bb);
PxReal a3 = angle(aa - cc, bb - cc);
return PxMax(a1, PxMax(a2, a3));
//return (aa - bb).magnitude() + (aa - cc).magnitude() + (bb - cc).magnitude();
}
void triangulateConvex(PxU32 originalTriangleIndexTimes3, PxArray<PxU32>& polygon, const PxArray<PxVec3>& vertices, PxArray<PxU32>& triangles, PxArray<PxI32>& offsets)
{
offsets.forceSize_Unsafe(0);
offsets.reserve(polygon.size());
for (PxU32 i = 0; i < polygon.size(); ++i)
offsets.pushBack(1);
PxI32 start = 0;
PxU32 count = polygon.size();
PxU32 triCounter = 0;
while (count > 2)
{
PxReal minCost = FLT_MAX;
PxI32 best = -1;
PxI32 i = start;
for (PxU32 j = 0; j < count; ++j)
{
PxU32 a = polygon[i];
PX_ASSERT(offsets[i] >= 0);
PxI32 n = (i + offsets[i]) % polygon.size();
PX_ASSERT(offsets[n] >= 0);
PxU32 b = polygon[n];
PxU32 nn = (n + offsets[n]) % polygon.size();
PX_ASSERT(offsets[nn] >= 0);
PxU32 c = polygon[nn];
PxReal cost = evaluateCost(vertices, a, b, c);
if (cost < minCost)
{
minCost = cost;
best = i;
}
i = n;
}
{
PxU32 a = polygon[best];
PxI32 n = (best + offsets[best]) % polygon.size();
PxU32 b = polygon[n];
PxU32 nn = (n + offsets[n]) % polygon.size();
PxU32 c = polygon[nn];
if (n == start)
start += offsets[n];
offsets[best] += offsets[n];
offsets[n] = -1;
PX_ASSERT(offsets[(best + offsets[best]) % polygon.size()] >= 0);
if (triCounter == 0)
{
triangles[originalTriangleIndexTimes3 + 0] = a;
triangles[originalTriangleIndexTimes3 + 1] = b;
triangles[originalTriangleIndexTimes3 + 2] = c;
}
else
{
triangles.pushBack(a);
triangles.pushBack(b);
triangles.pushBack(c);
}
++triCounter;
}
--count;
}
}
bool limitMaxEdgeLengthAdaptive(PxArray<PxU32>& triangles, PxArray<PxVec3>& points, PxReal maxEdgeLength, PxArray<PxU32>* triangleMap = NULL)
{
PxHashMap<PxU64, Info> edges;
bool split = false;
//Analyze edges
for (PxU32 i = 0; i < triangles.size(); i += 3)
{
const PxU32* t = &triangles[i];
checkEdge(t[0], t[1], edges, points, maxEdgeLength);
checkEdge(t[1], t[2], edges, points, maxEdgeLength);
checkEdge(t[0], t[2], edges, points, maxEdgeLength);
}
PxArray<PxI32> offsets;
PxArray<PxU32> polygon;
//Subdivide triangles if required
PxU32 size = triangles.size();
for (PxU32 i = 0; i < size; i += 3)
{
const PxU32* t = &triangles[i];
Info ab = getEdge(t[0], t[1], edges);
Info bc = getEdge(t[1], t[2], edges);
Info ac = getEdge(t[0], t[2], edges);
if (ab.StartIndex >= 0 || bc.StartIndex >= 0 || ac.StartIndex >= 0)
{
polygon.forceSize_Unsafe(0);
polygon.pushBack(t[0]);
addPoints(polygon, ab, t[0] > t[1]);
polygon.pushBack(t[1]);
addPoints(polygon, bc, t[1] > t[2]);
polygon.pushBack(t[2]);
addPoints(polygon, ac, t[2] > t[0]);
PxU32 s = triangles.size();
triangulateConvex(i, polygon, points, triangles, offsets);
split = true;
if (triangleMap != NULL)
{
for (PxU32 j = s; j < triangles.size(); ++j)
triangleMap->pushBack((*triangleMap)[i]);
}
}
/*else
{
result.pushBack(t[0]);
result.pushBack(t[1]);
result.pushBack(t[2]);
if (triangleMap != NULL)
triangleMap->pushBack((*triangleMap)[i]);
}*/
}
return split;
}
bool PxRemeshingExt::reduceSliverTriangles(PxArray<PxU32>& triangles, PxArray<PxVec3>& points, PxReal maxEdgeLength, PxU32 maxIterations, PxArray<PxU32>* triangleMap, PxU32 triangleCountThreshold)
{
bool split = limitMaxEdgeLengthAdaptive(triangles, points, maxEdgeLength, triangleMap);
if (!split)
return false;
for (PxU32 i = 1; i < maxIterations; ++i)
{
split = limitMaxEdgeLengthAdaptive(triangles, points, maxEdgeLength, triangleMap);
if (!split)
break;
if (triangles.size() >= triangleCountThreshold)
break;
}
return true;
}
bool PxRemeshingExt::limitMaxEdgeLength(PxArray<PxU32>& triangles, PxArray<PxVec3>& points, PxReal maxEdgeLength, PxU32 maxIterations, PxArray<PxU32>* triangleMap, PxU32 triangleCountThreshold)
{
if (triangleMap)
{
triangleMap->clear();
triangleMap->reserve(triangles.size() / 3);
for (PxU32 i = 0; i < triangles.size() / 3; ++i)
triangleMap->pushBack(i);
}
PxU32 numIndices = triangles.size();
PxHashMap<PxU64, PxI32> edges;
bool success = true;
for (PxU32 k = 0; k < maxIterations && success; ++k)
{
success = false;
edges.clear();
//Analyze edges
for (PxU32 i = 0; i < triangles.size(); i += 3)
{
checkEdge(triangles[i], triangles[i + 1], edges, points, maxEdgeLength);
checkEdge(triangles[i + 1], triangles[i + 2], edges, points, maxEdgeLength);
checkEdge(triangles[i], triangles[i + 2], edges, points, maxEdgeLength);
}
//Subdivide triangles if required
PxU32 size = triangles.size();
for (PxU32 i = 0; i < size; i += 3)
{
PxI32 ab = getEdge(triangles[i], triangles[i + 1], edges);
PxI32 bc = getEdge(triangles[i + 1], triangles[i + 2], edges);
PxI32 ac = getEdge(triangles[i], triangles[i + 2], edges);
if (ab >= 0 || bc >= 0 || ac >= 0)
{
PxU32 s = triangles.size();
subdivideTriangle(i / 3, ab, bc, ac, triangles, points);
success = true;
if (triangleMap)
{
for (PxU32 j = s / 3; j < triangles.size() / 3; ++j)
triangleMap->pushBack((*triangleMap)[i / 3]);
}
}
}
if (triangles.size() >= triangleCountThreshold)
break;
}
return numIndices != triangles.size();
}
}
| 12,387 | C++ | 27.283105 | 197 | 0.631307 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCollection.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 "geometry/PxConvexMesh.h"
#include "geometry/PxTriangleMesh.h"
#include "geometry/PxHeightField.h"
#include "extensions/PxJoint.h"
#include "extensions/PxConstraintExt.h"
#include "extensions/PxCollectionExt.h"
#include "PxShape.h"
#include "PxMaterial.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxAggregate.h"
#include "PxPhysics.h"
#include "PxScene.h"
#include "PxPruningStructure.h"
#include "foundation/PxArray.h"
using namespace physx;
void PxCollectionExt::releaseObjects(PxCollection& collection, bool releaseExclusiveShapes)
{
PxArray<PxBase*> releasableObjects;
for (PxU32 i = 0; i < collection.getNbObjects(); ++i)
{
PxBase* s = &collection.getObject(i);
// pruning structure must be released before its actors
if(s->is<PxPruningStructure>())
{
if(!releasableObjects.empty())
{
PxBase* first = releasableObjects[0];
releasableObjects.pushBack(first);
releasableObjects[0] = s;
}
}
else
{
if (s->isReleasable() && (releaseExclusiveShapes || !s->is<PxShape>() || !s->is<PxShape>()->isExclusive()))
releasableObjects.pushBack(s);
}
}
for (PxU32 i = 0; i < releasableObjects.size(); ++i)
releasableObjects[i]->release();
while (collection.getNbObjects() > 0)
collection.remove(collection.getObject(0));
}
void PxCollectionExt::remove(PxCollection& collection, PxType concreteType, PxCollection* to)
{
PxArray<PxBase*> removeObjects;
for (PxU32 i = 0; i < collection.getNbObjects(); i++)
{
PxBase& object = collection.getObject(i);
if(concreteType == object.getConcreteType())
{
if(to)
to->add(object);
removeObjects.pushBack(&object);
}
}
for (PxU32 i = 0; i < removeObjects.size(); ++i)
collection.remove(*removeObjects[i]);
}
PxCollection* PxCollectionExt::createCollection(PxPhysics& physics)
{
PxCollection* collection = PxCreateCollection();
if (!collection)
return NULL;
// Collect convexes
{
PxArray<PxConvexMesh*> objects(physics.getNbConvexMeshes());
const PxU32 nb = physics.getConvexMeshes(objects.begin(), objects.size());
PX_ASSERT(nb == objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
// Collect triangle meshes
{
PxArray<PxTriangleMesh*> objects(physics.getNbTriangleMeshes());
const PxU32 nb = physics.getTriangleMeshes(objects.begin(), objects.size());
PX_ASSERT(nb == objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
// Collect heightfields
{
PxArray<PxHeightField*> objects(physics.getNbHeightFields());
const PxU32 nb = physics.getHeightFields(objects.begin(), objects.size());
PX_ASSERT(nb == objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
// Collect materials
{
PxArray<PxMaterial*> objects(physics.getNbMaterials());
const PxU32 nb = physics.getMaterials(objects.begin(), objects.size());
PX_ASSERT(nb == objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
// Collect shapes
{
PxArray<PxShape*> objects(physics.getNbShapes());
const PxU32 nb = physics.getShapes(objects.begin(), objects.size());
PX_ASSERT(nb == objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
return collection;
}
PxCollection* PxCollectionExt::createCollection(PxScene& scene)
{
PxCollection* collection = PxCreateCollection();
if (!collection)
return NULL;
// Collect actors
{
PxActorTypeFlags selectionFlags = PxActorTypeFlag::eRIGID_STATIC | PxActorTypeFlag::eRIGID_DYNAMIC;
PxArray<PxActor*> objects(scene.getNbActors(selectionFlags));
const PxU32 nb = scene.getActors(selectionFlags, objects.begin(), objects.size());
PX_ASSERT(nb==objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
// Collect constraints
{
PxArray<PxConstraint*> objects(scene.getNbConstraints());
const PxU32 nb = scene.getConstraints(objects.begin(), objects.size());
PX_ASSERT(nb==objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
{
PxU32 typeId;
PxJoint* joint = reinterpret_cast<PxJoint*>(objects[i]->getExternalReference(typeId));
if(typeId == PxConstraintExtIDs::eJOINT)
collection->add(*joint);
}
}
// Collect articulations
{
PxArray<PxArticulationReducedCoordinate*> objects(scene.getNbArticulations());
const PxU32 nb = scene.getArticulations(objects.begin(), objects.size());
PX_ASSERT(nb==objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
// Collect aggregates
{
PxArray<PxAggregate*> objects(scene.getNbAggregates());
const PxU32 nb = scene.getAggregates(objects.begin(), objects.size());
PX_ASSERT(nb==objects.size());
PX_UNUSED(nb);
for(PxU32 i=0;i<objects.size();i++)
collection->add(*objects[i]);
}
return collection;
}
| 6,731 | C++ | 27.892704 | 110 | 0.713861 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqQuery.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 "ExtSqQuery.h"
using namespace physx;
using namespace Sq;
#include "common/PxProfileZone.h"
#include "foundation/PxFPU.h"
#include "GuBounds.h"
#include "GuIntersectionRayBox.h"
#include "GuIntersectionRay.h"
#include "GuBVH.h"
#include "geometry/PxGeometryQuery.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxTriangleMeshGeometry.h"
//#include "geometry/PxBVH.h"
#include "PxQueryFiltering.h"
#include "PxRigidActor.h"
using namespace physx;
using namespace Sq;
using namespace Gu;
///////////////////////////////////////////////////////////////////////////////
PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
// PT: this is a customized version of physx::Sq::SceneQueries that supports more than 2 hardcoded pruners.
// It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners.
// See #MODIFIED tag for what changed in this file compared to the initial code in SqQuery.cpp
static PX_FORCE_INLINE void copy(PxRaycastHit* PX_RESTRICT dest, const PxRaycastHit* PX_RESTRICT src)
{
dest->faceIndex = src->faceIndex;
dest->flags = src->flags;
dest->position = src->position;
dest->normal = src->normal;
dest->distance = src->distance;
dest->u = src->u;
dest->v = src->v;
dest->actor = src->actor;
dest->shape = src->shape;
}
static PX_FORCE_INLINE void copy(PxSweepHit* PX_RESTRICT dest, const PxSweepHit* PX_RESTRICT src)
{
dest->faceIndex = src->faceIndex;
dest->flags = src->flags;
dest->position = src->position;
dest->normal = src->normal;
dest->distance = src->distance;
dest->actor = src->actor;
dest->shape = src->shape;
}
static PX_FORCE_INLINE void copy(PxOverlapHit* PX_RESTRICT dest, const PxOverlapHit* PX_RESTRICT src)
{
dest->faceIndex = src->faceIndex;
dest->actor = src->actor;
dest->shape = src->shape;
}
// these partial template specializations are used to generalize the query code to be reused for all permutations of
// hit type=(raycast, overlap, sweep) x query type=(ANY, SINGLE, MULTIPLE)
template <typename HitType> struct HitTypeSupport { enum { IsRaycast = 0, IsSweep = 0, IsOverlap = 0 }; };
template <> struct HitTypeSupport<PxRaycastHit>
{
enum { IsRaycast = 1, IsSweep = 0, IsOverlap = 0 };
static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit& hit) { return static_cast<const PxRaycastHit&>(hit).distance; }
};
template <> struct HitTypeSupport<PxSweepHit>
{
enum { IsRaycast = 0, IsSweep = 1, IsOverlap = 0 };
static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit& hit) { return static_cast<const PxSweepHit&>(hit).distance; }
};
template <> struct HitTypeSupport<PxOverlapHit>
{
enum { IsRaycast = 0, IsSweep = 0, IsOverlap = 1 };
static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit&) { return -1.0f; }
};
#define HITDIST(hit) HitTypeSupport<HitType>::getDistance(hit)
template<typename HitType>
static PxU32 clipHitsToNewMaxDist(HitType* ppuHits, PxU32 count, PxReal newMaxDist)
{
PxU32 i=0;
while(i!=count)
{
if(HITDIST(ppuHits[i]) > newMaxDist)
ppuHits[i] = ppuHits[--count];
else
i++;
}
return count;
}
namespace physx
{
namespace Sq
{
struct ExtMultiQueryInput
{
const PxVec3* rayOrigin; // only valid for raycasts
const PxVec3* unitDir; // only valid for raycasts and sweeps
PxReal maxDistance; // only valid for raycasts and sweeps
const PxGeometry* geometry; // only valid for overlaps and sweeps
const PxTransform* pose; // only valid for overlaps and sweeps
PxReal inflation; // only valid for sweeps
// Raycast constructor
ExtMultiQueryInput(const PxVec3& aRayOrigin, const PxVec3& aUnitDir, PxReal aMaxDist)
{
rayOrigin = &aRayOrigin;
unitDir = &aUnitDir;
maxDistance = aMaxDist;
geometry = NULL;
pose = NULL;
inflation = 0.0f;
}
// Overlap constructor
ExtMultiQueryInput(const PxGeometry* aGeometry, const PxTransform* aPose)
{
geometry = aGeometry;
pose = aPose;
inflation = 0.0f;
rayOrigin = unitDir = NULL;
}
// Sweep constructor
ExtMultiQueryInput(
const PxGeometry* aGeometry, const PxTransform* aPose,
const PxVec3& aUnitDir, const PxReal aMaxDist, const PxReal aInflation)
{
rayOrigin = NULL;
maxDistance = aMaxDist;
unitDir = &aUnitDir;
geometry = aGeometry;
pose = aPose;
inflation = aInflation;
}
PX_FORCE_INLINE const PxVec3& getDir() const { PX_ASSERT(unitDir); return *unitDir; }
PX_FORCE_INLINE const PxVec3& getOrigin() const { PX_ASSERT(rayOrigin); return *rayOrigin; }
};
}
}
// performs a single geometry query for any HitType (PxSweepHit, PxOverlapHit, PxRaycastHit)
template<typename HitType>
struct ExtGeomQueryAny
{
static PX_FORCE_INLINE PxU32 geomHit(
const CachedFuncs& funcs, const ExtMultiQueryInput& input, const Gu::ShapeData* sd,
const PxGeometry& sceneGeom, const PxTransform& pose, PxHitFlags hitFlags,
PxU32 maxHits, HitType* hits, const PxReal shrunkMaxDistance, const PxBounds3* precomputedBounds,
PxQueryThreadContext* context)
{
using namespace Gu;
const PxGeometry& geom0 = *input.geometry;
const PxTransform& pose0 = *input.pose;
const PxGeometry& geom1 = sceneGeom;
const PxTransform& pose1 = pose;
// Handle raycasts
if(HitTypeSupport<HitType>::IsRaycast)
{
// the test for mesh AABB is archived in //sw/physx/dev/apokrovsky/graveyard/sqMeshAABBTest.cpp
// TODO: investigate performance impact (see US12801)
PX_CHECK_AND_RETURN_VAL(input.getDir().isFinite(), "PxScene::raycast(): rayDir is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(input.getOrigin().isFinite(), "PxScene::raycast(): rayOrigin is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(pose1.isValid(), "PxScene::raycast(): pose is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(shrunkMaxDistance >= 0.0f, "PxScene::raycast(): maxDist is negative.", 0);
PX_CHECK_AND_RETURN_VAL(PxIsFinite(shrunkMaxDistance), "PxScene::raycast(): maxDist is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(PxAbs(input.getDir().magnitudeSquared()-1)<1e-4f,
"PxScene::raycast(): ray direction must be unit vector.", 0);
// PT: TODO: investigate perf difference
const RaycastFunc func = funcs.mCachedRaycastFuncs[geom1.getType()];
return func(geom1, pose1, input.getOrigin(), input.getDir(), shrunkMaxDistance,
hitFlags, maxHits, reinterpret_cast<PxGeomRaycastHit*>(hits), sizeof(PxRaycastHit), context);
}
// Handle sweeps
else if(HitTypeSupport<HitType>::IsSweep)
{
PX_ASSERT(precomputedBounds != NULL);
PX_ASSERT(sd != NULL);
// b0 = query shape bounds
// b1 = scene shape bounds
// AP: Here we clip the sweep to bounds with sum of extents. This is needed for GJK stability.
// because sweep is equivalent to a raycast vs a scene shape with inflated bounds.
// This also may (or may not) provide an optimization for meshes because top level of rtree has multiple boxes
// and there is no bounds test for the whole mesh elsewhere
PxBounds3 b0 = *precomputedBounds, b1;
// compute the scene geometry bounds
// PT: TODO: avoid recomputing the bounds here
Gu::computeBounds(b1, sceneGeom, pose, 0.0f, 1.0f);
const PxVec3 combExt = (b0.getExtents() + b1.getExtents())*1.01f;
PxF32 tnear, tfar;
if(!intersectRayAABB2(-combExt, combExt, b0.getCenter() - b1.getCenter(), input.getDir(), shrunkMaxDistance, tnear, tfar)) // returns (tnear<tfar)
if(tnear>tfar) // this second test is needed because shrunkMaxDistance can be 0 for 0 length sweep
return 0;
PX_ASSERT(input.getDir().isNormalized());
// tfar is now the t where the ray exits the AABB. input.getDir() is normalized
const PxVec3& unitDir = input.getDir();
PxSweepHit& sweepHit = reinterpret_cast<PxSweepHit&>(hits[0]);
// if we don't start inside the AABB box, offset the start pos, because of precision issues with large maxDist
const bool offsetPos = (tnear > GU_RAY_SURFACE_OFFSET);
const PxReal offset = offsetPos ? (tnear - GU_RAY_SURFACE_OFFSET) : 0.0f;
const PxVec3 offsetVec(offsetPos ? (unitDir*offset) : PxVec3(0.0f));
// we move the geometry we sweep against, so that we avoid the Gu::Capsule/Box recomputation
const PxTransform pose1Offset(pose1.p - offsetVec, pose1.q);
const PxReal distance = PxMin(tfar, shrunkMaxDistance) - offset;
const PxReal inflation = input.inflation;
PX_CHECK_AND_RETURN_VAL(pose0.isValid(), "PxScene::sweep(): pose0 is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(pose1Offset.isValid(), "PxScene::sweep(): pose1 is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(unitDir.isFinite(), "PxScene::sweep(): unitDir is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(PxIsFinite(distance), "PxScene::sweep(): distance is not valid.", 0);
PX_CHECK_AND_RETURN_VAL((distance >= 0.0f && !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP)) || distance > 0.0f,
"PxScene::sweep(): sweep distance must be >=0 or >0 with eASSUME_NO_INITIAL_OVERLAP.", 0);
PxU32 retVal = 0;
const GeomSweepFuncs& sf = funcs.mCachedSweepFuncs;
switch(geom0.getType())
{
case PxGeometryType::eSPHERE:
{
const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom0);
const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f);
const Capsule worldCapsule(pose0.p, pose0.p, sphereGeom.radius); // AP: precompute?
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom1.getType()] : sf.capsuleMap[geom1.getType()];
retVal = PxU32(func(geom1, pose1Offset, capsuleGeom, pose0, worldCapsule, unitDir, distance, sweepHit, hitFlags, inflation, context));
}
break;
case PxGeometryType::eCAPSULE:
{
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom1.getType()] : sf.capsuleMap[geom1.getType()];
retVal = PxU32(func(geom1, pose1Offset, static_cast<const PxCapsuleGeometry&>(geom0), pose0, sd->getGuCapsule(), unitDir, distance, sweepHit, hitFlags, inflation, context));
}
break;
case PxGeometryType::eBOX:
{
const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP;
const SweepBoxFunc func = precise ? sf.preciseBoxMap[geom1.getType()] : sf.boxMap[geom1.getType()];
retVal = PxU32(func(geom1, pose1Offset, static_cast<const PxBoxGeometry&>(geom0), pose0, sd->getGuBox(), unitDir, distance, sweepHit, hitFlags, inflation, context));
}
break;
case PxGeometryType::eCONVEXMESH:
{
const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom0);
const SweepConvexFunc func = sf.convexMap[geom1.getType()];
retVal = PxU32(func(geom1, pose1Offset, convexGeom, pose0, unitDir, distance, sweepHit, hitFlags, inflation, context));
}
break;
default:
outputError<physx::PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::sweep(): first geometry object parameter must be sphere, capsule, box or convex geometry.");
break;
}
if (retVal)
{
// we need to offset the distance back
sweepHit.distance += offset;
// we need to offset the hit position back as we moved the geometry we sweep against
sweepHit.position += offsetVec;
}
return retVal;
}
// Handle overlaps
else if(HitTypeSupport<HitType>::IsOverlap)
{
const GeomOverlapTable* overlapFuncs = funcs.mCachedOverlapFuncs;
return PxU32(Gu::overlap(geom0, pose0, geom1, pose1, overlapFuncs, context));
}
else
{
PX_ALWAYS_ASSERT_MESSAGE("Unexpected template expansion in GeomQueryAny::geomHit");
return 0;
}
}
};
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE bool applyFilterEquation(const ExtQueryAdapter& adapter, const PrunerPayload& payload, const PxFilterData& queryFd)
{
// if the filterData field is non-zero, and the bitwise-AND value of filterData AND the shape's
// queryFilterData is zero, the shape is skipped.
if(queryFd.word0 | queryFd.word1 | queryFd.word2 | queryFd.word3)
{
// PT: TODO: revisit this, there's an obvious LHS here otherwise
// We could maybe make this more flexible and let the user do the filtering
// const PxFilterData& objFd = adapter.getFilterData(payload);
PxFilterData objFd;
adapter.getFilterData(payload, objFd);
const PxU32 keep = (queryFd.word0 & objFd.word0) | (queryFd.word1 & objFd.word1) | (queryFd.word2 & objFd.word2) | (queryFd.word3 & objFd.word3);
if(!keep)
return false;
}
return true;
}
static PX_FORCE_INLINE bool applyAllPreFiltersSQ(
const ExtQueryAdapter& adapter, const PrunerPayload& payload, const PxActorShape& as, PxQueryHitType::Enum& shapeHitType, const PxQueryFlags& inFilterFlags,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall,
PxHitFlags& queryFlags/*, PxU32 maxNbTouches*/)
{
// #MODIFIED
// PT: we have to do the static / dynamic filtering here now, because we're operating on N pruners
// and we don't know which one(s) are "static", which ones are "dynamic", and which ones are a mix of both.
const bool doStatics = filterData.flags & PxQueryFlag::eSTATIC;
const bool doDynamic = filterData.flags & PxQueryFlag::eDYNAMIC;
const PxType actorType = as.actor->getConcreteType();
const bool isStatic = (actorType == PxConcreteType::eRIGID_STATIC);
if(isStatic && !doStatics)
return false;
if(!isStatic && !doDynamic)
return false;
//~#MODIFIED
if(!(filterData.flags & PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR) && !applyFilterEquation(adapter, payload, filterData.data))
return false;
if((inFilterFlags & PxQueryFlag::ePREFILTER) && (filterCall))
{
PxHitFlags outQueryFlags = queryFlags;
if(filterCall)
shapeHitType = filterCall->preFilter(filterData.data, as.shape, as.actor, outQueryFlags);
// AP: at this point the callback might return eTOUCH but the touch buffer can be empty, the hit will be discarded
//PX_CHECK_MSG(hitType == PxQueryHitType::eTOUCH ? maxNbTouches > 0 : true,
// "SceneQuery: preFilter returned eTOUCH but empty touch buffer was provided, hit discarded.");
queryFlags = (queryFlags & ~PxHitFlag::eMODIFIABLE_FLAGS) | (outQueryFlags & PxHitFlag::eMODIFIABLE_FLAGS);
if(shapeHitType == PxQueryHitType::eNONE)
return false;
}
// test passed, continue to return as;
return true;
}
static PX_NOINLINE void computeCompoundShapeTransform(PxTransform* PX_RESTRICT transform, const PxTransform* PX_RESTRICT compoundPose, const PxTransform* PX_RESTRICT transforms, PxU32 primIndex)
{
// PT:: tag: scalar transform*transform
*transform = (*compoundPose) * transforms[primIndex];
}
// struct to access protected data members in the public PxHitCallback API
template<typename HitType>
struct ExtMultiQueryCallback : public PrunerRaycastCallback, public PrunerOverlapCallback, public CompoundPrunerRaycastCallback, public CompoundPrunerOverlapCallback
{
const ExtSceneQueries& mScene;
const ExtMultiQueryInput& mInput;
PxHitCallback<HitType>& mHitCall;
const PxHitFlags mHitFlags;
const PxQueryFilterData& mFilterData;
PxQueryFilterCallback* mFilterCall;
PxReal mShrunkDistance;
const PxHitFlags mMeshAnyHitFlags;
bool mReportTouchesAgain;
bool mFarBlockFound; // this is to prevent repeated searches for far block
const bool mNoBlock;
const bool mAnyHit;
// The reason we need these bounds is because we need to know combined(inflated shape) bounds to clip the sweep path
// to be tolerable by GJK precision issues. This test is done for (queryShape vs touchedShapes)
// So it makes sense to cache the bounds for sweep query shape, otherwise we'd have to recompute them every time
// Currently only used for sweeps.
const PxBounds3* mQueryShapeBounds;
const ShapeData* mShapeData;
PxTransform mCompoundShapeTransform;
ExtMultiQueryCallback(
const ExtSceneQueries& scene, const ExtMultiQueryInput& input, bool anyHit, PxHitCallback<HitType>& hitCall, PxHitFlags hitFlags,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, PxReal shrunkDistance) :
mScene (scene),
mInput (input),
mHitCall (hitCall),
mHitFlags (hitFlags),
mFilterData (filterData),
mFilterCall (filterCall),
mShrunkDistance (shrunkDistance),
mMeshAnyHitFlags ((hitFlags.isSet(PxHitFlag::eMESH_ANY) || anyHit) ? PxHitFlag::eMESH_ANY : PxHitFlag::Enum(0)),
mReportTouchesAgain (true),
mFarBlockFound (filterData.flags & PxQueryFlag::eNO_BLOCK),
mNoBlock (filterData.flags & PxQueryFlag::eNO_BLOCK),
mAnyHit (anyHit),
mQueryShapeBounds (NULL),
mShapeData (NULL)
{
}
bool processTouchHit(const HitType& hit, PxReal& aDist)
#if PX_WINDOWS_FAMILY
PX_RESTRICT
#endif
{
// -------------------------- handle eTOUCH hits ---------------------------------
// for qType=multiple, store the hit. For other qTypes ignore it.
// <= is important for initially overlapping sweeps
#if PX_CHECKED
if(mHitCall.maxNbTouches == 0 && !mFilterData.flags.isSet(PxQueryFlag::eRESERVED))
// issue a warning if eTOUCH was returned by the prefilter, we have 0 touch buffer and not a batch query
// not doing for BQ because the touches buffer can be overflown and thats ok by spec
// eRESERVED to avoid a warning from nested callback (closest blocking hit recursive search)
outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "User filter returned PxQueryHitType::eTOUCH but the touches buffer was empty. Hit was discarded.");
#endif
if(mHitCall.maxNbTouches && mReportTouchesAgain && HITDIST(hit) <= mShrunkDistance)
{
// Buffer full: need to find the closest blocking hit, clip touch hits and flush the buffer
if(mHitCall.nbTouches == mHitCall.maxNbTouches)
{
// issue a second nested query just looking for the closest blocking hit
// could do better perf-wise by saving traversal state (start looking for blocking from this point)
// but this is not a perf critical case because users can provide a bigger buffer
// that covers non-degenerate cases
// far block search doesn't apply to overlaps because overlaps don't work with blocking hits
if(HitTypeSupport<HitType>::IsOverlap == 0)
{
// AP: the use of eRESERVED is a bit tricky, see other comments containing #LABEL1
PxQueryFilterData fd1 = mFilterData; fd1.flags |= PxQueryFlag::eRESERVED;
PxHitBuffer<HitType> buf1; // create a temp callback buffer for a single blocking hit
if(!mFarBlockFound && mHitCall.maxNbTouches > 0 && mScene.ExtSceneQueries::multiQuery<HitType>(mInput, buf1, mHitFlags, NULL, fd1, mFilterCall))
{
mHitCall.block = buf1.block;
mHitCall.hasBlock = true;
mHitCall.nbTouches =
clipHitsToNewMaxDist<HitType>(mHitCall.touches, mHitCall.nbTouches, HITDIST(buf1.block));
mShrunkDistance = HITDIST(buf1.block);
aDist = mShrunkDistance;
}
mFarBlockFound = true;
}
if(mHitCall.nbTouches == mHitCall.maxNbTouches)
{
mReportTouchesAgain = mHitCall.processTouches(mHitCall.touches, mHitCall.nbTouches);
if(!mReportTouchesAgain)
return false; // optimization - buffer is full
else
mHitCall.nbTouches = 0; // reset nbTouches so we can continue accumulating again
}
}
//if(hitCall.nbTouches < hitCall.maxNbTouches) // can be true if maxNbTouches is 0
mHitCall.touches[mHitCall.nbTouches++] = hit;
} // if(hitCall.maxNbTouches && reportTouchesAgain && HITDIST(hit) <= shrunkDistance)
return true;
}
template<const bool isCached> // is this call coming as a callback from the pruner or a single item cached callback?
bool _invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose)
#if PX_WINDOWS_FAMILY
PX_RESTRICT
#endif
{
PX_ASSERT(payloads);
const PrunerPayload& payload = payloads[primIndex];
const ExtQueryAdapter& adapter = static_cast<const ExtQueryAdapter&>(mScene.mSQManager.getAdapter());
PxActorShape actorShape;
adapter.getActorShape(payload, actorShape);
const PxQueryFlags filterFlags = mFilterData.flags;
// for no filter callback, default to eTOUCH for MULTIPLE, eBLOCK otherwise
// also always treat as eBLOCK if currently tested shape is cached
// Using eRESERVED flag as a special condition to default to eTOUCH hits while only looking for a single blocking hit
// from a nested query (see other comments containing #LABEL1)
PxQueryHitType::Enum shapeHitType =
((mHitCall.maxNbTouches || (mFilterData.flags & PxQueryFlag::eRESERVED)) && !isCached)
? PxQueryHitType::eTOUCH
: PxQueryHitType::eBLOCK;
// apply pre-filter
PxHitFlags filteredHitFlags = mHitFlags;
if(!isCached) // don't run filters on single item cache
{
if(!applyAllPreFiltersSQ(adapter, payload, actorShape, shapeHitType/*in&out*/, filterFlags, mFilterData, mFilterCall, filteredHitFlags/*, mHitCall.maxNbTouches*/))
return true; // skip this shape from reporting if prefilter said to do so
// if(shapeHitType == PxQueryHitType::eNONE)
// return true;
}
const PxGeometry& shapeGeom = adapter.getGeometry(payload);
PX_ASSERT(transforms);
const PxTransform* shapeTransform;
if(!compoundPose)
{
shapeTransform = transforms + primIndex;
}
else
{
computeCompoundShapeTransform(&mCompoundShapeTransform, compoundPose, transforms, primIndex);
shapeTransform = &mCompoundShapeTransform;
}
const PxU32 tempCount = 1;
HitType tempBuf[tempCount];
// Here we decide whether to use the user provided buffer in place or a local stack buffer
// see if we have more room left in the callback results buffer than in the parent stack buffer
// if so get subHits in-place in the hit buffer instead of the parent stack buffer
// nbTouches is the number of accumulated touch hits so far
// maxNbTouches is the size of the user buffer
PxU32 maxSubHits1;
HitType* subHits1;
if(mHitCall.nbTouches >= mHitCall.maxNbTouches)
// if there's no room left in the user buffer, use a stack buffer
{
// tried using 64 here - causes check stack code to get generated on xbox, perhaps because of guard page
// need this buffer in case the input buffer is full but we still want to correctly merge results from later hits
maxSubHits1 = tempCount;
subHits1 = reinterpret_cast<HitType*>(tempBuf);
}
else
{
maxSubHits1 = mHitCall.maxNbTouches - mHitCall.nbTouches; // how much room is left in the user buffer
subHits1 = mHitCall.touches + mHitCall.nbTouches; // pointer to the first free hit in the user buffer
}
// call the geometry specific intersection template
const PxU32 nbSubHits = ExtGeomQueryAny<HitType>::geomHit(
mScene.mCachedFuncs, mInput, mShapeData, shapeGeom,
*shapeTransform, filteredHitFlags | mMeshAnyHitFlags,
maxSubHits1, subHits1, mShrunkDistance, mQueryShapeBounds, &mHitCall);
// ------------------------- iterate over geometry subhits -----------------------------------
for (PxU32 iSubHit = 0; iSubHit < nbSubHits; iSubHit++)
{
HitType& hit = subHits1[iSubHit];
hit.actor = actorShape.actor;
hit.shape = actorShape.shape;
// some additional processing only for sweep hits with initial overlap
if(HitTypeSupport<HitType>::IsSweep && HITDIST(hit) == 0.0f && !(filteredHitFlags & PxHitFlag::eMTD))
// PT: necessary as some leaf routines are called with reversed params, thus writing +unitDir there.
// AP: apparently still necessary to also do in Gu because Gu can be used standalone (without SQ)
reinterpret_cast<PxSweepHit&>(hit).normal = -mInput.getDir();
// start out with hitType for this cached shape set to a pre-filtered hit type
PxQueryHitType::Enum hitType = shapeHitType;
// run the post-filter if specified in filterFlags and filterCall is non-NULL
if(!isCached && mFilterCall && (filterFlags & PxQueryFlag::ePOSTFILTER))
{
//if(mFilterCall)
hitType = mFilterCall->postFilter(mFilterData.data, hit, hit.shape, hit.actor);
}
// early out on any hit if eANY_HIT was specified, regardless of hit type
if(mAnyHit && hitType != PxQueryHitType::eNONE)
{
// block or touch qualifies for qType=ANY type hit => return it as blocking according to spec. Ignore eNONE.
//mHitCall.block = hit;
copy(&mHitCall.block, &hit);
mHitCall.hasBlock = true;
return false; // found a hit for ANY qType, can early exit now
}
if(mNoBlock && hitType==PxQueryHitType::eBLOCK)
hitType = PxQueryHitType::eTOUCH;
PX_WARN_ONCE_IF(HitTypeSupport<HitType>::IsOverlap && hitType == PxQueryHitType::eBLOCK,
"eBLOCK returned from user filter for overlap() query. This may cause undesired behavior. "
"Consider using PxQueryFlag::eNO_BLOCK for overlap queries.");
if(hitType == PxQueryHitType::eTOUCH)
{
if(!processTouchHit(hit, aDist))
return false;
} // if(hitType == PxQueryHitType::eTOUCH)
else if(hitType == PxQueryHitType::eBLOCK)
{
// -------------------------- handle eBLOCK hits ----------------------------------
// only eBLOCK qualifies as a closest hit candidate => compare against best distance and store
// <= is needed for eTOUCH hits to be recorded correctly vs same eBLOCK distance for overlaps
if(HITDIST(hit) <= mShrunkDistance)
{
if(HitTypeSupport<HitType>::IsOverlap == 0)
{
mShrunkDistance = HITDIST(hit);
aDist = mShrunkDistance;
}
//mHitCall.block = hit;
copy(&mHitCall.block, &hit);
mHitCall.hasBlock = true;
}
} // if(hitType == eBLOCK)
else {
PX_ASSERT(hitType == PxQueryHitType::eNONE);
}
} // for iSubHit
return true;
}
virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
return _invoke<false>(aDist, primIndex, payloads, transforms, NULL);
}
virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms)
{
float unused = 0.0f;
return _invoke<false>(unused, primIndex, payloads, transforms, NULL);
}
virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose)
{
return _invoke<false>(aDist, primIndex, payloads, transforms, compoundPose);
}
virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose)
{
float unused = 0.0f;
return _invoke<false>(unused, primIndex, payloads, transforms, compoundPose);
}
private:
ExtMultiQueryCallback<HitType>& operator=(const ExtMultiQueryCallback<HitType>&);
};
//========================================================================================================================
#if PX_SUPPORT_PVD
template<typename HitType>
struct ExtCapturePvdOnReturn : public PxHitCallback<HitType>
{
// copy the arguments of multiQuery into a struct, this is strictly for PVD recording
const ExtSceneQueries* mSQ;
const ExtMultiQueryInput& mInput;
const PxQueryFilterData& mFilterData;
PxArray<HitType> mAllHits;
PxHitCallback<HitType>& mParentCallback;
ExtCapturePvdOnReturn(
const ExtSceneQueries* sq, const ExtMultiQueryInput& input,
const PxQueryFilterData& filterData,
PxHitCallback<HitType>& parentCallback) :
PxHitCallback<HitType> (parentCallback.touches, parentCallback.maxNbTouches),
mSQ (sq),
mInput (input),
mFilterData (filterData),
mParentCallback (parentCallback)
{}
virtual PxAgain processTouches(const HitType* hits, PxU32 nbHits)
{
const PxAgain again = mParentCallback.processTouches(hits, nbHits);
for(PxU32 i=0; i<nbHits; i++)
mAllHits.pushBack(hits[i]);
return again;
}
~ExtCapturePvdOnReturn()
{
ExtPVDCapture* pvd = mSQ->mPVD;
if(!pvd || !pvd->transmitSceneQueries())
return;
if(mParentCallback.nbTouches)
{
for(PxU32 i = 0; i < mParentCallback.nbTouches; i++)
mAllHits.pushBack(mParentCallback.touches[i]);
}
if(mParentCallback.hasBlock)
mAllHits.pushBack(mParentCallback.block);
// PT: TODO: why do we need reinterpret_casts below?
if(HitTypeSupport<HitType>::IsRaycast)
pvd->raycast(mInput.getOrigin(), mInput.getDir(), mInput.maxDistance, reinterpret_cast<PxRaycastHit*>(mAllHits.begin()), mAllHits.size(), mFilterData, this->maxNbTouches!=0);
else if(HitTypeSupport<HitType>::IsOverlap)
pvd->overlap(*mInput.geometry, *mInput.pose, reinterpret_cast<PxOverlapHit*>(mAllHits.begin()), mAllHits.size(), mFilterData);
else if(HitTypeSupport<HitType>::IsSweep)
pvd->sweep (*mInput.geometry, *mInput.pose, mInput.getDir(), mInput.maxDistance, reinterpret_cast<PxSweepHit*>(mAllHits.begin()), mAllHits.size(), mFilterData, this->maxNbTouches!=0);
}
private:
ExtCapturePvdOnReturn<HitType>& operator=(const ExtCapturePvdOnReturn<HitType>&);
};
#endif // PX_SUPPORT_PVD
//========================================================================================================================
template<typename HitType>
struct ExtIssueCallbacksOnReturn
{
PxHitCallback<HitType>& hits;
bool again; // query was stopped by previous processTouches. This means that nbTouches is still non-zero
// but we don't need to issue processTouches again
PX_FORCE_INLINE ExtIssueCallbacksOnReturn(PxHitCallback<HitType>& aHits) : hits(aHits)
{
again = true;
}
~ExtIssueCallbacksOnReturn()
{
if(again)
// only issue processTouches if query wasn't stopped
// this is because nbTouches doesn't get reset to 0 in this case (according to spec)
// and the touches in touches array were already processed by the callback
{
if(hits.hasBlock && hits.nbTouches)
hits.nbTouches = clipHitsToNewMaxDist<HitType>(hits.touches, hits.nbTouches, HITDIST(hits.block));
if(hits.nbTouches)
{
bool again_ = hits.processTouches(hits.touches, hits.nbTouches);
if(again_)
hits.nbTouches = 0;
}
}
hits.finalizeQuery();
}
private:
ExtIssueCallbacksOnReturn<HitType>& operator=(const ExtIssueCallbacksOnReturn<HitType>&);
};
#undef HITDIST
//========================================================================================================================
template<typename HitType>
static bool doQueryVsCached(const PrunerHandle handle, PxU32 prunerIndex, const PrunerCompoundId cachedCompoundId, const ExtPrunerManager& manager, ExtMultiQueryCallback<HitType>& pcb, const ExtMultiQueryInput& input);
static PX_FORCE_INLINE PxCompoundPrunerQueryFlags convertFlags(PxQueryFlags inFlags)
{
PxCompoundPrunerQueryFlags outFlags(0);
if(inFlags.isSet(PxQueryFlag::eSTATIC))
outFlags.raise(PxCompoundPrunerQueryFlag::eSTATIC);
if(inFlags.isSet(PxQueryFlag::eDYNAMIC))
outFlags.raise(PxCompoundPrunerQueryFlag::eDYNAMIC);
return outFlags;
}
// #MODIFIED
static PX_FORCE_INLINE bool prunerFilter(const ExtQueryAdapter& adapter, PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall)
{
// PT: the internal PhysX code can skip an entire pruner by just testing one query flag, since there is a direct
// mapping between the static/dynamic flags and the static/dynamic pruners. This is not the case here anymore,
// so instead we call a user-provided callback to validate processing each pruner.
return adapter.processPruner(prunerIndex, context, filterData, filterCall);
}
//~#MODIFIED
// PT: the following local callbacks are for the "tree of pruners"
template<typename HitType>
struct LocalBaseCallback
{
LocalBaseCallback(ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) :
mPCB (pcb),
mSQManager (manager),
mAdapter (adapter),
mHits (hits),
mFilterData (filterData),
mFilterCall (filterCall)
{}
ExtMultiQueryCallback<HitType>& mPCB;
const Sq::ExtPrunerManager& mSQManager;
const ExtQueryAdapter& mAdapter;
PxHitCallback<HitType>& mHits;
const PxQueryFilterData& mFilterData;
PxQueryFilterCallback* mFilterCall;
PX_FORCE_INLINE const Pruner* filtering(PxU32 prunerIndex)
{
if(!prunerFilter(mAdapter, prunerIndex, &mHits, mFilterData, mFilterCall))
return NULL;
return mSQManager.getPruner(prunerIndex);
}
PX_NOCOPY(LocalBaseCallback)
};
template<typename HitType>
struct LocalRaycastCallback : LocalBaseCallback<HitType>, PxBVH::RaycastCallback
{
LocalRaycastCallback(const ExtMultiQueryInput& input, ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) :
LocalBaseCallback<HitType>(pcb, manager, adapter, hits, filterData, filterCall), mInput(input) {}
virtual bool reportHit(PxU32 boundsIndex, PxReal& distance)
{
const Pruner* pruner = LocalBaseCallback<HitType>::filtering(boundsIndex);
if(!pruner)
return true;
return pruner->raycast(mInput.getOrigin(), mInput.getDir(), distance, this->mPCB);
}
const ExtMultiQueryInput& mInput;
PX_NOCOPY(LocalRaycastCallback)
};
template<typename HitType>
struct LocalOverlapCallback : LocalBaseCallback<HitType>, PxBVH::OverlapCallback
{
LocalOverlapCallback(const ShapeData& shapeData, ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) :
LocalBaseCallback<HitType>(pcb, manager, adapter, hits, filterData, filterCall), mShapeData(shapeData) {}
virtual bool reportHit(PxU32 boundsIndex)
{
const Pruner* pruner = LocalBaseCallback<HitType>::filtering(boundsIndex);
if(!pruner)
return true;
return pruner->overlap(mShapeData, this->mPCB);
}
const ShapeData& mShapeData;
PX_NOCOPY(LocalOverlapCallback)
};
template<typename HitType>
struct LocalSweepCallback : LocalBaseCallback<HitType>, PxBVH::RaycastCallback
{
LocalSweepCallback(const ShapeData& shapeData, const PxVec3& dir, ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) :
LocalBaseCallback<HitType>(pcb, manager, adapter, hits, filterData, filterCall), mShapeData(shapeData), mDir(dir) {}
virtual bool reportHit(PxU32 boundsIndex, PxReal& distance)
{
const Pruner* pruner = LocalBaseCallback<HitType>::filtering(boundsIndex);
if(!pruner)
return true;
return pruner->sweep(mShapeData, mDir, distance, this->mPCB);
}
const ShapeData& mShapeData;
const PxVec3& mDir;
PX_NOCOPY(LocalSweepCallback)
};
// PT: TODO: revisit error messages without breaking UTs
template<typename HitType>
bool ExtSceneQueries::multiQuery(
const ExtMultiQueryInput& input, PxHitCallback<HitType>& hits, PxHitFlags hitFlags, const PxQueryCache* cache,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const
{
const bool anyHit = (filterData.flags & PxQueryFlag::eANY_HIT) == PxQueryFlag::eANY_HIT;
if(HitTypeSupport<HitType>::IsRaycast == 0)
{
PX_CHECK_AND_RETURN_VAL(input.pose != NULL, "NpSceneQueries::overlap/sweep pose is NULL.", 0);
PX_CHECK_AND_RETURN_VAL(input.pose->isValid(), "NpSceneQueries::overlap/sweep pose is not valid.", 0);
}
else
{
PX_CHECK_AND_RETURN_VAL(input.getOrigin().isFinite(), "NpSceneQueries::raycast pose is not valid.", 0);
}
if(HitTypeSupport<HitType>::IsOverlap == 0)
{
PX_CHECK_AND_RETURN_VAL(input.getDir().isFinite(), "NpSceneQueries multiQuery input check: unitDir is not valid.", 0);
PX_CHECK_AND_RETURN_VAL(input.getDir().isNormalized(), "NpSceneQueries multiQuery input check: direction must be normalized", 0);
}
if(HitTypeSupport<HitType>::IsRaycast)
{
PX_CHECK_AND_RETURN_VAL(input.maxDistance > 0.0f, "NpSceneQueries::multiQuery input check: distance cannot be negative or zero", 0);
}
if(HitTypeSupport<HitType>::IsOverlap && !anyHit)
{
PX_CHECK_AND_RETURN_VAL(hits.maxNbTouches > 0, "PxScene::overlap() calls without eANY_HIT flag require a touch hit buffer for return results.", 0);
}
if(HitTypeSupport<HitType>::IsSweep)
{
PX_CHECK_AND_RETURN_VAL(input.maxDistance >= 0.0f, "NpSceneQueries multiQuery input check: distance cannot be negative", 0);
PX_CHECK_AND_RETURN_VAL(input.maxDistance != 0.0f || !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP),
"NpSceneQueries multiQuery input check: zero-length sweep only valid without the PxHitFlag::eASSUME_NO_INITIAL_OVERLAP flag", 0);
}
PX_CHECK_MSG(!cache || (cache && cache->shape && cache->actor), "Raycast cache specified but shape or actor pointer is NULL!");
PrunerCompoundId cachedCompoundId = INVALID_COMPOUND_ID;
// PT: this is similar to the code in the SqRefFinder so we could share that code maybe. But here we later retrieve the payload from the PrunerData,
// i.e. we basically go back to the same pointers we started from. I suppose it's to make sure they get properly invalidated when an object is deleted etc,
// but we could still probably find a more efficient way to do that here. Isn't it exactly why we had the Signature class initially?
//
// how can this work anyway? if the actor has been deleted the lookup won't work either => doc says it's up to users to manage that....
const ExtQueryAdapter& adapter = static_cast<const ExtQueryAdapter&>(mSQManager.getAdapter());
PxU32 prunerIndex = 0xffffffff;
const PrunerHandle cacheData = cache ? adapter.findPrunerHandle(*cache, cachedCompoundId, prunerIndex) : INVALID_PRUNERHANDLE;
// this function is logically const for the SDK user, as flushUpdates() will not have an API-visible effect on this object
// internally however, flushUpdates() changes the states of the Pruners in mSQManager
// because here is the only place we need this, const_cast instead of making SQM mutable
const_cast<ExtSceneQueries*>(this)->mSQManager.flushUpdates();
#if PX_SUPPORT_PVD
ExtCapturePvdOnReturn<HitType> pvdCapture(this, input, filterData, hits);
#endif
ExtIssueCallbacksOnReturn<HitType> cbr(hits); // destructor will execute callbacks on return from this function
hits.hasBlock = false;
hits.nbTouches = 0;
PxReal shrunkDistance = HitTypeSupport<HitType>::IsOverlap ? PX_MAX_REAL : input.maxDistance; // can be progressively shrunk as we go over the list of shapes
if(HitTypeSupport<HitType>::IsSweep)
shrunkDistance = PxMin(shrunkDistance, PX_MAX_SWEEP_DISTANCE);
ExtMultiQueryCallback<HitType> pcb(*this, input, anyHit, hits, hitFlags, filterData, filterCall, shrunkDistance);
if(cacheData!=INVALID_PRUNERHANDLE && hits.maxNbTouches == 0) // don't use cache for queries that can return touch hits
{
if(!doQueryVsCached(cacheData, prunerIndex, cachedCompoundId, mSQManager, pcb, input))
return hits.hasAnyHits();
}
const PxU32 nbPruners = mSQManager.getNbPruners();
const CompoundPruner* compoundPruner = mSQManager.getCompoundPruner();
const PxCompoundPrunerQueryFlags compoundPrunerQueryFlags = convertFlags(filterData.flags);
const BVH* treeOfPruners = mSQManager.getTreeOfPruners();
if(HitTypeSupport<HitType>::IsRaycast)
{
// #MODIFIED
bool again = true;
if(treeOfPruners)
{
LocalRaycastCallback<HitType> prunerRaycastCB(input, pcb, mSQManager, adapter, hits, filterData, filterCall);
again = treeOfPruners->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, prunerRaycastCB, PxGeometryQueryFlag::Enum(0));
if(!again)
{
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
else
{
for(PxU32 i=0;i<nbPruners;i++)
{
if(prunerFilter(adapter, i, &hits, filterData, filterCall))
{
const Pruner* pruner = mSQManager.getPruner(i);
again = pruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb);
if(!again)
{
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
}
}
//~#MODIFIED
if(again && compoundPruner)
again = compoundPruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb, compoundPrunerQueryFlags);
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
else if(HitTypeSupport<HitType>::IsOverlap)
{
PX_ASSERT(input.geometry);
const ShapeData sd(*input.geometry, *input.pose, input.inflation);
pcb.mShapeData = &sd;
// #MODIFIED
bool again = true;
if(treeOfPruners)
{
LocalOverlapCallback<HitType> prunerOverlapCB(sd, pcb, mSQManager, adapter, hits, filterData, filterCall);
again = treeOfPruners->overlap(*input.geometry, *input.pose, prunerOverlapCB, PxGeometryQueryFlag::Enum(0));
if(!again)
{
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
else
{
for(PxU32 i=0;i<nbPruners;i++)
{
if(prunerFilter(adapter, i, &hits, filterData, filterCall))
{
const Pruner* pruner = mSQManager.getPruner(i);
again = pruner->overlap(sd, pcb);
if(!again)
{
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
}
}
//~#MODIFIED
if(again && compoundPruner)
again = compoundPruner->overlap(sd, pcb, compoundPrunerQueryFlags);
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
else
{
PX_ASSERT(HitTypeSupport<HitType>::IsSweep);
PX_ASSERT(input.geometry);
const ShapeData sd(*input.geometry, *input.pose, input.inflation);
pcb.mQueryShapeBounds = &sd.getPrunerInflatedWorldAABB();
pcb.mShapeData = &sd;
// #MODIFIED
bool again = true;
if(treeOfPruners)
{
LocalSweepCallback<HitType> prunerSweepCB(sd, input.getDir(), pcb, mSQManager, adapter, hits, filterData, filterCall);
again = treeOfPruners->sweep(*input.geometry, *input.pose, input.getDir(), pcb.mShrunkDistance, prunerSweepCB, PxGeometryQueryFlag::Enum(0));
if(!again)
{
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
else
{
for(PxU32 i=0;i<nbPruners;i++)
{
if(prunerFilter(adapter, i, &hits, filterData, filterCall))
{
const Pruner* pruner = mSQManager.getPruner(i);
again = pruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb);
if(!again)
{
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
}
}
//~#MODIFIED
if(again && compoundPruner)
again = compoundPruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb, compoundPrunerQueryFlags);
cbr.again = again; // update the status to avoid duplicate processTouches()
return hits.hasAnyHits();
}
}
//explicit template instantiation
template bool ExtSceneQueries::multiQuery<PxRaycastHit>(const ExtMultiQueryInput&, PxHitCallback<PxRaycastHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const;
template bool ExtSceneQueries::multiQuery<PxOverlapHit>(const ExtMultiQueryInput&, PxHitCallback<PxOverlapHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const;
template bool ExtSceneQueries::multiQuery<PxSweepHit>(const ExtMultiQueryInput&, PxHitCallback<PxSweepHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const;
///////////////////////////////////////////////////////////////////////////////
bool ExtSceneQueries::_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
{
PX_PROFILE_ZONE("SceneQuery.raycast", getContextId());
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
ExtMultiQueryInput input(origin, unitDir, distance);
return multiQuery<PxRaycastHit>(input, hits, hitFlags, cache, filterData, filterCall);
}
//////////////////////////////////////////////////////////////////////////
bool ExtSceneQueries::_overlap(
const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hits,
const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall,
const PxQueryCache* cache, PxGeometryQueryFlags flags) const
{
PX_PROFILE_ZONE("SceneQuery.overlap", getContextId());
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
ExtMultiQueryInput input(&geometry, &pose);
return multiQuery<PxOverlapHit>(input, hits, PxHitFlags(), cache, filterData, filterCall);
}
///////////////////////////////////////////////////////////////////////////////
bool ExtSceneQueries::_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
{
PX_PROFILE_ZONE("SceneQuery.sweep", getContextId());
PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD)
#if PX_CHECKED
if(!PxGeometryQuery::isValid(geometry))
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Provided geometry is not valid");
#endif
if((hitFlags & PxHitFlag::ePRECISE_SWEEP) && (hitFlags & PxHitFlag::eMTD))
{
outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " Precise sweep doesn't support MTD. Perform MTD with default sweep");
hitFlags &= ~PxHitFlag::ePRECISE_SWEEP;
}
if((hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP) && (hitFlags & PxHitFlag::eMTD))
{
outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " eMTD cannot be used in conjunction with eASSUME_NO_INITIAL_OVERLAP. eASSUME_NO_INITIAL_OVERLAP will be ignored");
hitFlags &= ~PxHitFlag::eASSUME_NO_INITIAL_OVERLAP;
}
PxReal realInflation = inflation;
if((hitFlags & PxHitFlag::ePRECISE_SWEEP)&& inflation > 0.f)
{
realInflation = 0.f;
outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " Precise sweep doesn't support inflation, inflation will be overwritten to be zero");
}
ExtMultiQueryInput input(&geometry, &pose, unitDir, distance, realInflation);
return multiQuery<PxSweepHit>(input, hits, hitFlags, cache, filterData, filterCall);
}
///////////////////////////////////////////////////////////////////////////////
template<typename HitType>
static bool doQueryVsCached(const PrunerHandle handle, PxU32 prunerIndex, const PrunerCompoundId cachedCompoundId, const ExtPrunerManager& manager, ExtMultiQueryCallback<HitType>& pcb, const ExtMultiQueryInput& input)
{
// this block is only executed for single shape cache
const PrunerPayload* payloads;
const PxTransform* compoundPosePtr;
PxTransform* transform;
PxTransform compoundPose;
if(cachedCompoundId == INVALID_COMPOUND_ID)
{
const Pruner* pruner = manager.getPruner(PruningIndex::Enum(prunerIndex));
PX_ASSERT(pruner);
PrunerPayloadData ppd;
const PrunerPayload& cachedPayload = pruner->getPayloadData(handle, &ppd);
payloads = &cachedPayload;
compoundPosePtr = NULL;
transform = ppd.mTransform;
}
else
{
const CompoundPruner* pruner = manager.getCompoundPruner();
PX_ASSERT(pruner);
PrunerPayloadData ppd;
const PrunerPayload& cachedPayload = pruner->getPayloadData(handle, cachedCompoundId, &ppd);
compoundPose = pruner->getTransform(cachedCompoundId);
payloads = &cachedPayload;
compoundPosePtr = &compoundPose;
transform = ppd.mTransform;
}
PxReal dummyDist;
bool againAfterCache;
if(HitTypeSupport<HitType>::IsSweep)
{
// AP: for sweeps we cache the bounds because we need to know them for the test to clip the sweep to bounds
// otherwise GJK becomes unstable. The bounds can be used multiple times so this is an optimization.
const ShapeData sd(*input.geometry, *input.pose, input.inflation);
pcb.mQueryShapeBounds = &sd.getPrunerInflatedWorldAABB();
pcb.mShapeData = &sd;
// againAfterCache = pcb.invoke(dummyDist, 0);
againAfterCache = pcb.template _invoke<true>(dummyDist, 0, payloads, transform, compoundPosePtr);
pcb.mQueryShapeBounds = NULL;
pcb.mShapeData = NULL;
} else
// againAfterCache = pcb.invoke(dummyDist, 0);
againAfterCache = pcb.template _invoke<true>(dummyDist, 0, payloads, transform, compoundPosePtr);
return againAfterCache;
}
///////////////////////////////////////////////////////////////////////////////
ExtSceneQueries::ExtSceneQueries(ExtPVDCapture* pvd, PxU64 contextID, float inflation, const ExtQueryAdapter& adapter, bool usesTreeOfPruners) :
mSQManager (contextID, inflation, adapter, usesTreeOfPruners),
mPVD (pvd)
{
}
ExtSceneQueries::~ExtSceneQueries()
{
}
| 50,766 | C++ | 40.04042 | 276 | 0.723713 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtJointData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_JOINT_DATA_H
#define EXT_JOINT_DATA_H
#include "extensions/PxJointLimit.h"
namespace physx
{
namespace Ext
{
struct JointData
{
PxConstraintInvMassScale invMassScale;
PxTransform32 c2b[2];
protected:
~JointData() {}
};
} // namespace Ext
}
#endif
| 1,986 | C | 38.739999 | 74 | 0.75428 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCustomGeometryExt.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 "extensions/PxCustomGeometryExt.h"
#include <geometry/PxGeometryHelpers.h>
#include <geometry/PxGeometryQuery.h>
#include <geometry/PxMeshQuery.h>
#include <geometry/PxTriangle.h>
#include <geometry/PxTriangleMesh.h>
#include <geometry/PxTriangleMeshGeometry.h>
#include <geomutils/PxContactBuffer.h>
#include <common/PxRenderOutput.h>
#include <extensions/PxGjkQueryExt.h>
#include <extensions/PxMassProperties.h>
#include <PxImmediateMode.h>
#include "omnipvd/ExtOmniPvdSetData.h"
using namespace physx;
#if PX_SUPPORT_OMNI_PVD
using namespace Ext;
#endif
static const PxU32 gCollisionShapeColor = PxU32(PxDebugColor::eARGB_MAGENTA);
///////////////////////////////////////////////////////////////////////////////
static const PxU32 MAX_TRIANGLES = 512;
static const PxU32 MAX_TRIANGLE_CONTACTS = 6;
const PxReal FACE_CONTACT_THRESHOLD = 0.99999f;
struct TrimeshContactFilter
{
PxU32 triCount;
PxU32 triIndices[MAX_TRIANGLES];
PxU32 triAdjacencies[MAX_TRIANGLES][3];
PxU32 triContactCounts[MAX_TRIANGLES][2];
PxContactPoint triContacts[MAX_TRIANGLES][MAX_TRIANGLE_CONTACTS];
TrimeshContactFilter() : triCount(0) {}
void addTriangleContacts(const PxContactPoint* points, PxU32 count, const PxU32 triIndex, const PxVec3 triVerts[3], const PxU32 triAdjacency[3])
{
if (triCount == MAX_TRIANGLES)
return;
triIndices[triCount] = triIndex;
PxU32& faceContactCount = triContactCounts[triCount][0];
PxU32& edgeContactCount = triContactCounts[triCount][1];
faceContactCount = edgeContactCount = 0;
for (PxU32 i = 0; i < 3; ++i)
triAdjacencies[triCount][i] = triAdjacency[i];
PxVec3 triNormal = (triVerts[1] - triVerts[0]).cross(triVerts[2] - triVerts[0]).getNormalized();
for (PxU32 i = 0; i < count; ++i)
{
const PxContactPoint& point = points[i];
bool faceContact = fabsf(point.normal.dot(triNormal)) > FACE_CONTACT_THRESHOLD;
if (faceContactCount + edgeContactCount < MAX_TRIANGLE_CONTACTS)
{
if (faceContact) triContacts[triCount][faceContactCount++] = point;
else triContacts[triCount][MAX_TRIANGLE_CONTACTS - 1 - edgeContactCount++] = point;
}
}
++triCount;
}
void writeToBuffer(PxContactBuffer& buffer)
{
for (PxU32 i = 0; i < triCount; ++i)
{
if (triContactCounts[i][1] > 0)
{
for (PxU32 j = 0; j < triCount; ++j)
{
if (triIndices[j] == triAdjacencies[i][0] || triIndices[j] == triAdjacencies[i][1] || triIndices[j] == triAdjacencies[i][2])
{
if (triContactCounts[j][0] > 0)
{
triContactCounts[i][1] = 0;
break;
}
}
}
}
for (PxU32 j = 0; j < triContactCounts[i][0]; ++j)
buffer.contact(triContacts[i][j]);
for (PxU32 j = 0; j < triContactCounts[i][1]; ++j)
buffer.contact(triContacts[i][MAX_TRIANGLE_CONTACTS - 1 - j]);
}
}
PX_NOCOPY(TrimeshContactFilter)
};
///////////////////////////////////////////////////////////////////////////////
struct TriangleSupport : PxGjkQuery::Support
{
PxVec3 v0, v1, v2;
PxReal margin;
TriangleSupport(const PxVec3& _v0, const PxVec3& _v1, const PxVec3& _v2, PxReal _margin)
:
v0(_v0), v1(_v1), v2(_v2), margin(_margin)
{}
virtual PxReal getMargin() const
{
return margin;
}
virtual PxVec3 supportLocal(const PxVec3& dir) const
{
float d0 = dir.dot(v0), d1 = dir.dot(v1), d2 = dir.dot(v2);
return (d0 > d1 && d0 > d2) ? v0 : (d1 > d2) ? v1 : v2;
}
};
///////////////////////////////////////////////////////////////////////////////
static void drawArc(const PxVec3& center, const PxVec3& radius, const PxVec3& axis, PxReal angle, PxReal error, PxRenderOutput& out)
{
int sides = int(ceilf(angle / (2 * acosf(1.0f - error))));
float step = angle / sides;
out << PxRenderOutput::LINESTRIP;
for (int i = 0; i <= sides; ++i)
out << center + PxQuat(step * i, axis).rotate(radius);
}
static void drawCircle(const PxVec3& center, const PxVec3& radius, const PxVec3& axis, PxReal error, PxRenderOutput& out)
{
drawArc(center, radius, axis, PxTwoPi, error, out);
}
static void drawQuarterCircle(const PxVec3& center, const PxVec3& radius, const PxVec3& axis, PxReal error, PxRenderOutput& out)
{
drawArc(center, radius, axis, PxPiDivTwo, error, out);
}
static void drawLine(const PxVec3& s, const PxVec3& e, PxRenderOutput& out)
{
out << PxRenderOutput::LINES << s << e;
}
///////////////////////////////////////////////////////////////////////////////
PxBounds3 PxCustomGeometryExt::BaseConvexCallbacks::getLocalBounds(const PxGeometry&) const
{
const PxVec3 min(supportLocal(PxVec3(-1, 0, 0)).x, supportLocal(PxVec3(0, -1, 0)).y, supportLocal(PxVec3(0, 0, -1)).z);
const PxVec3 max(supportLocal(PxVec3(1, 0, 0)).x, supportLocal(PxVec3(0, 1, 0)).y, supportLocal(PxVec3(0, 0, 1)).z);
PxBounds3 bounds(min, max);
bounds.fattenSafe(getMargin());
return bounds;
}
bool PxCustomGeometryExt::BaseConvexCallbacks::generateContacts(const PxGeometry& geom0, const PxGeometry& geom1,
const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin,
const PxReal toleranceLength, PxContactBuffer& contactBuffer) const
{
struct ContactRecorder : immediate::PxContactRecorder
{
PxContactBuffer* contactBuffer;
ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {}
virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/)
{
for (PxU32 i = 0; i < nbContacts; ++i)
contactBuffer->contact(contactPoints[i]);
return true;
}
}
contactRecorder(contactBuffer);
PxCache contactCache;
struct ContactCacheAllocator : PxCacheAllocator
{
PxU8 buffer[1024];
ContactCacheAllocator() { PxMemSet(buffer, 0, sizeof(buffer)); }
virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return reinterpret_cast<PxU8*>(size_t(buffer + 0xf) & ~0xf); }
}
contactCacheAllocator;
const PxTransform identityPose(PxIdentity);
switch (geom1.getType())
{
case PxGeometryType::eSPHERE:
case PxGeometryType::eCAPSULE:
case PxGeometryType::eBOX:
case PxGeometryType::eCONVEXMESH:
{
PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1);
if (PxGjkQueryExt::generateContacts(*this, geomSupport, pose0, pose1, contactDistance, toleranceLength, contactBuffer))
{
PxGeometryHolder substituteGeom; PxTransform preTransform;
if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0))
{
contactBuffer.count--;
const PxGeometry* pGeom0 = &substituteGeom.any();
const PxGeometry* pGeom1 = &geom1;
// PT:: tag: scalar transform*transform
PxTransform pose = pose0.transform(preTransform);
immediate::PxGenerateContacts(&pGeom0, &pGeom1, &pose, &pose1, &contactCache, 1, contactRecorder,
contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator);
}
}
break;
}
case PxGeometryType::ePLANE:
{
const PxPlane plane = PxPlane(1.0f, 0.0f, 0.0f, 0.0f).transform(pose1);
const PxPlane localPlane = plane.inverseTransform(pose0);
const PxVec3 point = supportLocal(-localPlane.n) - localPlane.n * margin;
const float dist = localPlane.distance(point);
if (dist < contactDistance)
{
const PxVec3 n = localPlane.n;
const PxVec3 p = point - n * dist * 0.5f;
PxContactPoint contact;
contact.point = pose0.transform(p);
contact.normal = pose0.rotate(n);
contact.separation = dist;
contactBuffer.contact(contact);
PxGeometryHolder substituteGeom; PxTransform preTransform;
if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0))
{
contactBuffer.count--;
const PxGeometry* pGeom0 = &substituteGeom.any();
const PxGeometry* pGeom1 = &geom1;
// PT:: tag: scalar transform*transform
PxTransform pose = pose0.transform(preTransform);
immediate::PxGenerateContacts(&pGeom0, &pGeom1, &pose, &pose1, &contactCache, 1, contactRecorder,
contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator);
}
}
break;
}
case PxGeometryType::eTRIANGLEMESH:
case PxGeometryType::eHEIGHTFIELD:
{
// As a triangle has no thickness, we need to choose some collision margin - the distance
// considered a touching contact. I set it as 1% of the custom shape minimum dimension.
PxReal meshMargin = getLocalBounds(geom0).getDimensions().minElement() * 0.01f;
TrimeshContactFilter contactFilter;
bool hasAdjacency = (geom1.getType() != PxGeometryType::eTRIANGLEMESH || (static_cast<const PxTriangleMeshGeometry&>(geom1).triangleMesh->getTriangleMeshFlags() & PxTriangleMeshFlag::eADJACENCY_INFO));
PxBoxGeometry boxGeom(getLocalBounds(geom0).getExtents() + PxVec3(contactDistance + meshMargin));
PxU32 triangles[MAX_TRIANGLES];
bool overflow = false;
PxU32 triangleCount = (geom1.getType() == PxGeometryType::eTRIANGLEMESH) ?
PxMeshQuery::findOverlapTriangleMesh(boxGeom, pose0, static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow) :
PxMeshQuery::findOverlapHeightField(boxGeom, pose0, static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow);
if (overflow)
PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "PxCustomGeometryExt::BaseConvexCallbacks::generateContacts() Too many triangles.\n");
for (PxU32 i = 0; i < triangleCount; ++i)
{
PxTriangle tri; PxU32 adjacent[3];
if (geom1.getType() == PxGeometryType::eTRIANGLEMESH)
PxMeshQuery::getTriangle(static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles[i], tri, NULL, hasAdjacency ? adjacent : NULL);
else
PxMeshQuery::getTriangle(static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles[i], tri, NULL, adjacent);
TriangleSupport triSupport(tri.verts[0], tri.verts[1], tri.verts[2], meshMargin);
if (PxGjkQueryExt::generateContacts(*this, triSupport, pose0, identityPose, contactDistance, toleranceLength, contactBuffer))
{
contactBuffer.contacts[contactBuffer.count - 1].internalFaceIndex1 = triangles[i];
PxGeometryHolder substituteGeom; PxTransform preTransform;
if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0))
{
contactBuffer.count--;
const PxGeometry& geom = substituteGeom.any();
// PT:: tag: scalar transform*transform
PxTransform pose = pose0.transform(preTransform);
PxGeometryQuery::generateTriangleContacts(geom, pose, tri.verts, triangles[i], contactDistance, meshMargin, toleranceLength, contactBuffer);
}
}
if (hasAdjacency)
{
contactFilter.addTriangleContacts(contactBuffer.contacts, contactBuffer.count, triangles[i], tri.verts, adjacent);
contactBuffer.count = 0;
}
}
if (hasAdjacency)
contactFilter.writeToBuffer(contactBuffer);
break;
}
case PxGeometryType::eCUSTOM:
{
const PxCustomGeometry& customGeom1 = static_cast<const PxCustomGeometry&>(geom1);
if (customGeom1.getCustomType() == CylinderCallbacks::TYPE() ||
customGeom1.getCustomType() == ConeCallbacks::TYPE()) // It's a CustomConvex
{
BaseConvexCallbacks* custom1 = static_cast<BaseConvexCallbacks*>(customGeom1.callbacks);
if (PxGjkQueryExt::generateContacts(*this, *custom1, pose0, pose1, contactDistance, toleranceLength, contactBuffer))
{
PxGeometryHolder substituteGeom; PxTransform preTransform;
if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0))
{
contactBuffer.count--;
PxU32 oldCount = contactBuffer.count;
const PxGeometry* pGeom0 = &substituteGeom.any();
const PxGeometry* pGeom1 = &geom1;
// PT:: tag: scalar transform*transform
PxTransform pose = pose0.transform(preTransform);
immediate::PxGenerateContacts(&pGeom1, &pGeom0, &pose1, &pose, &contactCache, 1, contactRecorder,
contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator);
for (int i = oldCount; i < int(contactBuffer.count); ++i)
contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal;
}
}
}
else
{
const PxGeometry* pGeom0 = &geom0;
const PxGeometry* pGeom1 = &geom1;
immediate::PxGenerateContacts(&pGeom1, &pGeom0, &pose1, &pose0, &contactCache, 1, contactRecorder,
contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator);
for (int i = 0; i < int(contactBuffer.count); ++i)
contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal;
}
break;
}
default:
break;
}
return contactBuffer.count > 0;
}
PxU32 PxCustomGeometryExt::BaseConvexCallbacks::raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose,
PxReal maxDist, PxHitFlags /*hitFlags*/, PxU32 /*maxHits*/, PxGeomRaycastHit* rayHits, PxU32 /*stride*/, PxRaycastThreadContext*) const
{
// When FLT_MAX is used as maxDist, it works bad with GJK algorithm.
// Here I compute the maximum needed distance (wiseDist) as the diagonal
// of the bounding box of both the geometry and the ray origin.
PxBounds3 bounds = PxBounds3::transformFast(pose, getLocalBounds(geom));
bounds.include(origin);
PxReal wiseDist = PxMin(maxDist, bounds.getDimensions().magnitude());
PxReal t;
PxVec3 n, p;
if (PxGjkQuery::raycast(*this, pose, origin, unitDir, wiseDist, t, n, p))
{
PxGeomRaycastHit& hit = *rayHits;
hit.distance = t;
hit.position = p;
hit.normal = n;
return 1;
}
return 0;
}
bool PxCustomGeometryExt::BaseConvexCallbacks::overlap(const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const
{
switch (geom1.getType())
{
case PxGeometryType::eSPHERE:
case PxGeometryType::eCAPSULE:
case PxGeometryType::eBOX:
case PxGeometryType::eCONVEXMESH:
{
PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1);
if (PxGjkQuery::overlap(*this, geomSupport, pose0, pose1))
return true;
break;
}
default:
break;
}
return false;
}
bool PxCustomGeometryExt::BaseConvexCallbacks::sweep(const PxVec3& unitDir, const PxReal maxDist,
const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1,
PxGeomSweepHit& sweepHit, PxHitFlags /*hitFlags*/, const PxReal inflation, PxSweepThreadContext*) const
{
PxBounds3 bounds0 = PxBounds3::transformFast(pose0, getLocalBounds(geom0));
switch (geom1.getType())
{
case PxGeometryType::eSPHERE:
case PxGeometryType::eCAPSULE:
case PxGeometryType::eBOX:
case PxGeometryType::eCONVEXMESH:
{
// See comment in BaseConvexCallbacks::raycast
PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom1, pose1, 0, inflation);
bounds.include(bounds0);
PxReal wiseDist = PxMin(maxDist, bounds.getDimensions().magnitude());
PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1, inflation);
PxReal t;
PxVec3 n, p;
if (PxGjkQuery::sweep(*this, geomSupport, pose0, pose1, unitDir, wiseDist, t, n, p))
{
sweepHit.distance = t;
sweepHit.position = p;
sweepHit.normal = n;
sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL;
return true;
}
break;
}
// sweep against triangle meshes and height fields for CCD support
case PxGeometryType::eTRIANGLEMESH:
case PxGeometryType::eHEIGHTFIELD:
{
PxReal radius = getLocalBounds(geom0).getExtents().magnitude();
PxGeometryHolder sweepGeom = PxSphereGeometry(radius + inflation);
PxTransform sweepGeomPose = pose0;
if (maxDist > FLT_EPSILON)
{
sweepGeom = PxCapsuleGeometry(radius + inflation, maxDist * 0.5f);
sweepGeomPose = PxTransform(pose0.p - unitDir * maxDist * 0.5f, PxShortestRotation(PxVec3(1, 0, 0), unitDir));
}
PxU32 triangles[MAX_TRIANGLES];
bool overflow = false;
PxU32 triangleCount = (geom1.getType() == PxGeometryType::eTRIANGLEMESH) ?
PxMeshQuery::findOverlapTriangleMesh(sweepGeom.any(), sweepGeomPose, static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow) :
PxMeshQuery::findOverlapHeightField(sweepGeom.any(), sweepGeomPose, static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow);
if(overflow)
PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "PxCustomGeometryExt::BaseConvexCallbacks::sweep() Too many triangles.\n");
sweepHit.distance = PX_MAX_F32;
const PxTransform identityPose(PxIdentity);
for (PxU32 i = 0; i < triangleCount; ++i)
{
PxTriangle tri;
if (geom1.getType() == PxGeometryType::eTRIANGLEMESH)
PxMeshQuery::getTriangle(static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles[i], tri);
else
PxMeshQuery::getTriangle(static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles[i], tri);
TriangleSupport triSupport(tri.verts[0], tri.verts[1], tri.verts[2], inflation);
PxBounds3 bounds = bounds0;
for (PxU32 j = 0; j < 3; ++j)
bounds.include(tri.verts[j]);
bounds.fattenFast(inflation);
// See comment in BaseConvexCallbacks::raycast
PxReal wiseDist = PxMin(maxDist, bounds.getDimensions().magnitude());
PxReal t;
PxVec3 n, p;
if (PxGjkQuery::sweep(*this, triSupport, pose0, identityPose, unitDir, wiseDist, t, n, p))
{
if (sweepHit.distance > t)
{
sweepHit.faceIndex = triangles[i];
sweepHit.distance = t;
sweepHit.position = p;
sweepHit.normal = n;
sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX;
}
}
}
if (sweepHit.distance < PX_MAX_F32)
return true;
break;
}
default:
break;
}
return false;
}
bool PxCustomGeometryExt::BaseConvexCallbacks::usePersistentContactManifold(const PxGeometry& /*geometry*/, PxReal& breakingThreshold) const
{
// Even if we don't use persistent manifold, we still need to set proper breakingThreshold
// because the other geometry still can force the PCM usage. FLT_EPSILON ensures that
// the contacts will be discarded and recomputed every frame if actor moves.
breakingThreshold = FLT_EPSILON;
return false;
}
void PxCustomGeometryExt::BaseConvexCallbacks::setMargin(float m)
{
margin = m;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtBaseConvexCallbacks, margin, *this, margin);
#endif
}
///////////////////////////////////////////////////////////////////////////////
IMPLEMENT_CUSTOM_GEOMETRY_TYPE(PxCustomGeometryExt::CylinderCallbacks)
PxCustomGeometryExt::CylinderCallbacks::CylinderCallbacks(float _height, float _radius, int _axis, float _margin)
:
BaseConvexCallbacks(_margin), height(_height), radius(_radius), axis(_axis)
{
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, *this);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtBaseConvexCallbacks, margin, *static_cast<BaseConvexCallbacks*>(this), margin);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, height, *this, height);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, radius, *this, radius);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, axis, *this, axis);
OMNI_PVD_WRITE_SCOPE_END
#endif
}
void PxCustomGeometryExt::CylinderCallbacks::setHeight(float h)
{
height = h;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, height, *this, height);
#endif
}
void PxCustomGeometryExt::CylinderCallbacks::setRadius(float r)
{
radius = r;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, radius, *this, radius);
#endif
}
void PxCustomGeometryExt::CylinderCallbacks::setAxis(int a)
{
axis = a;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, axis, *this, axis);
#endif
}
void PxCustomGeometryExt::CylinderCallbacks::visualize(const PxGeometry&, PxRenderOutput& out, const PxTransform& transform, const PxBounds3&) const
{
const float ERR = 0.001f;
out << gCollisionShapeColor;
out << transform;
int axis1 = (axis + 1) % 3;
int axis2 = (axis + 2) % 3;
PxVec3 zr(PxZero), rd(PxZero), ax(PxZero), ax1(PxZero), ax2(PxZero), r0(PxZero), r1(PxZero);
ax[axis] = ax1[axis1] = ax2[axis2] = 1.0f;
r0[axis1] = r1[axis2] = radius;
rd[axis1] = radius;
rd[axis] = -(height * 0.5f + margin);
drawCircle(zr, rd, ax, ERR, out);
rd[axis] = (height * 0.5f + margin);
drawCircle(zr, rd, ax, ERR, out);
rd[axis1] = radius + margin;
rd[axis] = -(height * 0.5f);
drawCircle(zr, rd, ax, ERR, out);
rd[axis] = (height * 0.5f);
drawCircle(zr, rd, ax, ERR, out);
drawLine(-ax * height * 0.5f + ax1 * (radius + margin), ax * height * 0.5f + ax1 * (radius + margin), out);
drawLine(-ax * height * 0.5f - ax1 * (radius + margin), ax * height * 0.5f - ax1 * (radius + margin), out);
drawLine(-ax * height * 0.5f + ax2 * (radius + margin), ax * height * 0.5f + ax2 * (radius + margin), out);
drawLine(-ax * height * 0.5f - ax2 * (radius + margin), ax * height * 0.5f - ax2 * (radius + margin), out);
drawQuarterCircle(-ax * height * 0.5f + ax1 * radius, -ax * margin, -ax2, ERR, out);
drawQuarterCircle(-ax * height * 0.5f - ax1 * radius, -ax * margin, ax2, ERR, out);
drawQuarterCircle(-ax * height * 0.5f + ax2 * radius, -ax * margin, ax1, ERR, out);
drawQuarterCircle(-ax * height * 0.5f - ax2 * radius, -ax * margin, -ax1, ERR, out);
drawQuarterCircle(ax * height * 0.5f + ax1 * radius, ax * margin, ax2, ERR, out);
drawQuarterCircle(ax * height * 0.5f - ax1 * radius, ax * margin, -ax2, ERR, out);
drawQuarterCircle(ax * height * 0.5f + ax2 * radius, ax * margin, -ax1, ERR, out);
drawQuarterCircle(ax * height * 0.5f - ax2 * radius, ax * margin, ax1, ERR, out);
}
PxVec3 PxCustomGeometryExt::CylinderCallbacks::supportLocal(const PxVec3& dir) const
{
float halfHeight = height * 0.5f;
PxVec3 d = dir.getNormalized();
switch (axis)
{
case 0: // X
{
if (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0);
return PxVec3(PxSign2(d.x) * halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius;
}
case 1: // Y
{
if (PxSign2(d.x) == 0 && PxSign2(d.y) != 0 && PxSign2(d.z) == 0) return PxVec3(0, PxSign2(d.y) * halfHeight, 0);
return PxVec3(0, PxSign2(d.y) * halfHeight, 0) + PxVec3(d.x, 0, d.z).getNormalized() * radius;
}
case 2: // Z
{
if (PxSign2(d.x) == 0 && PxSign2(d.y) == 0 && PxSign2(d.z) != 0) return PxVec3(0, 0, PxSign2(d.z) * halfHeight);
return PxVec3(0, 0, PxSign2(d.z) * halfHeight) + PxVec3(d.x, d.y, 0).getNormalized() * radius;
}
}
return PxVec3(0);
}
void PxCustomGeometryExt::CylinderCallbacks::computeMassProperties(const PxGeometry& /*geometry*/, PxMassProperties& massProperties) const
{
if (margin == 0)
{
PxMassProperties& mass = massProperties;
float R = radius, H = height;
mass.mass = PxPi * R * R * H;
mass.inertiaTensor = PxMat33(PxZero);
mass.centerOfMass = PxVec3(PxZero);
float I0 = mass.mass * R * R / 2.0f;
float I1 = mass.mass * (3 * R * R + H * H) / 12.0f;
mass.inertiaTensor[axis][axis] = I0;
mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1;
}
else
{
const int SLICE_COUNT = 32;
PxMassProperties sliceMasses[SLICE_COUNT];
PxTransform slicePoses[SLICE_COUNT];
float sliceHeight = height / SLICE_COUNT;
for (int i = 0; i < SLICE_COUNT; ++i)
{
float t = -height * 0.5f + i * sliceHeight + sliceHeight * 0.5f;
float R = getRadiusAtHeight(t), H = sliceHeight;
PxMassProperties mass;
mass.mass = PxPi * R * R * H;
mass.inertiaTensor = PxMat33(PxZero);
mass.centerOfMass = PxVec3(PxZero);
float I0 = mass.mass * R * R / 2.0f;
float I1 = mass.mass * (3 * R * R + H * H) / 12.0f;
mass.inertiaTensor[axis][axis] = I0;
mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1;
mass.centerOfMass[axis] = t;
sliceMasses[i] = mass;
slicePoses[i] = PxTransform(PxIdentity);
}
massProperties = PxMassProperties::sum(sliceMasses, slicePoses, SLICE_COUNT);
}
}
bool PxCustomGeometryExt::CylinderCallbacks::useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const
{
// here I check if we contact with the cylender bases or the lateral surface
// where more than 1 contact point can be generated.
PxVec3 locN = pose0.rotateInv(p.normal);
float nAng = acosf(PxClamp(-locN[axis], -1.0f, 1.0f));
float epsAng = PxPi / 36.0f; // 5 degrees
if (nAng < epsAng || nAng > PxPi - epsAng)
{
// if we contact with the bases
// make the substitute geometry a box and rotate it so one of
// the corners matches the contact point
PxVec3 halfSize;
halfSize[axis] = height * 0.5f + margin;
halfSize[(axis + 1) % 3] = halfSize[(axis + 2) % 3] = radius / sqrtf(2.0f);
geom = PxBoxGeometry(halfSize);
PxVec3 axisDir(PxZero); axisDir[axis] = 1.0f;
PxVec3 locP = pose0.transformInv(p.point);
float s1 = locP[(axis + 1) % 3], s2 = locP[(axis + 2) % 3];
float ang = ((s1 * s1) + (s2 * s2) > 1e-3f) ? atan2f(s2, s1) : 0;
preTransform = PxTransform(PxQuat(ang + PxPi * 0.25f, axisDir));
return true;
}
else if (nAng > PxPiDivTwo - epsAng && nAng < PxPiDivTwo + epsAng)
{
// if it's the lateral surface
// make the substitute geometry a capsule and rotate it so it aligns
// with the cylinder surface
geom = PxCapsuleGeometry(radius + margin, height * 0.5f);
switch (axis)
{
case 0: preTransform = PxTransform(PxIdentity); break;
case 1: preTransform = PxTransform(PxQuat(PxPi * 0.5f, PxVec3(0, 0, 1))); break;
case 2: preTransform = PxTransform(PxQuat(PxPi * 0.5f, PxVec3(0, 1, 0))); break;
}
return true;
}
return false;
}
float PxCustomGeometryExt::CylinderCallbacks::getRadiusAtHeight(float h) const
{
if (h >= -height * 0.5f && h <= height * 0.5f)
return radius + margin;
if (h < -height * 0.5f)
{
float a = -h - height * 0.5f;
return radius + sqrtf(margin * margin - a * a);
}
if (h > height * 0.5f)
{
float a = h - height * 0.5f;
return radius + sqrtf(margin * margin - a * a);
}
PX_ASSERT(0);
return 0;
}
///////////////////////////////////////////////////////////////////////////////
IMPLEMENT_CUSTOM_GEOMETRY_TYPE(PxCustomGeometryExt::ConeCallbacks)
PxCustomGeometryExt::ConeCallbacks::ConeCallbacks(float _height, float _radius, int _axis, float _margin)
:
BaseConvexCallbacks(_margin), height(_height), radius(_radius), axis(_axis)
{
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, *this);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtBaseConvexCallbacks, margin, *static_cast<BaseConvexCallbacks*>(this), margin);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, height, *this, height);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, radius, *this, radius);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, axis, *this, axis);
OMNI_PVD_WRITE_SCOPE_END
#endif
}
void PxCustomGeometryExt::ConeCallbacks::setHeight(float h)
{
height = h;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, height, *this, height);
#endif
}
void PxCustomGeometryExt::ConeCallbacks::setRadius(float r)
{
radius = r;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, radius, *this, radius);
#endif
}
void PxCustomGeometryExt::ConeCallbacks::setAxis(int a)
{
axis = a;
#if PX_SUPPORT_OMNI_PVD
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, axis, *this, axis);
#endif
}
void PxCustomGeometryExt::ConeCallbacks::visualize(const PxGeometry&, PxRenderOutput& out, const PxTransform& transform, const PxBounds3&) const
{
const float ERR = 0.001f;
out << gCollisionShapeColor;
out << transform;
int axis1 = (axis + 1) % 3;
int axis2 = (axis + 2) % 3;
PxVec3 zr(PxZero), rd(PxZero), ax(PxZero), ax1(PxZero), ax2(PxZero), r0(PxZero), r1(PxZero);
ax[axis] = ax1[axis1] = ax2[axis2] = 1.0f;
r0[axis1] = r1[axis2] = radius;
float ang = atan2f(radius, height);
float aSin = sinf(ang);
rd[axis1] = radius;
rd[axis] = -(height * 0.5f + margin);
drawCircle(zr, rd, ax, ERR, out);
rd[axis] = -(height * 0.5f) + margin * aSin;
rd[axis1] = getRadiusAtHeight(rd[axis]);
drawCircle(zr, rd, ax, ERR, out);
rd[axis] = height * 0.5f + margin * aSin;
rd[axis1] = getRadiusAtHeight(rd[axis]);
drawCircle(zr, rd, ax, ERR, out);
float h0 = -height * 0.5f + margin * aSin, h1 = height * 0.5f + margin * aSin;
float s0 = getRadiusAtHeight(h0), s1 = getRadiusAtHeight(h1);
drawLine(ax * h0 + ax1 * s0, ax * h1 + ax1 * s1, out);
drawLine(ax * h0 - ax1 * s0, ax * h1 - ax1 * s1, out);
drawLine(ax * h0 + ax2 * s0, ax * h1 + ax2 * s1, out);
drawLine(ax * h0 - ax2 * s0, ax * h1 - ax2 * s1, out);
drawArc(-ax * height * 0.5f + ax1 * radius, -ax * margin, -ax2, PxPiDivTwo + ang, ERR, out);
drawArc(-ax * height * 0.5f - ax1 * radius, -ax * margin, ax2, PxPiDivTwo + ang, ERR, out);
drawArc(-ax * height * 0.5f + ax2 * radius, -ax * margin, ax1, PxPiDivTwo + ang, ERR, out);
drawArc(-ax * height * 0.5f - ax2 * radius, -ax * margin, -ax1, PxPiDivTwo + ang, ERR, out);
drawArc(ax * height * 0.5f, ax * margin, ax2, PxPiDivTwo - ang, ERR, out);
drawArc(ax * height * 0.5f, ax * margin, -ax2, PxPiDivTwo - ang, ERR, out);
drawArc(ax * height * 0.5f, ax * margin, -ax1, PxPiDivTwo - ang, ERR, out);
drawArc(ax * height * 0.5f, ax * margin, ax1, PxPiDivTwo - ang, ERR, out);
}
PxVec3 PxCustomGeometryExt::ConeCallbacks::supportLocal(const PxVec3& dir) const
{
float halfHeight = height * 0.5f;
float cosAlph = radius / sqrtf(height * height + radius * radius);
PxVec3 d = dir.getNormalized();
switch (axis)
{
case 0: // X
{
if (d.x > cosAlph || (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0)) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0);
return PxVec3(-halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius;
}
case 1: // Y
{
if (d.y > cosAlph || (PxSign2(d.y) != 0 && PxSign2(d.x) == 0 && PxSign2(d.z) == 0)) return PxVec3(0, PxSign2(d.y) * halfHeight, 0);
return PxVec3(0, -halfHeight, 0) + PxVec3(d.x, 0, d.z).getNormalized() * radius;
}
case 2: // Z
{
if (d.z > cosAlph || (PxSign2(d.z) != 0 && PxSign2(d.x) == 0 && PxSign2(d.y) == 0)) return PxVec3(0, 0, PxSign2(d.z) * halfHeight);
return PxVec3(0, 0, -halfHeight) + PxVec3(d.x, d.y, 0).getNormalized() * radius;
}
}
return PxVec3(0);
}
void PxCustomGeometryExt::ConeCallbacks::computeMassProperties(const PxGeometry& /*geometry*/, PxMassProperties& massProperties) const
{
if (margin == 0)
{
PxMassProperties& mass = massProperties;
float H = height, R = radius;
mass.mass = PxPi * R * R * H / 3.0f;
mass.inertiaTensor = PxMat33(PxZero);
mass.centerOfMass = PxVec3(PxZero);
float I0 = mass.mass * R * R * 3.0f / 10.0f;
float I1 = mass.mass * (R * R * 3.0f / 20.0f + H * H * 3.0f / 80.0f);
mass.inertiaTensor[axis][axis] = I0;
mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1;
mass.centerOfMass[axis] = -H / 4.0f;
mass.inertiaTensor = PxMassProperties::translateInertia(mass.inertiaTensor, mass.mass, mass.centerOfMass);
}
else
{
const int SLICE_COUNT = 32;
PxMassProperties sliceMasses[SLICE_COUNT];
PxTransform slicePoses[SLICE_COUNT];
float sliceHeight = height / SLICE_COUNT;
for (int i = 0; i < SLICE_COUNT; ++i)
{
float t = -height * 0.5f + i * sliceHeight + sliceHeight * 0.5f;
float R = getRadiusAtHeight(t), H = sliceHeight;
PxMassProperties mass;
mass.mass = PxPi * R * R * H;
mass.inertiaTensor = PxMat33(PxZero);
mass.centerOfMass = PxVec3(PxZero);
float I0 = mass.mass * R * R / 2.0f;
float I1 = mass.mass * (3 * R * R + H * H) / 12.0f;
mass.inertiaTensor[axis][axis] = I0;
mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1;
mass.centerOfMass[axis] = t;
sliceMasses[i] = mass;
slicePoses[i] = PxTransform(PxIdentity);
}
massProperties = PxMassProperties::sum(sliceMasses, slicePoses, SLICE_COUNT);
massProperties.inertiaTensor = PxMassProperties::translateInertia(massProperties.inertiaTensor, massProperties.mass, massProperties.centerOfMass);
}
}
bool PxCustomGeometryExt::ConeCallbacks::useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const
{
// here I check if we contact with the cone base or the lateral surface
// where more than 1 contact point can be generated.
PxVec3 locN = pose0.rotateInv(p.normal);
float nAng = acosf(PxClamp(-locN[axis], -1.0f, 1.0f));
float epsAng = PxPi / 36.0f; // 5 degrees
float coneAng = atan2f(radius, height);
if (nAng > PxPi - epsAng)
{
// if we contact with the base
// make the substitute geometry a box and rotate it so one of
// the corners matches the contact point
PxVec3 halfSize;
halfSize[axis] = height * 0.5f + margin;
halfSize[(axis + 1) % 3] = halfSize[(axis + 2) % 3] = radius / sqrtf(2.0f);
geom = PxBoxGeometry(halfSize);
PxVec3 axisDir(PxZero); axisDir[axis] = 1.0f;
PxVec3 locP = pose0.transformInv(p.point);
float s1 = locP[(axis + 1) % 3], s2 = locP[(axis + 2) % 3];
float ang = ((s1 * s1) + (s2 * s2) > 1e-3f) ? atan2f(s2, s1) : 0;
preTransform = PxTransform(PxQuat(ang + PxPi * 0.25f, axisDir));
return true;
}
else if (nAng > PxPiDivTwo - coneAng - epsAng && nAng < PxPiDivTwo - coneAng + epsAng)
{
// if it's the lateral surface
// make the substitute geometry a capsule and rotate it so it aligns
// with the cone surface
geom = PxCapsuleGeometry(radius * 0.25f + margin, sqrtf(height * height + radius * radius) * 0.5f);
switch (axis)
{
case 0:
{
PxVec3 capC = (PxVec3(height * 0.5f, 0, 0) + PxVec3(-height * 0.5f, radius, 0)) * 0.5f - PxVec3(radius, height, 0).getNormalized() * radius * 0.25f;
preTransform = PxTransform(capC, PxQuat(-coneAng, PxVec3(0, 0, 1)));
break;
}
case 1:
{
PxVec3 capC = (PxVec3(0, height * 0.5f, 0) + PxVec3(0, -height * 0.5f, radius)) * 0.5f - PxVec3(0, radius, height).getNormalized() * radius * 0.25f;
preTransform = PxTransform(capC, PxQuat(-coneAng, PxVec3(1, 0, 0)) * PxQuat(PxPiDivTwo, PxVec3(0, 0, 1)));
break;
}
case 2:
{
PxVec3 capC = (PxVec3(0, 0, height * 0.5f) + PxVec3(radius, 0, -height * 0.5f)) * 0.5f - PxVec3(height, 0, radius).getNormalized() * radius * 0.25f;
preTransform = PxTransform(capC, PxQuat(-coneAng, PxVec3(0, 1, 0)) * PxQuat(PxPiDivTwo, PxVec3(0, 1, 0)));
break;
}
}
PxVec3 axisDir(PxZero); axisDir[axis] = 1.0f;
float n1 = -locN[(axis + 1) % 3], n2 = -locN[(axis + 2) % 3];
float ang = atan2f(n2, n1);
// PT:: tag: scalar transform*transform
preTransform = PxTransform(PxQuat(ang, axisDir)) * preTransform;
return true;
}
return false;
}
float PxCustomGeometryExt::ConeCallbacks::getRadiusAtHeight(float h) const
{
float angle = atan2f(radius, height);
float aSin = sinf(angle);
float aCos = cosf(angle);
if (h >= -height * 0.5f + margin * aSin && h <= height * 0.5f + margin * aSin)
return radius * (height * 0.5f - h) / height + margin / aCos;
if (h < -height * 0.5f + margin * aSin)
{
float a = -h - height * 0.5f;
return radius + sqrtf(margin * margin - a * a);
}
if (h > height * 0.5f + margin * aSin)
{
float a = h - height * 0.5f;
return sqrtf(margin * margin - a * a);
}
PX_ASSERT(0);
return 0;
}
| 37,760 | C++ | 37.142424 | 203 | 0.693459 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtJoint.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 "ExtJoint.h"
#include "omnipvd/ExtOmniPvdSetData.h"
using namespace physx;
using namespace Ext;
// PX_SERIALIZATION
PxConstraint* physx::resolveConstraintPtr(PxDeserializationContext& v, PxConstraint* old, PxConstraintConnector* connector, PxConstraintShaderTable &shaders)
{
v.translatePxBase(old);
PxConstraint* new_nx = static_cast<PxConstraint*>(old);
new_nx->setConstraintFunctions(*connector, shaders);
return new_nx;
}
//~PX_SERIALIZATION
static void normalToTangents(const PxVec3& n, PxVec3& t1, PxVec3& t2)
{
const PxReal m_sqrt1_2 = PxReal(0.7071067811865475244008443621048490);
if(fabsf(n.z) > m_sqrt1_2)
{
const PxReal a = n.y*n.y + n.z*n.z;
const PxReal k = PxReal(1.0)/PxSqrt(a);
t1 = PxVec3(0,-n.z*k,n.y*k);
t2 = PxVec3(a*k,-n.x*t1.z,n.x*t1.y);
}
else
{
const PxReal a = n.x*n.x + n.y*n.y;
const PxReal k = PxReal(1.0)/PxSqrt(a);
t1 = PxVec3(-n.y*k,n.x*k,0);
t2 = PxVec3(-n.z*t1.y,n.z*t1.x,a*k);
}
t1.normalize();
t2.normalize();
}
void PxSetJointGlobalFrame(PxJoint& joint, const PxVec3* wsAnchor, const PxVec3* axisIn)
{
PxRigidActor* actors[2];
joint.getActors(actors[0], actors[1]);
PxTransform localPose[2];
for(PxU32 i=0; i<2; i++)
localPose[i] = PxTransform(PxIdentity);
// 1) global anchor
if(wsAnchor)
{
//transform anchorPoint to local space
for(PxU32 i=0; i<2; i++)
localPose[i].p = actors[i] ? actors[i]->getGlobalPose().transformInv(*wsAnchor) : *wsAnchor;
}
// 2) global axis
if(axisIn)
{
PxVec3 localAxis[2], localNormal[2];
//find 2 orthogonal vectors.
//gotta do this in world space, if we choose them
//separately in local space they won't match up in worldspace.
PxVec3 axisw = *axisIn;
axisw.normalize();
PxVec3 normalw, binormalw;
::normalToTangents(axisw, binormalw, normalw);
//because axis is supposed to be the Z axis of a frame with the other two being X and Y, we need to negate
//Y to make the frame right handed. Note that the above call makes a right handed frame if we pass X --> Y,Z, so
//it need not be changed.
for(PxU32 i=0; i<2; i++)
{
if(actors[i])
{
const PxTransform& m = actors[i]->getGlobalPose();
PxMat33 mM(m.q);
localAxis[i] = mM.transformTranspose(axisw);
localNormal[i] = mM.transformTranspose(normalw);
}
else
{
localAxis[i] = axisw;
localNormal[i] = normalw;
}
PxMat33 rot(localAxis[i], localNormal[i], localAxis[i].cross(localNormal[i]));
localPose[i].q = PxQuat(rot);
localPose[i].q.normalize();
}
}
for(PxU32 i=0; i<2; i++)
joint.setLocalPose(static_cast<PxJointActorIndex::Enum>( i ), localPose[i]);
}
#if PX_SUPPORT_OMNI_PVD
void physx::Ext::omniPvdSetBaseJointParams(PxJoint& joint, PxJointConcreteType::Enum cType)
{
OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData)
PxJoint& j = static_cast<PxJoint&>(joint);
PxRigidActor* actors[2]; j.getActors(actors[0], actors[1]);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0, j, actors[0])
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1, j, actors[1])
PxTransform actor0LocalPose = j.getLocalPose(PxJointActorIndex::eACTOR0);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0LocalPose, j, actor0LocalPose)
PxTransform actor1LocalPose = j.getLocalPose(PxJointActorIndex::eACTOR1);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1LocalPose, j, actor1LocalPose)
PxReal breakForce, breakTorque; j.getBreakForce(breakForce, breakTorque);
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakForce, j, breakForce)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakTorque, j, breakTorque)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, constraintFlags, j, j.getConstraintFlags())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale0, j, j.getInvMassScale0())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale0, j, j.getInvInertiaScale0())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale1, j, j.getInvMassScale1())
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale1, j, j.getInvInertiaScale1())
const char* name = j.getName() ? j.getName() : "";
PxU32 nameLen = PxU32(strlen(name)) + 1;
OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, name, j, name, nameLen)
const char* typeName = j.getConcreteTypeName();
PxU32 typeNameLen = PxU32(strlen(typeName)) + 1;
OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, concreteTypeName, j, typeName, typeNameLen)
OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, type, j, cType)
OMNI_PVD_WRITE_SCOPE_END
}
#endif
| 6,667 | C++ | 40.416149 | 157 | 0.736013 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCpuWorkerThread.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 "task/PxTask.h"
#include "ExtCpuWorkerThread.h"
#include "ExtDefaultCpuDispatcher.h"
#include "ExtTaskQueueHelper.h"
#include "foundation/PxFPU.h"
using namespace physx;
Ext::CpuWorkerThread::CpuWorkerThread()
: mQueueEntryPool(EXT_TASK_QUEUE_ENTRY_POOL_SIZE),
mThreadId(0)
{
}
Ext::CpuWorkerThread::~CpuWorkerThread()
{
}
void Ext::CpuWorkerThread::initialize(DefaultCpuDispatcher* ownerDispatcher)
{
mOwner = ownerDispatcher;
}
bool Ext::CpuWorkerThread::tryAcceptJobToLocalQueue(PxBaseTask& task, PxThread::Id taskSubmitionThread)
{
if(taskSubmitionThread == mThreadId)
{
SharedQueueEntry* entry = mQueueEntryPool.getEntry(&task);
if (entry)
{
mLocalJobList.push(*entry);
return true;
}
else
return false;
}
return false;
}
PxBaseTask* Ext::CpuWorkerThread::giveUpJob()
{
return TaskQueueHelper::fetchTask(mLocalJobList, mQueueEntryPool);
}
void Ext::CpuWorkerThread::execute()
{
mThreadId = getId();
const PxDefaultCpuDispatcherWaitForWorkMode::Enum ownerWaitForWorkMode = mOwner->getWaitForWorkMode();
while(!quitIsSignalled())
{
if(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == ownerWaitForWorkMode)
mOwner->resetWakeSignal();
PxBaseTask* task = TaskQueueHelper::fetchTask(mLocalJobList, mQueueEntryPool);
if(!task)
task = mOwner->fetchNextTask();
if(task)
{
mOwner->runTask(*task);
task->release();
}
else if(PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_THREAD == ownerWaitForWorkMode)
{
PxThread::yield();
}
else if(PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_PROCESSOR == ownerWaitForWorkMode)
{
const PxU32 pauseCounter = mOwner->getYieldProcessorCount();
for(PxU32 j = 0; j < pauseCounter; j++)
PxThread::yieldProcesor();
}
else
{
PX_ASSERT(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == ownerWaitForWorkMode);
mOwner->waitForWork();
}
}
quit();
}
| 3,602 | C++ | 30.605263 | 103 | 0.752915 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqManager.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 "ExtSqManager.h"
#define SQ_DEBUG_VIZ_STATIC_COLOR PxU32(PxDebugColor::eARGB_BLUE)
#define SQ_DEBUG_VIZ_DYNAMIC_COLOR PxU32(PxDebugColor::eARGB_RED)
#define SQ_DEBUG_VIZ_STATIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKBLUE)
#define SQ_DEBUG_VIZ_DYNAMIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKRED)
#define SQ_DEBUG_VIZ_COMPOUND_COLOR PxU32(PxDebugColor::eARGB_MAGENTA)
#include "GuBounds.h"
using namespace physx;
using namespace Sq;
using namespace Gu;
///////////////////////////////////////////////////////////////////////////////
#include "SqFactory.h"
#include "common/PxProfileZone.h"
#include "common/PxRenderBuffer.h"
#include "GuBVH.h"
#include "foundation/PxAlloca.h"
// PT: this is a customized version of physx::Sq::PrunerManager that supports more than 2 hardcoded pruners.
// It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners.
ExtPrunerManager::ExtPrunerManager(PxU64 contextID, float inflation, const Adapter& adapter, bool usesTreeOfPruners) :
mAdapter (adapter),
mTreeOfPruners (NULL),
mContextID (contextID),
mStaticTimestamp (0),
mRebuildRateHint (100),
mInflation (inflation),
mPrunerNeedsUpdating (false),
mTimestampNeedsUpdating (false),
mUsesTreeOfPruners (usesTreeOfPruners)
{
mCompoundPrunerExt.mPruner = createCompoundPruner(contextID);
}
ExtPrunerManager::~ExtPrunerManager()
{
PX_DELETE(mTreeOfPruners);
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
PX_DELETE(pe);
}
}
PxU32 ExtPrunerManager::addPruner(Pruner* pruner, PxU32 preallocated)
{
const PxU32 index = mPrunerExt.size();
PrunerExt* pe = PX_NEW(PrunerExt);
pe->init(pruner);
if(preallocated)
pe->preallocate(preallocated);
mPrunerExt.pushBack(pe);
return index;
}
void ExtPrunerManager::preallocate(PxU32 prunerIndex, PxU32 nbShapes)
{
const bool preallocateCompoundPruner = prunerIndex==0xffffffff;
if(preallocateCompoundPruner)
{
mCompoundPrunerExt.preallocate(nbShapes);
}
else
{
if(prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return;
}
mPrunerExt[prunerIndex]->preallocate(nbShapes);
}
}
void ExtPrunerManager::flushMemory()
{
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
pe->flushMemory();
}
mCompoundPrunerExt.flushMemory();
}
PrunerHandle ExtPrunerManager::addPrunerShape(const PrunerPayload& payload, PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, const PxBounds3& bounds, const PxTransform& transform, bool hasPruningStructure)
{
if(compoundId==INVALID_COMPOUND_ID && prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return INVALID_PRUNERHANDLE;
}
mPrunerNeedsUpdating = true;
if(!dynamic)
invalidateStaticTimestamp();
PrunerHandle handle;
if(compoundId == INVALID_COMPOUND_ID)
{
PX_ASSERT(prunerIndex<mPrunerExt.size());
PX_ASSERT(mPrunerExt[prunerIndex]->pruner());
mPrunerExt[prunerIndex]->pruner()->addObjects(&handle, &bounds, &payload, &transform, 1, hasPruningStructure);
//mPrunerExt[prunerIndex].growDirtyList(handle);
}
else
{
PX_ASSERT(mCompoundPrunerExt.pruner());
mCompoundPrunerExt.pruner()->addObject(compoundId, handle, bounds, payload, transform);
}
return handle;
}
void ExtPrunerManager::removePrunerShape(PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, PrunerHandle shapeHandle, PrunerPayloadRemovalCallback* removalCallback)
{
if(compoundId==INVALID_COMPOUND_ID && prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return;
}
mPrunerNeedsUpdating = true;
if(!dynamic)
invalidateStaticTimestamp();
if(compoundId == INVALID_COMPOUND_ID)
{
PX_ASSERT(prunerIndex<mPrunerExt.size());
PX_ASSERT(mPrunerExt[prunerIndex]->pruner());
mPrunerExt[prunerIndex]->removeFromDirtyList(shapeHandle);
mPrunerExt[prunerIndex]->pruner()->removeObjects(&shapeHandle, 1, removalCallback);
}
else
{
mCompoundPrunerExt.removeFromDirtyList(compoundId, shapeHandle);
mCompoundPrunerExt.pruner()->removeObject(compoundId, shapeHandle, removalCallback);
}
}
void ExtPrunerManager::markForUpdate(PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, PrunerHandle shapeHandle, const PxTransform& transform)
{
if(compoundId==INVALID_COMPOUND_ID && prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return;
}
mPrunerNeedsUpdating = true;
if(!dynamic)
invalidateStaticTimestamp();
if(compoundId == INVALID_COMPOUND_ID)
{
PX_ASSERT(prunerIndex<mPrunerExt.size());
PX_ASSERT(mPrunerExt[prunerIndex]->pruner());
// PT: TODO: at this point do we still need a dirty list? we could just update the bounds directly?
mPrunerExt[prunerIndex]->addToDirtyList(shapeHandle, dynamic, transform);
}
else
mCompoundPrunerExt.addToDirtyList(compoundId, shapeHandle, transform);
}
void ExtPrunerManager::setDynamicTreeRebuildRateHint(PxU32 rebuildRateHint)
{
mRebuildRateHint = rebuildRateHint;
// PT: we are still using the same rebuild hint for all pruners here, which may or may
// not make sense. We could also have a different build rate for each pruner.
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
Pruner* pruner = pe->pruner();
if(pruner && pruner->isDynamic())
static_cast<DynamicPruner*>(pruner)->setRebuildRateHint(rebuildRateHint);
}
}
void ExtPrunerManager::afterSync(bool buildStep, bool commit)
{
PX_PROFILE_ZONE("Sim.sceneQueryBuildStep", mContextID);
if(!buildStep && !commit)
{
mPrunerNeedsUpdating = true;
return;
}
// flush user modified objects
flushShapes();
// PT: TODO: with N pruners this part would be worth multi-threading
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
Pruner* pruner = pe->pruner();
if(pruner)
{
if(pruner->isDynamic())
static_cast<DynamicPruner*>(pruner)->buildStep(true);
if(commit)
pruner->commit();
}
}
if(commit)
{
if(mUsesTreeOfPruners)
createTreeOfPruners();
}
mPrunerNeedsUpdating = !commit;
}
void ExtPrunerManager::flushShapes()
{
PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID);
// must already have acquired writer lock here
const float inflation = 1.0f + mInflation;
bool mustInvalidateStaticTimestamp = false;
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
if(pe->processDirtyList(i, mAdapter, inflation))
mustInvalidateStaticTimestamp = true;
}
if(mustInvalidateStaticTimestamp)
invalidateStaticTimestamp();
mCompoundPrunerExt.flushShapes(mAdapter, inflation);
}
void ExtPrunerManager::flushUpdates()
{
PX_PROFILE_ZONE("SceneQuery.flushUpdates", mContextID);
if(mPrunerNeedsUpdating)
{
// no need to take lock if manual sq update is enabled
// as flushUpdates will only be called from NpScene::flushQueryUpdates()
mSQLock.lock();
if(mPrunerNeedsUpdating)
{
flushShapes();
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
if(pe->pruner())
pe->pruner()->commit();
}
if(mUsesTreeOfPruners)
createTreeOfPruners();
PxMemoryBarrier();
mPrunerNeedsUpdating = false;
}
mSQLock.unlock();
}
}
void ExtPrunerManager::forceRebuildDynamicTree(PxU32 prunerIndex)
{
// PT: beware here when called from the PxScene, the prunerIndex may not match
PX_PROFILE_ZONE("SceneQuery.forceDynamicTreeRebuild", mContextID);
if(prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return;
}
PxMutex::ScopedLock lock(mSQLock);
PrunerExt* pe = mPrunerExt[prunerIndex];
Pruner* pruner = pe->pruner();
if(pruner && pruner->isDynamic())
{
static_cast<DynamicPruner*>(pruner)->purge();
static_cast<DynamicPruner*>(pruner)->commit();
}
}
void* ExtPrunerManager::prepareSceneQueriesUpdate(PxU32 prunerIndex)
{
// PT: beware here when called from the PxScene, the prunerIndex may not match
if(prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return NULL;
}
PX_ASSERT(mPrunerExt[prunerIndex]->pruner());
bool retVal = false;
Pruner* pruner = mPrunerExt[prunerIndex]->pruner();
if(pruner && pruner->isDynamic())
retVal = static_cast<DynamicPruner*>(pruner)->prepareBuild();
return retVal ? pruner : NULL;
}
void ExtPrunerManager::sceneQueryBuildStep(void* handle)
{
PX_PROFILE_ZONE("SceneQuery.sceneQueryBuildStep", mContextID);
Pruner* pruner = reinterpret_cast<Pruner*>(handle);
if(pruner && pruner->isDynamic())
{
const bool buildFinished = static_cast<DynamicPruner*>(pruner)->buildStep(false);
if(buildFinished)
mPrunerNeedsUpdating = true;
}
}
void ExtPrunerManager::visualize(PxU32 prunerIndex, PxRenderOutput& out) const
{
// PT: beware here when called from the PxScene, the prunerIndex may not match
// This is quite awkward and should be improved.
// PT: problem here is that this function will be called by the regular PhysX scene when plugged to its PxSceneDesc,
// and the calling code only understands the regular PhysX pruners.
const bool visualizeCompoundPruner = prunerIndex==0xffffffff;
if(visualizeCompoundPruner)
{
const CompoundPruner* cp = mCompoundPrunerExt.pruner();
if(cp)
cp->visualizeEx(out, SQ_DEBUG_VIZ_COMPOUND_COLOR, true, true);
}
else
{
if(prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return;
}
PrunerExt* pe = mPrunerExt[prunerIndex];
Pruner* pruner = pe->pruner();
if(pruner)
{
// PT: TODO: this doesn't really work: the static color was for static shapes but they
// could still be stored in a dynamic pruner. So this code doesn't use a color scheme
// consistent with what we use in the default code.
if(pruner->isDynamic())
{
//if(visDynamic)
pruner->visualize(out, SQ_DEBUG_VIZ_DYNAMIC_COLOR, SQ_DEBUG_VIZ_DYNAMIC_COLOR2);
}
else
{
//if(visStatic)
pruner->visualize(out, SQ_DEBUG_VIZ_STATIC_COLOR, SQ_DEBUG_VIZ_STATIC_COLOR2);
}
}
}
}
void ExtPrunerManager::shiftOrigin(const PxVec3& shift)
{
const PxU32 nb = mPrunerExt.size();
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
Pruner* pruner = pe->pruner();
if(pruner)
pruner->shiftOrigin(shift);
}
mCompoundPrunerExt.pruner()->shiftOrigin(shift);
}
void ExtPrunerManager::addCompoundShape(const PxBVH& pxbvh, PrunerCompoundId compoundId, const PxTransform& compoundTransform, PrunerHandle* prunerHandle, const PrunerPayload* payloads, const PxTransform* transforms, bool isDynamic)
{
const Gu::BVH& bvh = static_cast<const Gu::BVH&>(pxbvh);
PX_ASSERT(mCompoundPrunerExt.mPruner);
mCompoundPrunerExt.mPruner->addCompound(prunerHandle, bvh, compoundId, compoundTransform, isDynamic, payloads, transforms);
if(!isDynamic)
invalidateStaticTimestamp();
}
void ExtPrunerManager::updateCompoundActor(PrunerCompoundId compoundId, const PxTransform& compoundTransform)
{
PX_ASSERT(mCompoundPrunerExt.mPruner);
const bool isDynamic = mCompoundPrunerExt.mPruner->updateCompound(compoundId, compoundTransform);
if(!isDynamic)
invalidateStaticTimestamp();
}
void ExtPrunerManager::removeCompoundActor(PrunerCompoundId compoundId, PrunerPayloadRemovalCallback* removalCallback)
{
PX_ASSERT(mCompoundPrunerExt.mPruner);
const bool isDynamic = mCompoundPrunerExt.mPruner->removeCompound(compoundId, removalCallback);
if(!isDynamic)
invalidateStaticTimestamp();
}
void ExtPrunerManager::sync(PxU32 prunerIndex, const PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices)
{
if(!count)
return;
if(prunerIndex>=mPrunerExt.size())
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index");
return;
}
Pruner* pruner = getPruner(prunerIndex);
if(!pruner)
return;
PxU32 startIndex = 0;
PxU32 numIndices = count;
// if shape sim map is not empty, parse the indices and skip update for the dirty one
if(ignoredIndices.count())
{
// PT: I think this codepath was used with SCB / buffered changes, but it's not needed anymore
numIndices = 0;
for(PxU32 i=0; i<count; i++)
{
// if(ignoredIndices.test(boundsIndices[i]))
if(ignoredIndices.boundedTest(boundsIndices[i]))
{
pruner->updateObjects(handles + startIndex, numIndices, mInflation, boundsIndices + startIndex, bounds, transforms);
numIndices = 0;
startIndex = i + 1;
}
else
numIndices++;
}
// PT: we fallback to the next line on purpose - no "else"
}
pruner->updateObjects(handles + startIndex, numIndices, mInflation, boundsIndices + startIndex, bounds, transforms);
}
PxU32 ExtPrunerManager::startCustomBuildstep()
{
PX_PROFILE_ZONE("SceneQuery.startCustomBuildstep", mContextID);
// flush user modified objects
//flushShapes();
{
PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID);
// PT: only flush the compound pruner synchronously
// must already have acquired writer lock here
const float inflation = 1.0f + mInflation;
mCompoundPrunerExt.flushShapes(mAdapter, inflation);
}
mTimestampNeedsUpdating = false;
return mPrunerExt.size();
}
void ExtPrunerManager::customBuildstep(PxU32 index)
{
PX_PROFILE_ZONE("SceneQuery.customBuildstep", mContextID);
PX_ASSERT(index<mPrunerExt.size());
PrunerExt* pe = mPrunerExt[index];
Pruner* pruner = pe->pruner();
//void ExtPrunerManager::flushShapes()
{
PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID);
// must already have acquired writer lock here
const float inflation = 1.0f + mInflation;
if(pe->processDirtyList(index, mAdapter, inflation))
mTimestampNeedsUpdating = true;
}
if(pruner)
{
if(pruner->isDynamic())
static_cast<DynamicPruner*>(pruner)->buildStep(true); // PT: "true" because that parameter was made for PxSceneQuerySystem::sceneQueryBuildStep(), not us
pruner->commit();
}
}
void ExtPrunerManager::finishCustomBuildstep()
{
PX_PROFILE_ZONE("SceneQuery.finishCustomBuildstep", mContextID);
if(mUsesTreeOfPruners)
createTreeOfPruners();
mPrunerNeedsUpdating = false;
if(mTimestampNeedsUpdating)
invalidateStaticTimestamp();
}
void ExtPrunerManager::createTreeOfPruners()
{
PX_PROFILE_ZONE("SceneQuery.createTreeOfPruners", mContextID);
PX_DELETE(mTreeOfPruners);
mTreeOfPruners = PX_NEW(BVH)(NULL);
const PxU32 nb = mPrunerExt.size();
PxBounds3* prunerBounds = reinterpret_cast<PxBounds3*>(PxAlloca(sizeof(PxBounds3)*(nb+1)));
PxU32 nbBounds = 0;
for(PxU32 i=0;i<nb;i++)
{
PrunerExt* pe = mPrunerExt[i];
Pruner* pruner = pe->pruner();
if(pruner)
pruner->getGlobalBounds(prunerBounds[nbBounds++]);
}
mTreeOfPruners->init(nbBounds, NULL, prunerBounds, sizeof(PxBounds3), BVH_SPLATTER_POINTS, 1, 0.01f);
}
| 16,920 | C++ | 28.224525 | 232 | 0.741253 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtInertiaTensor.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_INERTIA_TENSOR_H
#define EXT_INERTIA_TENSOR_H
#include "foundation/PxMat33.h"
#include "foundation/PxMathUtils.h"
namespace physx
{
namespace Ext
{
class InertiaTensorComputer
{
public:
InertiaTensorComputer(bool initTozero = true);
InertiaTensorComputer(const PxMat33& inertia, const PxVec3& com, PxReal mass);
~InertiaTensorComputer();
PX_INLINE void zero(); //sets to zero mass
PX_INLINE void setDiagonal(PxReal mass, const PxVec3& diagonal); //sets as a diagonal tensor
PX_INLINE void rotate(const PxMat33& rot); //rotates the mass
void translate(const PxVec3& t); //translates the mass
PX_INLINE void transform(const PxTransform& transform); //transforms the mass
PX_INLINE void scaleDensity(PxReal densityScale); //scales by a density factor
PX_INLINE void add(const InertiaTensorComputer& it); //adds a mass
PX_INLINE void center(); //recenters inertia around center of mass
void setBox(const PxVec3& halfWidths); //sets as an axis aligned box
PX_INLINE void setBox(const PxVec3& halfWidths, const PxTransform* pose); //sets as an oriented box
void setSphere(PxReal radius);
PX_INLINE void setSphere(PxReal radius, const PxTransform* pose);
void setCylinder(int dir, PxReal r, PxReal l);
PX_INLINE void setCylinder(int dir, PxReal r, PxReal l, const PxTransform* pose);
void setCapsule(int dir, PxReal r, PxReal l);
PX_INLINE void setCapsule(int dir, PxReal r, PxReal l, const PxTransform* pose);
void setEllipsoid(PxReal rx, PxReal ry, PxReal rz);
PX_INLINE void setEllipsoid(PxReal rx, PxReal ry, PxReal rz, const PxTransform* pose);
PX_INLINE PxVec3 getCenterOfMass() const { return mG; }
PX_INLINE PxReal getMass() const { return mMass; }
PX_INLINE PxMat33 getInertia() const { return mI; }
private:
PxMat33 mI;
PxVec3 mG;
PxReal mMass;
};
//--------------------------------------------------------------
//
// Helper routines
//
//--------------------------------------------------------------
// Special version allowing 2D quads
PX_INLINE PxReal volume(const PxVec3& extents)
{
PxReal v = 1.0f;
if(extents.x != 0.0f) v*=extents.x;
if(extents.y != 0.0f) v*=extents.y;
if(extents.z != 0.0f) v*=extents.z;
return v;
}
// Sphere
PX_INLINE PxReal computeSphereRatio(PxReal radius) { return (4.0f/3.0f) * PxPi * radius * radius * radius; }
PxReal computeSphereMass(PxReal radius, PxReal density) { return density * computeSphereRatio(radius); }
PxReal computeSphereDensity(PxReal radius, PxReal mass) { return mass / computeSphereRatio(radius); }
// Box
PX_INLINE PxReal computeBoxRatio(const PxVec3& extents) { return volume(extents); }
PxReal computeBoxMass(const PxVec3& extents, PxReal density) { return density * computeBoxRatio(extents); }
PxReal computeBoxDensity(const PxVec3& extents, PxReal mass) { return mass / computeBoxRatio(extents); }
// Ellipsoid
PX_INLINE PxReal computeEllipsoidRatio(const PxVec3& extents) { return (4.0f/3.0f) * PxPi * volume(extents); }
PxReal computeEllipsoidMass(const PxVec3& extents, PxReal density) { return density * computeEllipsoidRatio(extents); }
PxReal computeEllipsoidDensity(const PxVec3& extents, PxReal mass) { return mass / computeEllipsoidRatio(extents); }
// Cylinder
PX_INLINE PxReal computeCylinderRatio(PxReal r, PxReal l) { return PxPi * r * r * (2.0f*l); }
PxReal computeCylinderMass(PxReal r, PxReal l, PxReal density) { return density * computeCylinderRatio(r, l); }
PxReal computeCylinderDensity(PxReal r, PxReal l, PxReal mass) { return mass / computeCylinderRatio(r, l); }
// Capsule
PX_INLINE PxReal computeCapsuleRatio(PxReal r, PxReal l) { return computeSphereRatio(r) + computeCylinderRatio(r, l);}
PxReal computeCapsuleMass(PxReal r, PxReal l, PxReal density) { return density * computeCapsuleRatio(r, l); }
PxReal computeCapsuleDensity(PxReal r, PxReal l, PxReal mass) { return mass / computeCapsuleRatio(r, l); }
// Cone
PX_INLINE PxReal computeConeRatio(PxReal r, PxReal l) { return PxPi * r * r * PxAbs(l)/3.0f; }
PxReal computeConeMass(PxReal r, PxReal l, PxReal density) { return density * computeConeRatio(r, l); }
PxReal computeConeDensity(PxReal r, PxReal l, PxReal mass) { return mass / computeConeRatio(r, l); }
void computeBoxInertiaTensor(PxVec3& inertia, PxReal mass, PxReal xlength, PxReal ylength, PxReal zlength);
void computeSphereInertiaTensor(PxVec3& inertia, PxReal mass, PxReal radius, bool hollow);
bool jacobiTransform(PxI32 n, PxF64 a[], PxF64 w[]);
bool diagonalizeInertiaTensor(const PxMat33& denseInertia, PxVec3& diagonalInertia, PxMat33& rotation);
} // namespace Ext
void Ext::computeBoxInertiaTensor(PxVec3& inertia, PxReal mass, PxReal xlength, PxReal ylength, PxReal zlength)
{
//to model a hollow block, one would have to multiply coeff by up to two.
const PxReal coeff = mass/12;
inertia.x = coeff * (ylength*ylength + zlength*zlength);
inertia.y = coeff * (xlength*xlength + zlength*zlength);
inertia.z = coeff * (xlength*xlength + ylength*ylength);
PX_ASSERT(inertia.x != 0.0f);
PX_ASSERT(inertia.y != 0.0f);
PX_ASSERT(inertia.z != 0.0f);
PX_ASSERT(inertia.isFinite());
}
void Ext::computeSphereInertiaTensor(PxVec3& inertia, PxReal mass, PxReal radius, bool hollow)
{
inertia.x = mass * radius * radius;
if (hollow)
inertia.x *= PxReal(2 / 3.0);
else
inertia.x *= PxReal(2 / 5.0);
inertia.z = inertia.y = inertia.x;
PX_ASSERT(inertia.isFinite());
}
//--------------------------------------------------------------
//
// InertiaTensorComputer implementation
//
//--------------------------------------------------------------
Ext::InertiaTensorComputer::InertiaTensorComputer(bool initTozero)
{
if (initTozero)
zero();
}
Ext::InertiaTensorComputer::InertiaTensorComputer(const PxMat33& inertia, const PxVec3& com, PxReal mass) :
mI(inertia),
mG(com),
mMass(mass)
{
}
Ext::InertiaTensorComputer::~InertiaTensorComputer()
{
}
PX_INLINE void Ext::InertiaTensorComputer::zero()
{
mMass = 0.0f;
mI = PxMat33(PxZero);
mG = PxVec3(0);
}
PX_INLINE void Ext::InertiaTensorComputer::setDiagonal(PxReal mass, const PxVec3& diag)
{
mMass = mass;
mI = PxMat33::createDiagonal(diag);
mG = PxVec3(0);
PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite());
PX_ASSERT(PxIsFinite(mMass));
}
void Ext::InertiaTensorComputer::setBox(const PxVec3& halfWidths)
{
// Setup inertia tensor for a cube with unit density
const PxReal mass = 8.0f * computeBoxRatio(halfWidths);
const PxReal s =(1.0f/3.0f) * mass;
const PxReal x = halfWidths.x*halfWidths.x;
const PxReal y = halfWidths.y*halfWidths.y;
const PxReal z = halfWidths.z*halfWidths.z;
setDiagonal(mass, PxVec3(y+z, z+x, x+y) * s);
}
PX_INLINE void Ext::InertiaTensorComputer::rotate(const PxMat33& rot)
{
//well known inertia tensor rotation expression is: RIR' -- this could be optimized due to symmetry, see code to do that in Body::updateGlobalInverseInertia
mI = rot * mI * rot.getTranspose();
PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite());
//com also needs to be rotated
mG = rot * mG;
PX_ASSERT(mG.isFinite());
}
void Ext::InertiaTensorComputer::translate(const PxVec3& t)
{
if (!t.isZero()) //its common for this to be zero
{
PxMat33 t1, t2;
t1.column0 = PxVec3(0, mG.z, -mG.y);
t1.column1 = PxVec3(-mG.z, 0, mG.x);
t1.column2 = PxVec3(mG.y, -mG.x, 0);
PxVec3 sum = mG + t;
if (sum.isZero())
{
mI += (t1 * t1)*mMass;
}
else
{
t2.column0 = PxVec3(0, sum.z, -sum.y);
t2.column1 = PxVec3(-sum.z, 0, sum.x);
t2.column2 = PxVec3(sum.y, -sum.x, 0);
mI += (t1 * t1 - t2 * t2)*mMass;
}
//move center of mass
mG += t;
PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite());
PX_ASSERT(mG.isFinite());
}
}
PX_INLINE void Ext::InertiaTensorComputer::transform(const PxTransform& transform)
{
rotate(PxMat33(transform.q));
translate(transform.p);
}
PX_INLINE void Ext::InertiaTensorComputer::setBox(const PxVec3& halfWidths, const PxTransform* pose)
{
setBox(halfWidths);
if (pose)
transform(*pose);
}
PX_INLINE void Ext::InertiaTensorComputer::scaleDensity(PxReal densityScale)
{
mI *= densityScale;
mMass *= densityScale;
PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite());
PX_ASSERT(PxIsFinite(mMass));
}
PX_INLINE void Ext::InertiaTensorComputer::add(const InertiaTensorComputer& it)
{
const PxReal TotalMass = mMass + it.mMass;
mG = (mG * mMass + it.mG * it.mMass) / TotalMass;
mMass = TotalMass;
mI += it.mI;
PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite());
PX_ASSERT(mG.isFinite());
PX_ASSERT(PxIsFinite(mMass));
}
PX_INLINE void Ext::InertiaTensorComputer::center()
{
PxVec3 center = -mG;
translate(center);
}
void Ext::InertiaTensorComputer::setSphere(PxReal radius)
{
// Compute mass of the sphere
const PxReal m = computeSphereRatio(radius);
// Compute moment of inertia
const PxReal s = m * radius * radius * (2.0f/5.0f);
setDiagonal(m,PxVec3(s,s,s));
}
PX_INLINE void Ext::InertiaTensorComputer::setSphere(PxReal radius, const PxTransform* pose)
{
setSphere(radius);
if (pose)
transform(*pose);
}
void Ext::InertiaTensorComputer::setCylinder(int dir, PxReal r, PxReal l)
{
// Compute mass of cylinder
const PxReal m = computeCylinderRatio(r, l);
const PxReal i1 = r*r*m/2.0f;
const PxReal i2 = (3.0f*r*r+4.0f*l*l)*m/12.0f;
switch(dir)
{
case 0: setDiagonal(m,PxVec3(i1,i2,i2)); break;
case 1: setDiagonal(m,PxVec3(i2,i1,i2)); break;
default: setDiagonal(m,PxVec3(i2,i2,i1)); break;
}
}
PX_INLINE void Ext::InertiaTensorComputer::setCylinder(int dir, PxReal r, PxReal l, const PxTransform* pose)
{
setCylinder(dir, r, l);
if (pose)
transform(*pose);
}
void Ext::InertiaTensorComputer::setCapsule(int dir, PxReal r, PxReal l)
{
// Compute mass of capsule
const PxReal m = computeCapsuleRatio(r, l);
const PxReal t = PxPi * r * r;
const PxReal i1 = t * ((r*r*r * 8.0f/15.0f) + (l*r*r));
const PxReal i2 = t * ((r*r*r * 8.0f/15.0f) + (l*r*r * 3.0f/2.0f) + (l*l*r * 4.0f/3.0f) + (l*l*l * 2.0f/3.0f));
switch(dir)
{
case 0: setDiagonal(m,PxVec3(i1,i2,i2)); break;
case 1: setDiagonal(m,PxVec3(i2,i1,i2)); break;
default: setDiagonal(m,PxVec3(i2,i2,i1)); break;
}
}
PX_INLINE void Ext::InertiaTensorComputer::setCapsule(int dir, PxReal r, PxReal l, const PxTransform* pose)
{
setCapsule(dir, r, l);
if (pose)
transform(*pose);
}
void Ext::InertiaTensorComputer::setEllipsoid(PxReal rx, PxReal ry, PxReal rz)
{
// Compute mass of ellipsoid
const PxReal m = computeEllipsoidRatio(PxVec3(rx, ry, rz));
// Compute moment of inertia
const PxReal s = m * (2.0f/5.0f);
// Setup inertia tensor for an ellipsoid centered at the origin
setDiagonal(m,PxVec3(ry*rz,rz*rx,rx*ry)*s);
}
PX_INLINE void Ext::InertiaTensorComputer::setEllipsoid(PxReal rx, PxReal ry, PxReal rz, const PxTransform* pose)
{
setEllipsoid(rx,ry,rz);
if (pose)
transform(*pose);
}
}
#endif
| 12,953 | C | 33.360743 | 157 | 0.692658 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSerialization.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_SERIALIZATION_H
#define EXT_SERIALIZATION_H
namespace physx
{
namespace Ext
{
void RegisterExtensionsSerializers(PxSerializationRegistry& sr);
void UnregisterExtensionsSerializers(PxSerializationRegistry& sr);
void GetExtensionsBinaryMetaData(PxOutputStream& stream);
}
}
#endif
| 1,995 | C | 44.363635 | 74 | 0.775439 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetUnionFind.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 "ExtTetUnionFind.h"
namespace physx
{
namespace Ext
{
//------------------------------------------------------------------------------------
void UnionFind::init(PxI32 numSets)
{
mEntries.resize(numSets);
for (PxI32 i = 0; i < numSets; i++) {
Entry &e = mEntries[i];
e.parent = i;
e.rank = 0;
e.setNr = i;
}
}
//------------------------------------------------------------------------------------
PxI32 UnionFind::find(PxI32 x)
{
if (mEntries[x].parent != x)
mEntries[x].parent = find(mEntries[x].parent);
return mEntries[x].parent;
}
//------------------------------------------------------------------------------------
void UnionFind::makeSet(PxI32 x, PxI32 y)
{
PxI32 xroot = find(x);
PxI32 yroot = find(y);
if (xroot == yroot)
return;
if (mEntries[xroot].rank < mEntries[yroot].rank)
mEntries[xroot].parent = yroot;
else if (mEntries[xroot].rank > mEntries[yroot].rank)
mEntries[yroot].parent = xroot;
else {
mEntries[yroot].parent = xroot;
mEntries[xroot].rank++;
}
}
//------------------------------------------------------------------------------------
PxI32 UnionFind::computeSetNrs()
{
PxArray<PxI32> oldToNew(mEntries.size(), -1);
PxI32 numSets = 0;
for (PxU32 i = 0; i < mEntries.size(); i++) {
PxI32 nr = find(i);
if (oldToNew[nr] < 0)
oldToNew[nr] = numSets++;
mEntries[i].setNr = oldToNew[nr];
}
return numSets;
}
//------------------------------------------------------------------------------------
PxI32 UnionFind::getSetNr(PxI32 x)
{
return mEntries[x].setNr;
}
}
}
| 3,162 | C++ | 33.380434 | 87 | 0.609108 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtQuadric.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_QUADRIC_H
#define EXT_QUADRIC_H
#include "foundation/PxVec3.h"
// MM: used in ExtMeshSimplificator
// see paper Garland and Heckbert: "Surface Simplification Using Quadric Error Metrics"
namespace physx
{
namespace Ext
{
class Quadric {
public:
PX_FORCE_INLINE void zero()
{
a00 = 0.0f; a01 = 0.0f; a02 = 0.0f; a03 = 0.0f;
a11 = 0.0f; a12 = 0.0f; a13 = 0.0f;
a22 = 0.0f; a23 = 0.0f;
a33 = 0.0f;
}
PX_FORCE_INLINE void setFromPlane(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2)
{
PxVec3 n = (v1 - v0).cross(v2 - v0); n.normalize();
float d = -n.dot(v0);
a00 = n.x * n.x; a01 = n.x * n.y; a02 = n.x * n.z; a03 = n.x * d;
a11 = n.y * n.y; a12 = n.y * n.z; a13 = n.y * d;
a22 = n.z * n.z; a23 = n.z * d;
a33 = d * d;
}
PX_FORCE_INLINE Quadric operator +(const Quadric& q) const
{
Quadric sum;
sum.a00 = a00 + q.a00; sum.a01 = a01 + q.a01; sum.a02 = a02 + q.a02; sum.a03 = a03 + q.a03;
sum.a11 = a11 + q.a11; sum.a12 = a12 + q.a12; sum.a13 = a13 + q.a13;
sum.a22 = a22 + q.a22; sum.a23 = a23 + q.a23;
sum.a33 = a33 + q.a33;
return sum;
}
void operator +=(const Quadric& q)
{
a00 += q.a00; a01 += q.a01; a02 += q.a02; a03 += q.a03;
a11 += q.a11; a12 += q.a12; a13 += q.a13;
a22 += q.a22; a23 += q.a23;
a33 += q.a33;
}
PxF32 outerProduct(const PxVec3& v)
{
return a00 * v.x * v.x + 2.0f * a01 * v.x * v.y + 2.0f * a02 * v.x * v.z + 2.0f * a03 * v.x +
a11 * v.y * v.y + 2.0f * a12 * v.y * v.z + 2.0f * a13 * v.y +
a22 * v.z * v.z + 2.0f * a23 * v.z + a33;
}
private:
PxF32 a00, a01, a02, a03;
PxF32 a11, a12, a13;
PxF32 a22, a23;
PxF32 a33;
};
}
}
#endif
| 3,331 | C | 34.446808 | 97 | 0.637646 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtBVH.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 "ExtBVH.h"
#include "ExtUtilities.h"
namespace physx
{
namespace Ext
{
using namespace Gu;
void BVHDesc::query(const PxBounds3& bounds, PxArray<PxI32>& items)
{
items.clear();
IntersectionCollectingTraversalController traversalController(bounds, items);
traverseBVH(tree.begin(), traversalController, 0);
}
void BVHBuilder::build(BVHDesc& bvh, const PxBounds3* items, PxI32 n)
{
AABBTreeBounds boxes;
boxes.init(n);
for (PxI32 i = 0; i < n; ++i)
boxes.getBounds()[i] = items[i];
Gu::buildAABBTree(n, boxes, bvh.tree);
}
}
}
| 2,146 | C++ | 39.509433 | 80 | 0.744175 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtFastWindingNumber.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 "ExtFastWindingNumber.h"
#include "foundation/PxSort.h"
#include "foundation/PxMath.h"
#include "ExtUtilities.h"
//The following paper explains all the techniques used in this file
//http://www.dgp.toronto.edu/projects/fast-winding-numbers/fast-winding-numbers-for-soups-and-clouds-siggraph-2018-barill-et-al.pdf
namespace physx
{
namespace Ext
{
PxF64 computeWindingNumber(const PxArray<Gu::BVHNode>& tree, const PxVec3d& q, PxF64 beta, const PxHashMap<PxU32, ClusterApproximationF64>& clusters,
const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points)
{
return Gu::computeWindingNumber<PxF64, PxVec3d>(tree.begin(), q, beta, clusters, reinterpret_cast<const PxU32*>(triangles.begin()), points.begin());
}
void precomputeClusterInformation(PxArray<Gu::BVHNode>& tree, const PxArray<Triangle>& triangles,
const PxArray<PxVec3d>& points, PxHashMap<PxU32, ClusterApproximationF64>& result, PxI32 rootNodeIndex)
{
Gu::precomputeClusterInformation<PxF64, PxVec3d>(tree.begin(), reinterpret_cast<const PxU32*>(triangles.begin()), triangles.size(), points.begin(), result, rootNodeIndex);
}
}
}
| 2,691 | C++ | 48.851851 | 173 | 0.770346 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayTetrahedralizer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_DELAUNAY_TETRAHEDRALIZER_H
#define EXT_DELAUNAY_TETRAHEDRALIZER_H
#include "foundation/PxArray.h"
#include "foundation/PxVec3.h"
#include "foundation/PxHashSet.h"
#include "GuTetrahedron.h"
#include "ExtVec3.h"
namespace physx
{
namespace Ext
{
using Edge = PxPair<PxI32, PxI32>;
using Tetrahedron = Gu::TetrahedronT<PxI32>;
using Tetrahedron16 = Gu::TetrahedronT<PxI16>;
void buildNeighborhood(const PxArray<Tetrahedron>& tets, PxArray<PxI32>& result);
void buildNeighborhood(const PxI32* tets, PxU32 numTets, PxArray<PxI32>& result);
PX_FORCE_INLINE PxF64 tetVolume(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d)
{
return (-1.0 / 6.0) * (a - d).dot((b - d).cross(c - d));
}
PX_FORCE_INLINE PxF64 tetVolume(const Tetrahedron& tet, const PxArray<PxVec3d>& points)
{
return tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
}
//Returns the intersection (set operation) of two sorted lists
PX_FORCE_INLINE void intersectionOfSortedLists(const PxArray<PxI32>& sorted1, const PxArray<PxI32>& sorted2, PxArray<PxI32>& result)
{
PxU32 a = 0;
PxU32 b = 0;
result.clear();
while (a < sorted1.size() && b < sorted2.size())
{
if (sorted1[a] == sorted2[b])
{
result.pushBack(sorted1[a]);
++a;
++b;
}
else if (sorted1[a] > sorted2[b])
++b;
else
++a;
}
}
PX_FORCE_INLINE bool intersectionOfSortedListsContainsElements(const PxArray<PxI32>& sorted1, const PxArray<PxI32>& sorted2)
{
PxU32 a = 0;
PxU32 b = 0;
while (a < sorted1.size() && b < sorted2.size())
{
if (sorted1[a] == sorted2[b])
return true;
else if (sorted1[a] > sorted2[b])
++b;
else
++a;
}
return false;
}
class BaseTetAnalyzer
{
public:
virtual PxF64 quality(const PxArray<PxI32> tetIndices) const = 0;
virtual PxF64 quality(const PxArray<Tetrahedron> tetrahedraToCheck) const = 0;
virtual bool improved(PxF64 previousQuality, PxF64 newQuality) const = 0;
virtual ~BaseTetAnalyzer() {}
};
class MinimizeMaxAmipsEnergy : public BaseTetAnalyzer
{
const PxArray<PxVec3d>& points;
const PxArray<Tetrahedron>& tetrahedra;
public:
MinimizeMaxAmipsEnergy(const PxArray<PxVec3d>& points_, const PxArray<Tetrahedron>& tetrahedra_) : points(points_), tetrahedra(tetrahedra_)
{}
PxF64 quality(const PxArray<PxI32> tetIndices) const;
PxF64 quality(const PxArray<Tetrahedron> tetrahedraToCheck) const;
bool improved(PxF64 previousQuality, PxF64 newQuality) const;
virtual ~MinimizeMaxAmipsEnergy() {}
private:
PX_NOCOPY(MinimizeMaxAmipsEnergy)
};
class MaximizeMinTetVolume : public BaseTetAnalyzer
{
const PxArray<PxVec3d>& points;
const PxArray<Tetrahedron>& tetrahedra;
public:
MaximizeMinTetVolume(const PxArray<PxVec3d>& points_, const PxArray<Tetrahedron>& tetrahedra_) : points(points_), tetrahedra(tetrahedra_)
{}
PxF64 quality(const PxArray<PxI32> tetIndices) const;
PxF64 quality(const PxArray<Tetrahedron> tetrahedraToCheck) const;
bool improved(PxF64 previousQuality, PxF64 newQuality) const;
virtual ~MaximizeMinTetVolume() {}
private:
PX_NOCOPY(MaximizeMinTetVolume)
};
//Helper class to extract surface triangles from a tetmesh
struct SortedTriangle
{
public:
PxI32 A;
PxI32 B;
PxI32 C;
bool Flipped;
PX_FORCE_INLINE SortedTriangle(PxI32 a, PxI32 b, PxI32 c)
{
A = a; B = b; C = c; Flipped = false;
if (A > B) { PxSwap(A, B); Flipped = !Flipped; }
if (B > C) { PxSwap(B, C); Flipped = !Flipped; }
if (A > B) { PxSwap(A, B); Flipped = !Flipped; }
}
};
struct TriangleHash
{
PX_FORCE_INLINE std::size_t operator()(const SortedTriangle& k) const
{
return k.A ^ k.B ^ k.C;
}
PX_FORCE_INLINE bool equal(const SortedTriangle& first, const SortedTriangle& second) const
{
return first.A == second.A && first.B == second.B && first.C == second.C;
}
};
struct RecoverEdgeMemoryCache
{
PxArray<PxI32> facesStart;
PxHashSet<PxI32> tetsDoneStart;
PxArray<PxI32> resultStart;
PxArray<PxI32> facesEnd;
PxHashSet<PxI32> tetsDoneEnd;
PxArray<PxI32> resultEnd;
};
class StackMemory
{
public:
void clear()
{
faces.forceSize_Unsafe(0);
hashSet.clear();
}
PxArray<PxI32> faces;
PxHashSet<PxI32> hashSet;
};
//Incremental delaunay tetrahedralizer
class DelaunayTetrahedralizer
{
public:
//The bounds specified must contain all points that will get inserted by calling insertPoints.
DelaunayTetrahedralizer(const PxVec3d& min, const PxVec3d& max);
DelaunayTetrahedralizer(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets);
void initialize(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets);
//Inserts a bunch of new points into the tetrahedralization and keeps the delaunay condition satisfied. The new result will
//get stored in the tetrahedra array. Points to insert must already be present in inPoints, the indices of the points to insert
//can be controlled with start and end index (end index is exclusive, start index is inclusive)
void insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end, PxArray<Tetrahedron>& tetrahedra);
bool insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end);
void exportTetrahedra(PxArray<Tetrahedron>& tetrahedra);
bool canCollapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove, PxF64 volumeChangeThreshold = 0.1, BaseTetAnalyzer* tetAnalyzer = NULL);
bool canCollapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB,
PxF64& qualityAfterCollapse, PxF64 volumeChangeThreshold = 0.1, BaseTetAnalyzer* tetAnalyzer = NULL);
void collapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove);
void collapseEdge(PxI32 edgeVertexAToKeep, PxI32 edgeVertexBToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB);
void collectTetsConnectedToVertex(PxI32 vertexIndex, PxArray<PxI32>& tetIds);
void collectTetsConnectedToVertex(PxArray<PxI32>& faces, PxHashSet<PxI32>& tetsDone, PxI32 vertexIndex, PxArray<PxI32>& tetIds);
void collectTetsConnectedToEdge(PxI32 edgeStart, PxI32 edgeEnd, PxArray<PxI32>& tetIds);
PX_FORCE_INLINE const PxVec3d& point(PxI32 index) const { return centeredNormalizedPoints[index]; }
PX_FORCE_INLINE PxU32 numPoints() const { return centeredNormalizedPoints.size(); }
PX_FORCE_INLINE PxArray<PxVec3d>& points() { return centeredNormalizedPoints; }
PX_FORCE_INLINE const PxArray<PxVec3d>& points() const { return centeredNormalizedPoints; }
PxU32 addPoint(const PxVec3d& p)
{
centeredNormalizedPoints.pushBack(p);
vertexToTet.pushBack(-1);
return centeredNormalizedPoints.size() - 1;
}
PX_FORCE_INLINE const Tetrahedron& tetrahedron(PxI32 index) const { return result[index]; }
PX_FORCE_INLINE PxU32 numTetrahedra() const { return result.size(); }
PX_FORCE_INLINE PxArray<Tetrahedron>& tetrahedra() { return result; }
PX_FORCE_INLINE const PxArray<Tetrahedron>& tetrahedra() const { return result; }
void copyInternalPointsTo(PxArray<PxVec3d>& points) { points = centeredNormalizedPoints; }
bool optimizeByFlipping(PxArray<PxI32>& affectedFaces, const BaseTetAnalyzer& qualityAnalyzer);
void insertPointIntoEdge(PxI32 newPointIndex, PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& affectedTets, BaseTetAnalyzer* qualityAnalyzer = NULL);
bool removeEdgeByFlip(PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& tetIndices, BaseTetAnalyzer* qualityAnalyzer = NULL);
void addLockedEdges(const PxArray<Gu::IndexedTriangleT<PxI32>>& triangles);
void addLockedTriangles(const PxArray<Gu::IndexedTriangleT<PxI32>>& triangles);
void clearLockedEdges() { lockedEdges.clear(); }
void clearLockedTriangles() { lockedTriangles.clear(); }
bool recoverEdgeByFlip(PxI32 eStart, PxI32 eEnd, RecoverEdgeMemoryCache& cache);
void generateTetmeshEnforcingEdges(const PxArray<PxVec3d>& trianglePoints, const PxArray<Gu::IndexedTriangleT<PxI32>>& triangles, PxArray<PxArray<PxI32>>& allEdges,
PxArray<PxArray<PxI32>>& pointToOriginalTriangle,
PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets);
private:
PxArray<PxVec3d> centeredNormalizedPoints;
PxArray<PxI32> neighbors;
PxArray<PxI32> unusedTets;
PxArray<PxI32> vertexToTet;
PxArray<Tetrahedron> result;
PxI32 numAdditionalPointsAtBeginning = 4;
PxHashSet<SortedTriangle, TriangleHash> lockedTriangles;
PxHashSet<PxU64> lockedEdges;
StackMemory stackMemory;
PX_NOCOPY(DelaunayTetrahedralizer)
};
struct EdgeWithLength
{
PxI32 A;
PxI32 B;
PxF64 Length;
EdgeWithLength(PxI32 a_, PxI32 b_, PxF64 length_)
{
A = a_;
B = b_;
Length = length_;
}
};
PX_FORCE_INLINE bool operator <(const EdgeWithLength& lhs, const EdgeWithLength& rhs)
{
return lhs.Length < rhs.Length;
}
struct SplitEdge
{
PxI32 A;
PxI32 B;
PxF64 Q;
PxF64 L;
bool InteriorEdge;
SplitEdge(PxI32 a, PxI32 b, PxF64 q, PxF64 l, bool interiorEdge)
{
A = a;
B = b;
Q = q;
L = l;
InteriorEdge = interiorEdge;
}
};
PX_FORCE_INLINE bool operator >(const SplitEdge& lhs, const SplitEdge& rhs)
{
if (lhs.Q == rhs.Q)
return lhs.L > rhs.L;
return lhs.Q > rhs.Q;
}
bool optimizeByCollapsing(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges,
PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints, BaseTetAnalyzer* qualityAnalyzer = NULL);
bool optimizeBySwapping(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges,
const PxArray<PxArray<PxI32>>& pointToOriginalTriangle, BaseTetAnalyzer* qualityAnalyzer);
bool optimizeBySplitting(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, const PxArray<PxArray<PxI32>>& pointToOriginalTriangle,
PxI32 maxPointsToInsert = -1, bool sortByQuality = false, BaseTetAnalyzer* qualityAnalyzer = NULL, PxF64 qualityThreshold = 10);
//Modified tetmesh quality improvement implementation of the method described in https://cs.nyu.edu/~yixinhu/tetwild.pdf Section 3.2 Mesh Improvement
void optimize(DelaunayTetrahedralizer& del, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints,
PxArray<PxVec3d>& optimizedPoints, PxArray<Tetrahedron>& optimizedTets, PxI32 numPasses = 10);
}
}
#endif
| 11,905 | C | 31.798898 | 166 | 0.742041 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetSplitting.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_TET_SPLITTING_H
#define EXT_TET_SPLITTING_H
#include "ExtVec3.h"
#include "foundation/PxArray.h"
#include "foundation/PxHashMap.h"
#include "GuTetrahedron.h"
namespace physx
{
namespace Ext
{
using Edge = PxPair<PxI32, PxI32>;
using Tetrahedron = Gu::TetrahedronT<PxI32>;
//Splits all edges specified in edgesToSplit. The tets are modified in place. The poitns referenced by index in the key-value pari in
//edgesToSplit must already pe present in the points array. This functions guarantees that the tetmesh will remain watertight.
PX_C_EXPORT void PX_CALL_CONV split(PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points, const PxHashMap<PxU64, PxI32>& edgesToSplit);
}
}
#endif
| 2,272 | C | 44.459999 | 142 | 0.769366 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtOctreeTetrahedralizer.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 "ExtOctreeTetrahedralizer.h"
#include "foundation/PxSort.h"
#include "foundation/PxQuat.h"
#include "CmRandom.h"
namespace physx
{
namespace Ext
{
// -------------------------------------------------------------------------------------
static const PxI32 childRelPos[8][3] = { {0,0,0}, {1,0,0},{0,1,0},{1,1,0}, {0,0,1}, {1,0,1},{0,1,1},{1,1,1} };
static const PxI32 cubeCorners[8][3] = { {0,0,0}, {1,0,0},{1,1,0},{0,1,0}, {0,0,1}, {1,0,1},{1,1,1},{0,1,1} };
//static const PxI32 cubeEdges[12][2] = { {0,1}, {1,2},{2,3},{3,0}, {0,4},{1,5},{2,6},{3,7},{4,5},{5,6},{6,7},{7,4} };
static const PxI32 tetFaces[4][3] = { {2,1,0}, {0,1,3}, {1,2,3}, {2,0,3} };
static const PxI32 cubeTets[6][4] = { {0,1,2,5}, {0,4,5,2}, {2,4,5,6}, {4,7,6,3}, {2,6,3,4}, {0,2,3,4} };
static const PxI32 cubeTetNeighbors[6][4] = { {-1,-1,-1,1}, {-1,5,2,0}, {1,4,-1,-1},
{-1,-1,-1,4}, {-1,2,3,5}, {-1,1,4,-1} };
// -------------------------------------------------------------------------------------
OctreeTetrahedralizer::OctreeTetrahedralizer()
{
clear();
}
// -------------------------------------------------------------------------------------
void OctreeTetrahedralizer::clearTets()
{
tetVerts.clear();
tetIds.clear();
firstFreeTet = -1;
currentTetMark = 0;
tetMarks.clear();
tetNeighbors.clear();
renderVerts.clear();
renderTriIds.clear();
firstABBVert = 0;
}
// -------------------------------------------------------------------------------------
void OctreeTetrahedralizer::clear()
{
surfaceVerts.clear();
surfaceTriIds.clear();
tetIds.clear();
tetNeighbors.clear();
cells.clear();
clearTets();
prevClip = -1.0f;
prevScale = -1.0f;
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::createTree()
{
Bounds3 bounds;
bounds.setEmpty();
for (PxI32 i = 0; i < PxI32(surfaceVerts.size()); i++)
{
const PxVec3& v = surfaceVerts[i];
bounds.include(PxVec3d(PxF64(v.x), PxF64(v.y), PxF64(v.z)));
}
bounds.expand(0.01);
PxVec3d dims = bounds.getDimensions();
PxF64 size = PxMax(dims.x, PxMax(dims.y, dims.z));
// create root
cells.resize(1);
cells.front().init();
cells.front().orig = bounds.minimum;
cells.front().size = size;
cells.front().depth = 0;
// insert vertices
PxI32 numVerts = PxI32(surfaceVerts.size());
for (PxI32 i = 0; i < numVerts; i++)
{
treeInsertVert(0, i);
}
}
// -------------------------------------------------------------------------------------
PxI32 OctreeTetrahedralizer::Cell::getChildNr(const PxVec3d& p)
{
if (firstChild < 0)
return -1;
PxI32 nr = 0;
if (p.x > orig.x + 0.5 * size) nr |= 1;
if (p.y > orig.y + 0.5 * size) nr |= 2;
if (p.z > orig.z + 0.5 * size) nr |= 4;
return firstChild + nr;
}
// -------------------------------------------------------------------------------------
void OctreeTetrahedralizer::treeInsertVert(PxI32 cellNr, PxI32 vertNr)
{
// inner node
if (cells[cellNr].firstChild >= 0)
{
treeInsertVert(cells[cellNr].getChildNr(surfaceVerts[vertNr]), vertNr);
return;
}
// add
vertsOfCell.add(cellNr, vertNr);
cells[cellNr].numVerts++;
if (cells[cellNr].numVerts <= maxVertsPerCell ||
cells[cellNr].depth >= maxTreeDepth)
return;
// split
PxI32 firstChild = cells.size();
cells[cellNr].firstChild = firstChild;
cells.resize(cells.size() + 8);
for (PxI32 i = 0; i < 8; i++)
{
Cell& child = cells[firstChild + i];
child.init();
child.depth = cells[cellNr].depth + 1;
child.size = cells[cellNr].size * 0.5;
child.orig = cells[cellNr].orig + PxVec3d(
childRelPos[i][0] * child.size,
childRelPos[i][1] * child.size,
childRelPos[i][2] * child.size);
}
PxI32 iterator, id;
vertsOfCell.initIteration(cellNr, iterator);
while (vertsOfCell.iterate(id, iterator))
treeInsertVert(cells[cellNr].getChildNr(surfaceVerts[id]), id);
vertsOfCell.removeAll(cellNr);
cells[cellNr].numVerts = 0;
}
// -----------------------------------------------------------------------------------
static PxVec3d jitter(const PxVec3d& p, Cm::RandomR250& random)
{
PxF64 eps = 0.001;
return PxVec3d(
p.x - eps + 2.0 * eps * PxF64(random.rand(0.0f, 1.0f)),
p.y - eps + 2.0 * eps * PxF64(random.rand(0.0f, 1.0f)),
p.z - eps + 2.0 * eps * PxF64(random.rand(0.0f, 1.0f)));
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::createTetVerts(bool includeOctreeNodes)
{
tetVerts.clear();
insideTester.init(surfaceVerts.begin(), PxI32(surfaceVerts.size()),
surfaceTriIds.begin(), PxI32(surfaceTriIds.size()) / 3);
for (PxI32 i = 0; i < PxI32(surfaceVerts.size()); i++)
{
const PxVec3& v = surfaceVerts[i];
tetVerts.pushBack(PxVec3d(PxF64(v.x), PxF64(v.y), PxF64(v.z)));
}
if (includeOctreeNodes)
{
PxArray<PxVec3d> treeVerts;
for (PxI32 i = 0; i < PxI32(cells.size()); i++)
{
PxF64 s = cells[i].size;
for (PxI32 j = 0; j < 8; j++) {
PxVec3d p = cells[i].orig + PxVec3d(
s * cubeCorners[j][0],
s * cubeCorners[j][1],
s * cubeCorners[j][2]);
treeVerts.pushBack(p);
}
}
// remove duplicates
PxF64 eps = 1e-8;
struct Ref
{
PxF64 d;
PxI32 vertNr;
bool operator < (const Ref& r) const
{
return d < r.d;
}
};
PxI32 numTreeVerts = PxI32(treeVerts.size());
PxArray<Ref> refs(numTreeVerts);
for (PxI32 i = 0; i < numTreeVerts; i++)
{
PxVec3d& p = treeVerts[i];
refs[i].d = p.x + 0.3 * p.y + 0.1 * p.z;
refs[i].vertNr = i;
}
PxSort(refs.begin(), refs.size());
PxArray<bool> duplicate(numTreeVerts, false);
PxI32 nr = 0;
Cm::RandomR250 random(0);
while (nr < numTreeVerts)
{
Ref& r = refs[nr];
nr++;
if (duplicate[r.vertNr])
continue;
PxVec3d& p = treeVerts[r.vertNr];
PxVec3d v = jitter(p, random);
if (insideTester.isInside(PxVec3(PxReal(v.x), PxReal(v.y), PxReal(v.z))))
tetVerts.pushBack(jitter(p, random));
PxI32 i = nr;
while (i < numTreeVerts && fabs(refs[i].d - r.d) < eps)
{
PxVec3d& q = treeVerts[refs[i].vertNr];
if ((p - q).magnitude() < eps)
duplicate[refs[i].vertNr] = true;
i++;
}
}
}
}
// -----------------------------------------------------------------------------------
PxVec3d OctreeTetrahedralizer::getTetCenter(PxI32 tetNr) const
{
return (tetVerts[tetIds[4 * tetNr]] +
tetVerts[tetIds[4 * tetNr + 1]] +
tetVerts[tetIds[4 * tetNr + 2]] +
tetVerts[tetIds[4 * tetNr + 3]]) * 0.25;
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::treeInsertTet(PxI32 tetNr)
{
PxVec3d center = getTetCenter(tetNr);
PxI32 cellNr = 0;
while (cellNr >= 0)
{
Cell& c = cells[cellNr];
if (c.closestTetNr < 0)
c.closestTetNr = tetNr;
else
{
PxVec3d cellCenter = c.orig + PxVec3d(c.size, c.size, c.size) * 0.5;
PxVec3d closest = getTetCenter(c.closestTetNr);
if ((cellCenter - center).magnitudeSquared() < (cellCenter - closest).magnitudeSquared())
c.closestTetNr = tetNr;
}
cellNr = cells[cellNr].getChildNr(center);
}
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::treeRemoveTet(PxI32 tetNr)
{
PxVec3d center = getTetCenter(tetNr);
PxI32 cellNr = 0;
while (cellNr >= 0)
{
Cell& c = cells[cellNr];
if (c.closestTetNr == tetNr)
c.closestTetNr = -1;
cellNr = cells[cellNr].getChildNr(center);
}
}
void resizeFast(PxArray<PxI32>& arr, PxU32 newSize, PxI32 value = 0)
{
if (newSize < arr.size())
arr.removeRange(newSize, arr.size() - newSize);
else
{
while (arr.size() < newSize)
arr.pushBack(value);
}
}
// -----------------------------------------------------------------------------------
PxI32 OctreeTetrahedralizer::getNewTetNr()
{
PxI32 newTetNr;
if (firstFreeTet >= 0)
{
// take from free list
newTetNr = firstFreeTet;
firstFreeTet = tetIds[4 * firstFreeTet];
}
else
{
// append
newTetNr = PxI32(tetIds.size()) / 4;
resizeFast(tetIds, tetIds.size() + 4);
resizeFast(tetMarks, newTetNr + 1, 0);
resizeFast(tetNeighbors, tetIds.size(), -1);
}
return newTetNr;
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::removeTetNr(PxI32 tetNr)
{
// add to free list
tetIds[4 * tetNr] = firstFreeTet;
tetIds[4 * tetNr + 1] = -1;
tetIds[4 * tetNr + 2] = -1;
tetIds[4 * tetNr + 3] = -1;
firstFreeTet = tetNr;
}
// -----------------------------------------------------------------------------------
bool OctreeTetrahedralizer::findSurroundingTet(const PxVec3d& p, PxI32 startTetNr, PxI32& tetNr)
{
currentTetMark++;
tetNr = startTetNr;
bool found = false;
while (!found)
{
if (tetNr < 0 || tetMarks[tetNr] == currentTetMark) // circular, something went wrong
break;
tetMarks[tetNr] = currentTetMark;
PxVec3d c = getTetCenter(tetNr);
PxI32* ids = &tetIds[4 * tetNr];
PxF64 minT = DBL_MAX;
PxI32 minFaceNr = -1;
for (PxI32 i = 0; i < 4; i++)
{
const PxVec3d& p0 = tetVerts[ids[tetFaces[i][0]]];
const PxVec3d& p1 = tetVerts[ids[tetFaces[i][1]]];
const PxVec3d& p2 = tetVerts[ids[tetFaces[i][2]]];
PxVec3d n = (p1 - p0).cross(p2 - p0);
n = n.getNormalized();
PxF64 hp = (p - p0).dot(n);
PxF64 hc = (c - p0).dot(n);
PxF64 t = hp - hc;
if (t == 0.0)
continue;
t = -hc / t; // time when c -> p hits the face
if (t >= 0.0 && t < minT) { // in front and new min
minT = t;
minFaceNr = i;
}
}
if (minT >= 1.0)
found = true;
else
tetNr = tetNeighbors[4 * tetNr + minFaceNr];
}
return found;
}
// -----------------------------------------------------------------------------------
bool OctreeTetrahedralizer::findSurroundingTet(const PxVec3d& p, PxI32& tetNr)
{
PxI32 startTet = 0;
PxI32 cellNr = 0;
while (cellNr >= 0)
{
if (cells[cellNr].closestTetNr >= 0)
startTet = cells[cellNr].closestTetNr;
cellNr = cells[cellNr].getChildNr(p);
}
return findSurroundingTet(p, startTet, tetNr);
}
// -----------------------------------------------------------------------------------
static PxVec3d getCircumCenter(PxVec3d& p0, PxVec3d& p1, PxVec3d& p2, PxVec3d& p3)
{
PxVec3d b = p1 - p0;
PxVec3d c = p2 - p0;
PxVec3d d = p3 - p0;
PxF64 det = 2.0 * (b.x*(c.y*d.z - c.z*d.y) - b.y*(c.x*d.z - c.z*d.x) + b.z*(c.x*d.y - c.y*d.x));
if (det == 0.0)
return p0;
else
{
PxVec3d v = c.cross(d)*b.dot(b) + d.cross(b)*c.dot(c) + b.cross(c)*d.dot(d);
v /= det;
return p0 + v;
}
}
// -----------------------------------------------------------------------------------
bool OctreeTetrahedralizer::meshInsertTetVert(PxI32 vertNr)
{
const PxVec3d& p = tetVerts[vertNr];
PxI32 surroundingTetNr;
if (!findSurroundingTet(p, surroundingTetNr))
return false;
// find violating tets
violatingTets.clear();
stack.clear();
currentTetMark++;
stack.pushBack(surroundingTetNr);
while (!stack.empty())
{
PxI32 tetNr = stack.back();
stack.popBack();
if (tetMarks[tetNr] == currentTetMark)
continue;
tetMarks[tetNr] = currentTetMark;
violatingTets.pushBack(tetNr);
for (PxI32 i = 0; i < 4; i++)
{
PxI32 n = tetNeighbors[4 * tetNr + i];
if (n < 0 || tetMarks[n] == currentTetMark)
continue;
// Delaunay condition test
PxI32* ids = &tetIds[4 * n];
PxVec3d c = getCircumCenter(tetVerts[ids[0]], tetVerts[ids[1]], tetVerts[ids[2]], tetVerts[ids[3]]);
PxF64 r2 = (tetVerts[ids[0]] - c).magnitudeSquared();
if ((p - c).magnitudeSquared() < r2)
stack.pushBack(n);
}
}
// remove old tets, create new ones
edges.clear();
Edge e;
for (PxI32 i = 0; i < PxI32(violatingTets.size()); i++)
{
PxI32 tetNr = violatingTets[i];
// copy information before we delete it
PxI32 ids[4], ns[4];
for (PxI32 j = 0; j < 4; j++) {
ids[j] = tetIds[4 * tetNr + j];
ns[j] = tetNeighbors[4 * tetNr + j];
}
// delete the tetrahedron
treeRemoveTet(tetNr);
removeTetNr(tetNr);
// visit neighbors
for (PxI32 j = 0; j < 4; j++) {
PxI32 n = ns[j];
if (n < 0 || tetMarks[n] != currentTetMark)
{
// no neighbor or neighbor is not-violating -> we are facing the border
// create new tetrahedron
PxI32 newTetNr = getNewTetNr();
PxI32 id0 = ids[tetFaces[j][2]];
PxI32 id1 = ids[tetFaces[j][1]];
PxI32 id2 = ids[tetFaces[j][0]];
tetIds[4 * newTetNr] = id0;
tetIds[4 * newTetNr + 1] = id1;
tetIds[4 * newTetNr + 2] = id2;
tetIds[4 * newTetNr + 3] = vertNr;
treeInsertTet(newTetNr);
tetNeighbors[4 * newTetNr] = n;
if (n >= 0)
{
for (PxI32 k = 0; k < 4; k++)
{
if (tetNeighbors[4 * n + k] == tetNr)
tetNeighbors[4 * n + k] = newTetNr;
}
}
// will set the neighbors among the new tetrahedra later
tetNeighbors[4 * newTetNr + 1] = -1;
tetNeighbors[4 * newTetNr + 2] = -1;
tetNeighbors[4 * newTetNr + 3] = -1;
e.init(id0, id1, newTetNr, 1); edges.pushBack(e);
e.init(id1, id2, newTetNr, 2); edges.pushBack(e);
e.init(id2, id0, newTetNr, 3); edges.pushBack(e);
}
} // next neighbor
} // next violating tetrahedron
// fix neighbors
PxSort(edges.begin(), edges.size());
PxI32 nr = 0;
while (nr < PxI32(edges.size()))
{
Edge& e0 = edges[nr];
nr++;
if (nr < PxI32(edges.size()) && edges[nr] == e0)
{
Edge& e1 = edges[nr];
tetNeighbors[4 * e0.tetNr + e0.faceNr] = e1.tetNr;
tetNeighbors[4 * e1.tetNr + e1.faceNr] = e0.tetNr;
nr++;
}
}
return true;
}
// -----------------------------------------------------------------------------------
static PxF64 tetQuality(const PxVec3d& p0, const PxVec3d& p1, const PxVec3d& p2, const PxVec3d& p3)
{
PxVec3d d0 = p1 - p0;
PxVec3d d1 = p2 - p0;
PxVec3d d2 = p3 - p0;
PxVec3d d3 = p2 - p1;
PxVec3d d4 = p3 - p2;
PxVec3d d5 = p1 - p3;
PxF64 s0 = d0.magnitudeSquared();
PxF64 s1 = d1.magnitudeSquared();
PxF64 s2 = d2.magnitudeSquared();
PxF64 s3 = d3.magnitudeSquared();
PxF64 s4 = d4.magnitudeSquared();
PxF64 s5 = d5.magnitudeSquared();
PxF64 ms = (s0 + s1 + s2 + s3 + s4 + s5) / 6.0;
PxF64 rms = sqrt(ms);
static const PxF64 s = 12.0 / sqrt(2.0);
PxF64 vol = d0.dot(d1.cross(d2)) / 6.0;
return s * vol / (rms * rms * rms); // 1.0 for regular tetrahedron
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::pruneTets()
{
insideTester.init(surfaceVerts.begin(), PxI32(surfaceVerts.size()),
surfaceTriIds.begin(), PxI32(surfaceTriIds.size()) / 3);
static PxF64 minQuality = 0.01;
PxI32 numTets = tetIds.size() / 4;
PxI32 num = 0;
for (PxI32 i = 0; i < numTets; i++)
{
bool remove = false;
PxI32* ids = &tetIds[4 * i];
for (PxI32 j = 0; j < 4; j++)
{
if (ids[j] >= firstABBVert)
remove = true;
}
if (ids[0] < 0 || ids[1] < 0 || ids[2] < 0 || ids[3] < 0)
remove = true;
if (!remove)
{
PxVec3d c = getTetCenter(i);
if (!insideTester.isInside(PxVec3(PxReal(c.x), PxReal(c.y), PxReal(c.z))))
remove = true;
if (tetQuality(tetVerts[ids[0]], tetVerts[ids[1]],
tetVerts[ids[2]], tetVerts[ids[3]]) < minQuality)
continue;
}
if (remove)
continue;
for (PxI32 j = 0; j < 4; j++)
tetIds[4 * num + j] = ids[j];
num++;
}
tetIds.resize(4 * num);
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::createTetMesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds,
bool includeOctreeNodes, PxI32 _maxVertsPerCell, PxI32 _maxTreeDepth)
{
this->surfaceVerts = verts;
surfaceTriIds.resize(triIds.size());
for (PxU32 i = 0; i < triIds.size(); i++)
this->surfaceTriIds[i] = triIds[i];
this->maxVertsPerCell = _maxVertsPerCell;
this->maxTreeDepth = _maxTreeDepth;
createTree();
clearTets();
if (cells.empty())
return;
createTetVerts(includeOctreeNodes);
if (tetVerts.empty())
return;
for (PxI32 i = 0; i < PxI32(cells.size()); i++)
cells[i].closestTetNr = -1;
// create aabb tets
Bounds3 bounds;
bounds.setEmpty();
for (PxI32 i = 0; i < PxI32(tetVerts.size()); i++)
bounds.include(tetVerts[i]);
bounds.expand(bounds.getDimensions().magnitude() * 0.1);
firstABBVert = PxI32(tetVerts.size());
PxVec3d dims = bounds.getDimensions();
for (PxI32 i = 0; i < 8; i++)
{
tetVerts.pushBack(bounds.minimum + PxVec3d(
cubeCorners[i][0] * dims.x,
cubeCorners[i][1] * dims.y,
cubeCorners[i][2] * dims.z));
}
for (PxI32 i = 0; i < 6; i++)
{
for (PxI32 j = 0; j < 4; j++)
{
tetIds.pushBack(firstABBVert + cubeTets[i][j]);
tetNeighbors.pushBack(cubeTetNeighbors[i][j]);
}
treeInsertTet(i);
}
tetMarks.resize(6, 0);
for (PxI32 i = 0; i < firstABBVert; i++)
{
meshInsertTetVert(i);
}
pruneTets();
renderTriIds.clear();
renderVerts.clear();
}
// -----------------------------------------------------------------------------------
void OctreeTetrahedralizer::readBack(PxArray<PxVec3> &outputTetVerts, PxArray<PxU32> &outputTetIds)
{
outputTetVerts.resize(tetVerts.size());
for (PxU32 i = 0; i < tetVerts.size(); i++)
{
PxVec3d &v = tetVerts[i];
outputTetVerts[i] = PxVec3(PxReal(v.x), PxReal(v.y), PxReal(v.z));
}
outputTetIds.resize(tetIds.size());
for (PxU32 i = 0; i < tetIds.size(); i++)
outputTetIds[i] = PxU32(tetIds[i]);
}
}
}
| 20,051 | C++ | 26.356071 | 120 | 0.536632 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtVec3.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_VEC3_H
#define EXT_VEC3_H
#include "foundation/PxMath.h"
#include "foundation/PxVec3.h"
namespace physx
{
namespace Ext
{
// ---------------------------------------------------------------------------------
struct Bounds3 {
Bounds3() {}
Bounds3(const PxVec3d &min, const PxVec3d &max) : minimum(min), maximum(max) {}
void setEmpty() {
minimum = PxVec3d(PX_MAX_F64, PX_MAX_F64, PX_MAX_F64);
maximum = PxVec3d(-PX_MAX_F64, -PX_MAX_F64, -PX_MAX_F64);
}
PxVec3d getDimensions() const {
return maximum - minimum;
}
void include(const PxVec3d &p) {
minimum = minimum.minimum(p);
maximum = maximum.maximum(p);
}
void include(const Bounds3 &b) {
minimum = minimum.minimum(b.minimum);
maximum = maximum.maximum(b.maximum);
}
void expand(double d) {
minimum -= PxVec3d(d, d, d);
maximum += PxVec3d(d, d, d);
}
PxVec3d minimum, maximum;
};
}
}
#endif
| 2,507 | C | 34.323943 | 86 | 0.694456 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayTetrahedralizer.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 "ExtDelaunayTetrahedralizer.h"
#include "foundation/PxSort.h"
#include "foundation/PxHashMap.h"
#include "ExtUtilities.h"
namespace physx
{
namespace Ext
{
using Triangle = Gu::IndexedTriangleT<PxI32>;
//http://tizian.cs.uni-bonn.de/publications/BaudsonKlein.pdf Page 44
static const PxI32 neighborFaces[4][3] = { { 0, 1, 2 }, { 0, 3, 1 }, { 0, 2, 3 }, { 1, 3, 2 } };
static const PxI32 tetTip[4] = { 3, 2, 1, 0 };
struct Plane
{
PxVec3d normal;
PxF64 planeD;
PX_FORCE_INLINE Plane(const PxVec3d& n, PxF64 d) : normal(n), planeD(d)
{ }
PX_FORCE_INLINE Plane(const PxVec3d& n, const PxVec3d& pointOnPlane) : normal(n)
{
planeD = -pointOnPlane.dot(normal);
}
PX_FORCE_INLINE Plane(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c)
{
normal = (b - a).cross(c - a);
PxF64 norm = normal.magnitude();
normal /= norm;
planeD = -a.dot(normal);
}
PX_FORCE_INLINE PxF64 signedDistance(const PxVec3d& p)
{
return normal.dot(p) + planeD;
}
PX_FORCE_INLINE PxF64 unsignedDistance(const PxVec3d& p)
{
return PxAbs(signedDistance(p));
}
};
DelaunayTetrahedralizer::DelaunayTetrahedralizer(const PxVec3d& min, const PxVec3d& max)
{
for(PxI32 i = 0; i < 4; ++i)
neighbors.pushBack(-1);
PxF64 radius = 1.1 * 0.5 * (max - min).magnitude();
PxF64 scaledRadius = 6 * radius;
centeredNormalizedPoints.pushBack(PxVec3d(-scaledRadius, -scaledRadius, -scaledRadius));
centeredNormalizedPoints.pushBack(PxVec3d(scaledRadius, scaledRadius, -scaledRadius));
centeredNormalizedPoints.pushBack(PxVec3d(-scaledRadius, scaledRadius, scaledRadius));
centeredNormalizedPoints.pushBack(PxVec3d(scaledRadius, -scaledRadius, scaledRadius));
numAdditionalPointsAtBeginning = 4;
result.pushBack(Tetrahedron(0, 1, 2, 3));
for (PxI32 i = 0; i < 4; ++i)
vertexToTet.pushBack(0);
}
void buildNeighborhood(const PxI32* tets, PxU32 numTets, PxArray<PxI32>& result)
{
PxU32 l = 4 * numTets;
result.clear();
result.resize(l, -1);
PxHashMap<SortedTriangle, PxI32, TriangleHash> faces;
for (PxU32 i = 0; i < numTets; ++i)
{
const PxI32* tet = &tets[4 * i];
if (tet[0] < 0)
continue;
for (PxI32 j = 0; j < 4; ++j)
{
SortedTriangle tri(tet[neighborFaces[j][0]], tet[neighborFaces[j][1]], tet[neighborFaces[j][2]]);
if (const PxPair<const SortedTriangle, PxI32>* ptr = faces.find(tri))
{
if (ptr->second < 0)
{
//PX_ASSERT(false); //Invalid tetmesh since a face is shared by more than 2 tetrahedra
continue;
}
result[4 * i + j] = ptr->second;
result[ptr->second] = 4 * i + j;
faces[tri] = -1;
}
else
faces.insert(tri, 4 * i + j);
}
}
}
void buildNeighborhood(const PxArray<Tetrahedron>& tets, PxArray<PxI32>& result)
{
buildNeighborhood(reinterpret_cast<const PxI32*>(tets.begin()), tets.size(), result);
}
bool shareFace(const Tetrahedron& t1, const Tetrahedron& t2)
{
PxI32 counter = 0;
if (t1.contains(t2[0])) ++counter;
if (t1.contains(t2[1])) ++counter;
if (t1.contains(t2[2])) ++counter;
if (t1.contains(t2[3])) ++counter;
if (counter == 4)
PX_ASSERT(false);
return counter == 3;
}
//Keep for debugging & verification
void validateNeighborhood(const PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors)
{
PxI32 borderCounter = 0;
for (PxU32 i = 0; i < neighbors.size(); ++i)
if (neighbors[i] == -1)
++borderCounter;
//if (borderCounter != 4)
// throw new Exception();
PxArray<PxI32> n;
buildNeighborhood(tets, n);
for (PxU32 i = 0; i < n.size(); ++i)
{
if (n[i] < 0)
continue;
if (n[i] != neighbors[i])
PX_ASSERT(false);
}
for (PxU32 i = 0; i < neighbors.size(); ++i)
{
if (neighbors[i] < 0)
continue;
Tetrahedron tet1 = tets[i >> 2];
Tetrahedron tet2 = tets[neighbors[i] >> 2];
if (!shareFace(tet1, tet2))
PX_ASSERT(false);
PxI32 face1 = i & 3;
SortedTriangle tri1(tet1[neighborFaces[face1][0]], tet1[neighborFaces[face1][1]], tet1[neighborFaces[face1][2]]);
PxI32 face2 = neighbors[i] & 3;
SortedTriangle tri2(tet2[neighborFaces[face2][0]], tet2[neighborFaces[face2][1]], tet2[neighborFaces[face2][2]]);
if (tri1.A != tri2.A || tri1.B != tri2.B || tri1.C != tri2.C)
PX_ASSERT(false);
}
}
void buildVertexToTet(const PxArray<Tetrahedron>& tets, PxI32 numPoints, PxArray<PxI32>& result)
{
result.clear();
result.resize(numPoints, -1);
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
result[tet[0]] = i;
result[tet[1]] = i;
result[tet[2]] = i;
result[tet[3]] = i;
}
}
DelaunayTetrahedralizer::DelaunayTetrahedralizer(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets)
{
initialize(points, tets);
}
void DelaunayTetrahedralizer::initialize(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets)
{
clearLockedEdges();
clearLockedTriangles();
centeredNormalizedPoints = points;
result = tets;
numAdditionalPointsAtBeginning = 0;
buildNeighborhood(tets, neighbors);
buildVertexToTet(tets, points.size(), vertexToTet);
for (PxU32 i = 0; i < tets.size(); ++i)
if (tets[i][0] < 0)
unusedTets.pushBack(i);
}
PX_FORCE_INLINE PxF64 inSphere(const PxVec3d& pa, const PxVec3d& pb, const PxVec3d& pc, const PxVec3d& pd, const PxVec3d& candidiate)
{
PxF64 aex = pa.x - candidiate.x;
PxF64 bex = pb.x - candidiate.x;
PxF64 cex = pc.x - candidiate.x;
PxF64 dex = pd.x - candidiate.x;
PxF64 aey = pa.y - candidiate.y;
PxF64 bey = pb.y - candidiate.y;
PxF64 cey = pc.y - candidiate.y;
PxF64 dey = pd.y - candidiate.y;
PxF64 aez = pa.z - candidiate.z;
PxF64 bez = pb.z - candidiate.z;
PxF64 cez = pc.z - candidiate.z;
PxF64 dez = pd.z - candidiate.z;
PxF64 ab = aex * bey - bex * aey;
PxF64 bc = bex * cey - cex * bey;
PxF64 cd = cex * dey - dex * cey;
PxF64 da = dex * aey - aex * dey;
PxF64 ac = aex * cey - cex * aey;
PxF64 bd = bex * dey - dex * bey;
PxF64 abc = aez * bc - bez * ac + cez * ab;
PxF64 bcd = bez * cd - cez * bd + dez * bc;
PxF64 cda = cez * da + dez * ac + aez * cd;
PxF64 dab = dez * ab + aez * bd + bez * da;
PxF64 alift = aex * aex + aey * aey + aez * aez;
PxF64 blift = bex * bex + bey * bey + bez * bez;
PxF64 clift = cex * cex + cey * cey + cez * cez;
PxF64 dlift = dex * dex + dey * dey + dez * dez;
return (dlift * abc - clift * dab) + (blift * cda - alift * bcd);
}
PX_FORCE_INLINE bool isDelaunay(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& neighbors, PxI32 faceId)
{
PxI32 neighborPointer = neighbors[faceId];
if (neighborPointer < 0)
return true; //Border faces are always delaunay
PxI32 tet1Id = faceId >> 2;
PxI32 tet2Id = neighborPointer >> 2;
const PxI32* localTriangle1 = neighborFaces[faceId & 3];
PxI32 localTip1 = tetTip[faceId & 3];
PxI32 localTip2 = tetTip[neighborPointer & 3];
Tetrahedron tet1 = tets[tet1Id];
Tetrahedron tet2 = tets[tet2Id];
return inSphere(points[tet1[localTriangle1[0]]], points[tet1[localTriangle1[1]]], points[tet1[localTriangle1[2]]], points[tet1[localTip1]], points[tet2[localTip2]]) > 0;
}
PX_FORCE_INLINE PxI32 storeNewTet(PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, const Tetrahedron& tet, PxArray<PxI32>& unusedTets)
{
if (unusedTets.size() == 0)
{
PxU32 tetId = tets.size();
tets.pushBack(tet);
for (PxI32 i = 0; i < 4; ++i)
neighbors.pushBack(-1);
return tetId;
}
else
{
PxI32 tetId = unusedTets[unusedTets.size() - 1];
unusedTets.remove(unusedTets.size() - 1);
tets[tetId] = tet;
return tetId;
}
}
PX_FORCE_INLINE PxI32 localFaceId(PxI32 localA, PxI32 localB, PxI32 localC)
{
PxI32 result = localA + localB + localC - 3;
PX_ASSERT(result >= 0 || result <= 3);
return result;
}
PX_FORCE_INLINE PxI32 localFaceId(const Tetrahedron& tet, PxI32 globalA, PxI32 globalB, PxI32 globalC)
{
PxI32 result = localFaceId(tet.indexOf(globalA), tet.indexOf(globalB), tet.indexOf(globalC));
return result;
}
PX_FORCE_INLINE void setFaceNeighbor(PxArray<PxI32>& neighbors, PxI32 tetId, PxI32 faceId, PxI32 newNeighborTet, PxI32 newNeighborFace)
{
neighbors[4 * tetId + faceId] = 4 * newNeighborTet + newNeighborFace;
neighbors[4 * newNeighborTet + newNeighborFace] = 4 * tetId + faceId;
}
PX_FORCE_INLINE void setFaceNeighbor(PxArray<PxI32>& neighbors, PxI32 tetId, PxI32 faceId, PxI32 newNeighbor)
{
neighbors[4 * tetId + faceId] = newNeighbor;
if (newNeighbor >= 0)
neighbors[newNeighbor] = 4 * tetId + faceId;
}
PX_FORCE_INLINE void setFaceNeighbor(PxArray<PxI32>& affectedFaces, PxArray<PxI32>& neighbors, PxI32 tetId, PxI32 faceId, PxI32 newNeighbor)
{
setFaceNeighbor(neighbors, tetId, faceId, newNeighbor);
affectedFaces.pushBack(newNeighbor);
}
void flip1to4(PxI32 pointToInsert, PxI32 tetId, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces)
{
const Tetrahedron origTet = tets[tetId];
Tetrahedron tet(origTet[0], origTet[1], origTet[2], pointToInsert);
tets[tetId] = tet;
Tetrahedron tet2(origTet[0], origTet[3], origTet[1], pointToInsert);
Tetrahedron tet3(origTet[0], origTet[2], origTet[3], pointToInsert);
Tetrahedron tet4(origTet[1], origTet[3], origTet[2], pointToInsert);
PxI32 tet2Id = storeNewTet(tets, neighbors, tet2, unusedTets);
PxI32 tet3Id = storeNewTet(tets, neighbors, tet3, unusedTets);
PxI32 tet4Id = storeNewTet(tets, neighbors, tet4, unusedTets);
PxI32 n1 = neighbors[4 * tetId + localFaceId(origTet, origTet[0], origTet[1], origTet[2])];
PxI32 n2 = neighbors[4 * tetId + localFaceId(origTet, origTet[0], origTet[1], origTet[3])];
PxI32 n3 = neighbors[4 * tetId + localFaceId(origTet, origTet[0], origTet[2], origTet[3])];
PxI32 n4 = neighbors[4 * tetId + localFaceId(origTet, origTet[1], origTet[2], origTet[3])];
setFaceNeighbor(affectedFaces, neighbors, tetId, localFaceId(tet, origTet[0], origTet[1], origTet[2]), n1);
setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, origTet[0], origTet[1], origTet[3]), n2);
setFaceNeighbor(affectedFaces, neighbors, tet3Id, localFaceId(tet3, origTet[0], origTet[2], origTet[3]), n3);
setFaceNeighbor(affectedFaces, neighbors, tet4Id, localFaceId(tet4, origTet[1], origTet[2], origTet[3]), n4);
setFaceNeighbor(neighbors, tetId, localFaceId(tet, pointToInsert, origTet[0], origTet[1]), tet2Id, localFaceId(tet2, pointToInsert, origTet[0], origTet[1]));
setFaceNeighbor(neighbors, tetId, localFaceId(tet, pointToInsert, origTet[0], origTet[2]), tet3Id, localFaceId(tet3, pointToInsert, origTet[0], origTet[2]));
setFaceNeighbor(neighbors, tetId, localFaceId(tet, pointToInsert, origTet[1], origTet[2]), tet4Id, localFaceId(tet4, pointToInsert, origTet[1], origTet[2]));
setFaceNeighbor(neighbors, tet2Id, localFaceId(tet2, pointToInsert, origTet[0], origTet[3]), tet3Id, localFaceId(tet3, pointToInsert, origTet[0], origTet[3]));
setFaceNeighbor(neighbors, tet2Id, localFaceId(tet2, pointToInsert, origTet[1], origTet[3]), tet4Id, localFaceId(tet4, pointToInsert, origTet[1], origTet[3]));
setFaceNeighbor(neighbors, tet3Id, localFaceId(tet3, pointToInsert, origTet[2], origTet[3]), tet4Id, localFaceId(tet4, pointToInsert, origTet[2], origTet[3]));
vertexToTet[tet[0]] = tetId; vertexToTet[tet[1]] = tetId; vertexToTet[tet[2]] = tetId; vertexToTet[tet[3]] = tetId;
vertexToTet[tet2[0]] = tet2Id; vertexToTet[tet2[1]] = tet2Id; vertexToTet[tet2[2]] = tet2Id; vertexToTet[tet2[3]] = tet2Id;
vertexToTet[tet3[0]] = tet3Id; vertexToTet[tet3[1]] = tet3Id; vertexToTet[tet3[2]] = tet3Id; vertexToTet[tet3[3]] = tet3Id;
vertexToTet[tet4[0]] = tet4Id; vertexToTet[tet4[1]] = tet4Id; vertexToTet[tet4[2]] = tet4Id; vertexToTet[tet4[3]] = tet4Id;
}
bool flip2to3(PxI32 tet1Id, PxI32 tet2Id,
PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces,
PxI32 tip1, PxI32 tip2, const Triangle& tri)
{
// 2->3 flip
Tetrahedron tet1(tip2, tip1, tri[0], tri[1]);
Tetrahedron tet2(tip2, tip1, tri[1], tri[2]);
Tetrahedron tet3(tip2, tip1, tri[2], tri[0]);
PxI32 n1 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[0], tri[1], tip1)];
PxI32 n2 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[0], tri[1], tip2)];
if (n1 >= 0 && (n1 >> 2) == (n2 >> 2))
{
if (Tetrahedron::identical(tet1, tets[n1 >> 2]))
return false;
}
PxI32 n3 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[1], tri[2], tip1)];
PxI32 n4 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[1], tri[2], tip2)];
if (n3 >= 0 && (n3 >> 2) == (n4 >> 2))
{
if (Tetrahedron::identical(tet2, tets[n3 >> 2]))
return false;
}
PxI32 n5 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[2], tri[0], tip1)];
PxI32 n6 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[2], tri[0], tip2)];
if (n5 >= 0 && (n5 >> 2) == (n6 >> 2))
{
if (Tetrahedron::identical(tet3, tets[n5 >> 2]))
return false;
}
PxI32 tet3Id = storeNewTet(tets, neighbors, tet3, unusedTets);
setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, tri[0], tri[1], tip1), n1);
setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, tri[0], tri[1], tip2), n2);
setFaceNeighbor(neighbors, tet1Id, localFaceId(tet1, tri[0], tip1, tip2), tet3Id, localFaceId(tet3, tri[0], tip1, tip2)); //Interior face
setFaceNeighbor(neighbors, tet1Id, localFaceId(tet1, tri[1], tip1, tip2), tet2Id, localFaceId(tet2, tri[1], tip1, tip2)); //Interior face
setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, tri[1], tri[2], tip1), n3);
setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, tri[1], tri[2], tip2), n4);
setFaceNeighbor(neighbors, tet2Id, localFaceId(tet2, tri[2], tip1, tip2), tet3Id, localFaceId(tet3, tri[2], tip1, tip2)); //Interior face
setFaceNeighbor(affectedFaces, neighbors, tet3Id, localFaceId(tet3, tri[2], tri[0], tip1), n5);
setFaceNeighbor(affectedFaces, neighbors, tet3Id, localFaceId(tet3, tri[2], tri[0], tip2), n6);
tets[tet1Id] = tet1;
tets[tet2Id] = tet2;
vertexToTet[tet1[0]] = tet1Id; vertexToTet[tet1[1]] = tet1Id; vertexToTet[tet1[2]] = tet1Id; vertexToTet[tet1[3]] = tet1Id;
vertexToTet[tet2[0]] = tet2Id; vertexToTet[tet2[1]] = tet2Id; vertexToTet[tet2[2]] = tet2Id; vertexToTet[tet2[3]] = tet2Id;
vertexToTet[tet3[0]] = tet3Id; vertexToTet[tet3[1]] = tet3Id; vertexToTet[tet3[2]] = tet3Id; vertexToTet[tet3[3]] = tet3Id;
return true;
}
bool flip3to2(PxI32 tet1Id, PxI32 tet2Id, PxI32 tet3Id,
PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces,
PxI32 tip1, PxI32 tip2, PxI32 reflexEdgeA, PxI32 reflexEdgeB, PxI32 nonReflexTrianglePoint)
{
// 3->2 flip
Tetrahedron tet1(tip1, tip2, reflexEdgeA, nonReflexTrianglePoint);
Tetrahedron tet2(tip2, tip1, reflexEdgeB, nonReflexTrianglePoint);
PxI32 n1 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], reflexEdgeA, tip1, nonReflexTrianglePoint)];
PxI32 n2 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], reflexEdgeA, tip2, nonReflexTrianglePoint)];
PxI32 n3 = neighbors[4 * tet3Id + localFaceId(tets[tet3Id], reflexEdgeA, tip1, tip2)];
if (n1 >= 0 && n2 >= 0 && (n1 >> 2) == (n2 >> 2) && Tetrahedron::identical(tet1, tets[n1 >> 2]))
return false;
if (n1 >= 0 && n3 >= 0 && (n1 >> 2) == (n3 >> 2) && Tetrahedron::identical(tet1, tets[n1 >> 2]))
return false;
if (n2 >= 0 && n3 >= 0 && (n2 >> 2) == (n3 >> 2) && Tetrahedron::identical(tet1, tets[n2 >> 2]))
return false;
PxI32 n4 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], reflexEdgeB, tip1, nonReflexTrianglePoint)];
PxI32 n5 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], reflexEdgeB, tip2, nonReflexTrianglePoint)];
PxI32 n6 = neighbors[4 * tet3Id + localFaceId(tets[tet3Id], reflexEdgeB, tip1, tip2)];
if (n4 >= 0 && n5 >= 0 && (n4 >> 2) == (n5 >> 2) && Tetrahedron::identical(tet2, tets[n4 >> 2]))
return false;
if (n4 >= 0 && n6 >= 0 && (n4 >> 2) == (n6 >> 2) && Tetrahedron::identical(tet2, tets[n4 >> 2]))
return false;
if (n5 >= 0 && n6 >= 0 && (n5 >> 2) == (n6 >> 2) && Tetrahedron::identical(tet2, tets[n5 >> 2]))
return false;
setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, reflexEdgeA, tip1, nonReflexTrianglePoint), n1);
setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, reflexEdgeA, tip2, nonReflexTrianglePoint), n2);
setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, reflexEdgeA, tip1, tip2), n3);
setFaceNeighbor(neighbors, tet1Id, localFaceId(tet1, nonReflexTrianglePoint, tip1, tip2), tet2Id, localFaceId(tet2, nonReflexTrianglePoint, tip1, tip2)); //Interior face // Marker (*)
setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, reflexEdgeB, tip1, nonReflexTrianglePoint), n4);
setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, reflexEdgeB, tip2, nonReflexTrianglePoint), n5);
setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, reflexEdgeB, tip1, tip2), n6);
tets[tet1Id] = tet1;
tets[tet2Id] = tet2;
tets[tet3Id] = Tetrahedron(-1, -1, -1, -1);
for (PxI32 i = 0; i < 4; ++i)
neighbors[4 * tet3Id + i] = -2;
unusedTets.pushBack(tet3Id);
vertexToTet[tet1[0]] = tet1Id; vertexToTet[tet1[1]] = tet1Id; vertexToTet[tet1[2]] = tet1Id; vertexToTet[tet1[3]] = tet1Id;
vertexToTet[tet2[0]] = tet2Id; vertexToTet[tet2[1]] = tet2Id; vertexToTet[tet2[2]] = tet2Id; vertexToTet[tet2[3]] = tet2Id;
return true;
}
PX_FORCE_INLINE PxF64 orient3D(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d)
{
return (a - d).dot((b - d).cross(c - d));
}
PX_FORCE_INLINE bool edgeIsLocked(const PxHashSet<PxU64>& lockedEdges, int edgeA, int edgeB)
{
return lockedEdges.contains(key(edgeA, edgeB));
}
PX_FORCE_INLINE bool faceIsLocked(const PxHashSet<SortedTriangle, TriangleHash>& lockedTriangles, int triA, int triB, int triC)
{
return lockedTriangles.contains(SortedTriangle(triA, triB, triC));
}
void flip(const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxI32 faceId, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces,
const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges)
{
PxI32 neighborPointer = neighbors[faceId];
if (neighborPointer < 0)
return;
PxI32 tet1Id = faceId >> 2;
const PxI32* localTriangle1 = neighborFaces[faceId & 3];
Tetrahedron tet1 = tets[tet1Id];
Triangle tri(tet1[localTriangle1[0]], tet1[localTriangle1[1]], tet1[localTriangle1[2]]);
PxI32 localTip1 = tetTip[faceId & 3];
PxI32 localTip2 = tetTip[neighborPointer & 3];
PxI32 tip1 = tet1[localTip1];
PxI32 tet2Id = neighborPointer >> 2;
Tetrahedron tet2 = tets[tet2Id];
PxI32 tip2 = tet2[localTip2];
PX_ASSERT(tet2.contains(tri[0]) && tet2.contains(tri[1]) && tet2.contains(tri[2]));
PxI32 face1 = -1;
PxI32 face2 = -1;
PxI32 numReflexEdges = 0;
PxI32 reflexEdgeA = -1;
PxI32 reflexEdgeB = -1;
PxI32 nonReflexTrianglePoint = -1;
PxF64 ab = orient3D(points[tri[0]], points[tri[1]], points[tip1], points[tip2]);
if (ab < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[0], localTriangle1[1], localTip1); reflexEdgeA = tri[0]; reflexEdgeB = tri[1]; nonReflexTrianglePoint = tri[2]; face2 = localFaceId(tet2, tri[0], tri[1], tip2); }
PxF64 bc = orient3D(points[tri[1]], points[tri[2]], points[tip1], points[tip2]);
if (bc < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[1], localTriangle1[2], localTip1); reflexEdgeA = tri[1]; reflexEdgeB = tri[2]; nonReflexTrianglePoint = tri[0]; face2 = localFaceId(tet2, tri[1], tri[2], tip2); }
PxF64 ca = orient3D(points[tri[2]], points[tri[0]], points[tip1], points[tip2]);
if (ca < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[2], localTriangle1[0], localTip1); reflexEdgeA = tri[2]; reflexEdgeB = tri[0]; nonReflexTrianglePoint = tri[1]; face2 = localFaceId(tet2, tri[2], tri[0], tip2); }
if (numReflexEdges == 0)
{
if (!faceIsLocked(lockedFaces, tri[0], tri[1], tri[2]))
flip2to3(tet1Id, tet2Id, neighbors, vertexToTet, tets, unusedTets, affectedFaces, tip1, tip2, tri);
}
else if (numReflexEdges == 1)
{
PxI32 candidate1 = neighbors[4 * tet1Id + face1] >> 2;
PxI32 candidate2 = neighbors[4 * tet2Id + face2] >> 2;
if (candidate1 == candidate2 && candidate1 >= 0)
{
if (!edgeIsLocked(lockedEdges, reflexEdgeA, reflexEdgeB) &&
!faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint) &&
!faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip1) &&
!faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip2))
flip3to2(tet1Id, tet2Id, candidate1, neighbors, vertexToTet, tets, unusedTets, affectedFaces, tip1, tip2, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint);
}
}
else if (numReflexEdges == 2)
{
//Cannot do anything
}
else if (numReflexEdges == 3)
{
//Something is wrong if we end up here - maybe there are degenerate tetrahedra or issues due to numerical rounding
}
}
void flip(PxArray<PxI32>& faces, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, const PxArray<PxVec3d>& points,
PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces,
const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges)
{
while (faces.size() > 0)
{
PxI32 faceId = faces.popBack();
if (faceId < 0)
continue;
if (isDelaunay(points, tets, neighbors, faceId))
continue;
affectedFaces.clear();
flip(points, tets, neighbors, vertexToTet, faceId, unusedTets, affectedFaces, lockedFaces, lockedEdges);
for (PxU32 j = 0; j < affectedFaces.size(); ++j)
if (faces.find(affectedFaces[j]) == faces.end())
faces.pushBack(affectedFaces[j]);
}
}
void insertAndFlip(PxI32 pointToInsert, PxI32 tetId, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, const PxArray<PxVec3d>& points,
PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces,
const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges)
{
flip1to4(pointToInsert, tetId, neighbors, vertexToTet, tets, unusedTets, affectedFaces);
PxArray<PxI32> stack;
for (PxU32 j = 0; j < affectedFaces.size(); ++j)
if (stack.find(affectedFaces[j]) == stack.end())
stack.pushBack(affectedFaces[j]);
flip(stack, neighbors, vertexToTet, points, tets, unusedTets, affectedFaces, lockedFaces, lockedEdges);
}
PxI32 searchAll(const PxVec3d& p, const PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points)
{
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
PxI32 j = 0;
for (; j < 4; j++)
{
Plane plane(points[tet[neighborFaces[j][0]]], points[tet[neighborFaces[j][1]]], points[tet[neighborFaces[j][2]]]);
PxF64 distP = plane.signedDistance(p);
if (distP < 0)
break;
}
if (j == 4)
return i;
}
return -1;
}
bool runDelaunay(const PxArray<PxVec3d>& points, PxI32 start, PxI32 end, PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<PxI32>& unusedTets,
const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges)
{
PxI32 tetId = 0;
PxArray<PxI32> affectedFaces;
for (PxI32 i = start; i < end; ++i)
{
const PxVec3d p = points[i];
if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z))
continue;
if (tetId < 0 || unusedTets.find(tetId) != unusedTets.end())
tetId = 0;
while (unusedTets.find(tetId) != unusedTets.end())
++tetId;
PxU32 counter = 0;
bool tetLocated = false;
while (!tetLocated)
{
const Tetrahedron& tet = tets[tetId];
const PxVec3d center = (points[tet[0]] + points[tet[1]] + points[tet[2]] + points[tet[3]]) * 0.25;
PxF64 minDist = DBL_MAX;
PxI32 minFaceNr = -1;
for (PxI32 j = 0; j < 4; j++)
{
Plane plane(points[tet[neighborFaces[j][0]]], points[tet[neighborFaces[j][1]]], points[tet[neighborFaces[j][2]]]);
PxF64 distP = plane.signedDistance(p);
PxF64 distCenter = plane.signedDistance(center);
PxF64 delta = distP - distCenter;
if (delta == 0.0)
continue;
delta = -distCenter / delta;
if (delta >= 0.0 && delta < minDist)
{
minDist = delta;
minFaceNr = j;
}
}
if (minDist >= 1.0)
tetLocated = true;
else
{
tetId = neighbors[4 * tetId + minFaceNr] >> 2;
if (tetId < 0)
{
tetId = searchAll(p, tets, points);
tetLocated = true;
}
}
++counter;
if (counter > tets.size())
{
tetId = searchAll(p, tets, points);
if (tetId < 0)
return false;
tetLocated = true;
}
}
insertAndFlip(i, tetId, neighbors, vertexToTet, points, tets, unusedTets, affectedFaces, lockedFaces, lockedEdges);
}
return true;
}
bool DelaunayTetrahedralizer::insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end)
{
for (PxI32 i = start; i < end; ++i)
{
centeredNormalizedPoints.pushBack(inPoints[i]);
vertexToTet.pushBack(-1);
}
if (!runDelaunay(centeredNormalizedPoints, start + numAdditionalPointsAtBeginning, end + numAdditionalPointsAtBeginning, result, neighbors, vertexToTet, unusedTets, lockedTriangles, lockedEdges))
return false;
return true;
}
void DelaunayTetrahedralizer::exportTetrahedra(PxArray<Tetrahedron>& tetrahedra)
{
tetrahedra.clear();
for (PxU32 i = 0; i < result.size(); ++i)
{
const Tetrahedron& tet = result[i];
if (tet[0] >= numAdditionalPointsAtBeginning && tet[1] >= numAdditionalPointsAtBeginning && tet[2] >= numAdditionalPointsAtBeginning && tet[3] >= numAdditionalPointsAtBeginning)
tetrahedra.pushBack(Tetrahedron(tet[0] - numAdditionalPointsAtBeginning, tet[1] - numAdditionalPointsAtBeginning, tet[2] - numAdditionalPointsAtBeginning, tet[3] - numAdditionalPointsAtBeginning));
}
}
void DelaunayTetrahedralizer::insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end, PxArray<Tetrahedron>& tetrahedra)
{
insertPoints(inPoints, start, end);
exportTetrahedra(tetrahedra);
}
//Code below this line is for tetmesh manipulation and not directly required to generate a Delaunay tetrahedron mesh. It is used to impmrove the quality of a tetrahedral mesh.
//https://cs.nyu.edu/~panozzo/papers/SLIM-2016.pdf
PxF64 evaluateAmipsEnergyPow3(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d)
{
PxF64 x1 = a.x + d.x - 2.0 * b.x;
PxF64 x2 = a.x + b.x + d.x - 3.0 * c.x;
PxF64 y1 = a.y + d.y - 2.0 * b.y;
PxF64 y2 = a.y + b.y + d.y - 3.0 * c.y;
PxF64 z1 = a.z + d.z - 2.0 * b.z;
PxF64 z2 = a.z + b.z + d.z - 3.0 * c.z;
PxF64 f = (1.0 / (PxSqrt(3.0) * PxSqrt(6.0))) *
((a.x - d.x) * (y1 * z2 - y2 * z1) -
(a.y - d.y) * (z2 * x1 - x2 * z1) +
(a.z - d.z) * (y2 * x1 - y1 * x2));
if (f >= 0)
return 0.25 * DBL_MAX;
PxF64 g = a.x * (b.x + c.x + d.x - 3.0 * a.x) +
a.y * (b.y + c.y + d.y - 3.0 * a.y) +
a.z * (b.z + c.z + d.z - 3.0 * a.z) +
b.x * (a.x + c.x + d.x - 3.0 * b.x) +
b.y * (a.y + c.y + d.y - 3.0 * b.y) +
b.z * (a.z + c.z + d.z - 3.0 * b.z) +
c.x * x2 +
c.y * y2 +
c.z * z2 +
d.x * (a.x + b.x + c.x - 3.0 * d.x) +
d.y * (a.y + b.y + c.y - 3.0 * d.y) +
d.z * (a.z + b.z + c.z - 3.0 * d.z);
return -0.125 * (g * g * g) / (f * f);
//return -0.5 * PxPow(f * f, -1.0 / 3.0) * g;
}
PX_FORCE_INLINE PxF64 pow(const PxF64 a, const PxF64 b)
{
return PxF64(PxPow(PxF32(a), PxF32(b)));
}
PX_FORCE_INLINE PxF64 evaluateAmipsEnergy(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d)
{
return pow(evaluateAmipsEnergyPow3(a, b, c, d), 1.0 / 3.0);
}
PxF64 maxEnergyPow3(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets)
{
PxF64 maxEnergy = 0;
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
PxF64 e = evaluateAmipsEnergyPow3(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
if (e > maxEnergy)
maxEnergy = e;
}
return maxEnergy;
}
PX_FORCE_INLINE PxF64 maxEnergy(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets)
{
return pow(maxEnergyPow3(points, tets), 1.0 / 3.0);
}
PxF64 maxEnergyPow3(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& tetIds)
{
PxF64 maxEnergy = 0;
for (PxU32 i = 0; i < tetIds.size(); ++i)
{
const Tetrahedron& tet = tets[tetIds[i]];
if (tet[0] < 0)
continue;
PxF64 e = evaluateAmipsEnergyPow3(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
if (e > maxEnergy)
maxEnergy = e;
}
return maxEnergy;
}
PxF64 minAbsTetVolume(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets)
{
PxF64 minVol = DBL_MAX;
for (PxU32 i = 0; i < tets.size(); ++i) {
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
PxF64 vol = PxAbs(tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]));
if (vol < minVol)
minVol = vol;
}
return minVol;
}
PxF64 minTetVolume(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets)
{
PxF64 minVol = DBL_MAX;
for (PxU32 i = 0; i < tets.size(); ++i) {
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
PxF64 vol = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
if (vol < minVol)
minVol = vol;
}
return minVol;
}
PxF64 minTetVolume(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& indices)
{
PxF64 minVol = DBL_MAX;
for (PxU32 i = 0; i < indices.size(); ++i) {
const Tetrahedron& tet = tets[indices[i]];
if (tet[0] < 0)
continue;
PxF64 vol = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
if (vol < minVol)
minVol = vol;
}
return minVol;
}
PxF64 MinimizeMaxAmipsEnergy::quality(const PxArray<PxI32> tetIndices) const
{
return maxEnergyPow3(points, tetrahedra, tetIndices);
}
PxF64 MinimizeMaxAmipsEnergy::quality(const PxArray<Tetrahedron> tetrahedraToCheck) const
{
return maxEnergyPow3(points, tetrahedraToCheck);
}
bool MinimizeMaxAmipsEnergy::improved(PxF64 previousQuality, PxF64 newQuality) const
{
return newQuality < previousQuality; //Minimize quality for Amips energy
}
PxF64 MaximizeMinTetVolume::quality(const PxArray<PxI32> tetIndices) const
{
return minTetVolume(points, tetrahedra, tetIndices);
}
PxF64 MaximizeMinTetVolume::quality(const PxArray<Tetrahedron> tetrahedraToCheck) const
{
return minTetVolume(points, tetrahedraToCheck);
}
bool MaximizeMinTetVolume::improved(PxF64 previousQuality, PxF64 newQuality) const
{
return newQuality > previousQuality; //Maximize quality for min volume
}
void fixVertexToTet(PxArray<PxI32>& vertexToTet, const PxArray<PxI32>& newTetIds, const PxArray<Tetrahedron>& tets)
{
for (PxU32 i = 0; i < newTetIds.size(); ++i)
{
PxI32 id = newTetIds[i];
const Tetrahedron& tet = tets[id];
if (tet[0] < 0)
continue;
while (PxU32(tet[0]) >= vertexToTet.size()) vertexToTet.pushBack(-1);
while (PxU32(tet[1]) >= vertexToTet.size()) vertexToTet.pushBack(-1);
while (PxU32(tet[2]) >= vertexToTet.size()) vertexToTet.pushBack(-1);
while (PxU32(tet[3]) >= vertexToTet.size()) vertexToTet.pushBack(-1);
vertexToTet[tet[0]] = id; vertexToTet[tet[1]] = id; vertexToTet[tet[2]] = id; vertexToTet[tet[3]] = id;
}
}
void fixNeighborhoodLocally(const PxArray<PxI32>& removedTets, const PxArray<PxI32>& tetIndices, const PxArray<Tetrahedron>& tets,
PxArray<PxI32>& neighborhood, PxArray<PxI32>* affectedFaces = NULL)
{
for (PxU32 k = 0; k < removedTets.size(); ++k)
{
PxI32 i = removedTets[k];
for (PxI32 j = 0; j < 4; ++j)
{
PxI32 faceId = 4 * i + j;
neighborhood[faceId] = -1;
if (affectedFaces != NULL && affectedFaces->find(faceId) == affectedFaces->end())
affectedFaces->pushBack(faceId);
}
}
PxHashMap<SortedTriangle, PxI32, TriangleHash> faces;
for(PxU32 k = 0; k< tetIndices.size(); ++k)
{
PxI32 i = tetIndices[k];
if (i < 0)
continue;
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
for (PxI32 j = 0; j < 4; ++j)
{
SortedTriangle tri(tet[neighborFaces[j][0]], tet[neighborFaces[j][1]], tet[neighborFaces[j][2]]);
if (const PxPair<const SortedTriangle, PxI32>* ptr = faces.find(tri))
{
neighborhood[4 * i + j] = ptr->second;
neighborhood[ptr->second] = 4 * i + j;
}
else
faces.insert(tri, 4 * i + j);
}
}
//validateNeighborhood(tets, neighborhood);
}
void collectTetsConnectedToVertex(PxArray<PxI32>& faces, PxHashSet<PxI32>& tetsDone, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& tetNeighbors, const PxArray<PxI32>& vertexToTet,
PxI32 vertexIndex, PxArray<PxI32>& tetIds, PxI32 secondVertexId = -1, PxI32 thirdVertexId = -1)
{
tetIds.clear();
int tetIndex = vertexToTet[vertexIndex];
if (tetIndex < 0)
return; //Free floating point
if ((secondVertexId < 0 || tets[tetIndex].contains(secondVertexId)) && (thirdVertexId < 0 || tets[tetIndex].contains(thirdVertexId)))
tetIds.pushBack(tetIndex);
faces.clear();
tetsDone.clear();
for (int i = 0; i < 4; ++i)
{
if (tetNeighbors[4 * tetIndex + i] >= 0)
faces.pushBack(4 * tetIndex + i);
}
tetsDone.insert(tetIndex);
while (faces.size() > 0)
{
PxI32 faceId = faces.popBack();
int tetId = tetNeighbors[faceId] >> 2;
if (tetId < 0 || tetIds.find(tetId) != tetIds.end())
continue;
const Tetrahedron& tet = tets[tetId];
int id = tet.indexOf(vertexIndex);
if (id >= 0)
{
if ((secondVertexId < 0 || tets[tetId].contains(secondVertexId)) && (thirdVertexId < 0 || tets[tetId].contains(thirdVertexId)))
tetIds.pushBack(tetId);
const PxI32* f = neighborFaces[id];
for (int i = 0; i < 3; ++i)
{
int candidate = 4 * tetId + f[i];
if (tetsDone.insert(tetNeighbors[candidate] >> 2))
{
int otherTetId = tetNeighbors[candidate] >> 2;
if (otherTetId >= 0 && tets[otherTetId].contains(vertexIndex))
faces.pushBack(candidate);
}
}
}
}
}
void DelaunayTetrahedralizer::collectTetsConnectedToVertex(PxI32 vertexIndex, PxArray<PxI32>& tetIds)
{
stackMemory.clear();
physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, vertexIndex, tetIds, -1, -1);
}
void DelaunayTetrahedralizer::collectTetsConnectedToVertex(PxArray<PxI32>& faces, PxHashSet<PxI32>& tetsDone, PxI32 vertexIndex, PxArray<PxI32>& tetIds)
{
faces.clear();
tetsDone.clear();
physx::Ext::collectTetsConnectedToVertex(faces, tetsDone, result, neighbors, vertexToTet, vertexIndex, tetIds);
}
void DelaunayTetrahedralizer::collectTetsConnectedToEdge(PxI32 edgeStart, PxI32 edgeEnd, PxArray<PxI32>& tetIds)
{
if (edgeStart < edgeEnd)
PxSwap(edgeStart, edgeEnd);
stackMemory.clear();
physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeStart, tetIds, edgeEnd);
}
PX_FORCE_INLINE bool containsDuplicates(PxI32 a, PxI32 b, PxI32 c, PxI32 d)
{
return a == b || a == c || a == d || b == c || b == d || c == d;
}
//Returns true if the volume of a tet would become negative if a vertex it contains would get replaced by another one
bool tetFlipped(const Tetrahedron& tet, PxI32 vertexToReplace, PxI32 replacement, const PxArray<PxVec3d>& points, PxF64 volumeChangeThreshold = 0.1)
{
PxF64 volumeBefore = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
PxI32 a = tet[0] == vertexToReplace ? replacement : tet[0];
PxI32 b = tet[1] == vertexToReplace ? replacement : tet[1];
PxI32 c = tet[2] == vertexToReplace ? replacement : tet[2];
PxI32 d = tet[3] == vertexToReplace ? replacement : tet[3];
if (containsDuplicates(a, b, c, d))
return false;
PxF64 volume = tetVolume(points[a], points[b], points[c], points[d]);
if (volume < 0)
return true;
if (PxAbs(volume / volumeBefore) < volumeChangeThreshold)
return true;
return false;
}
PX_FORCE_INLINE Tetrahedron getTet(const Tetrahedron& tet, PxI32 vertexToReplace, PxI32 replacement)
{
return Tetrahedron(tet[0] == vertexToReplace ? replacement : tet[0],
tet[1] == vertexToReplace ? replacement : tet[1],
tet[2] == vertexToReplace ? replacement : tet[2],
tet[3] == vertexToReplace ? replacement : tet[3]);
}
PX_FORCE_INLINE bool containsDuplicates(const Tetrahedron& tet)
{
return tet[0] == tet[1] || tet[0] == tet[2] || tet[0] == tet[3] || tet[1] == tet[2] || tet[1] == tet[3] || tet[2] == tet[3];
}
//Returns true if a tetmesh's edge, defined by vertex indices keep and remove, can be collapsed without leading to an invalid tetmesh topology
bool canCollapseEdge(PxI32 keep, PxI32 remove, const PxArray<PxVec3d>& points,
const PxArray<PxI32>& tetsConnectedToKeepVertex, const PxArray<PxI32>& tetsConnectedToRemoveVertex, const PxArray<Tetrahedron>& allTet,
PxF64& qualityAfterCollapse, PxF64 volumeChangeThreshold = 0.1, BaseTetAnalyzer* tetAnalyzer = NULL)
{
const PxArray<PxI32>& tets = tetsConnectedToRemoveVertex;
//If a tet would get a negative volume due to the edge collapse, then this edge is not collapsible
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = allTet[tets[i]];
if (tet[0] < 0)
return false;
if (tetFlipped(tet, remove, keep, points, volumeChangeThreshold))
return false;
}
PxHashMap<SortedTriangle, PxI32, TriangleHash> triangles;
PxHashSet<PxI32> candidates;
for (PxU32 i = 0; i < tets.size(); ++i)
candidates.insert(tets[i]);
const PxArray<PxI32>& tets2 = tetsConnectedToKeepVertex;
for (PxU32 i = 0; i < tets2.size(); ++i)
if (allTet[tets2[i]][0] >= 0)
candidates.insert(tets2[i]);
PxArray<PxI32> affectedTets;
affectedTets.reserve(candidates.size());
PxArray<Tetrahedron> remainingTets;
remainingTets.reserve(candidates.size());
//If a tet-face would get referenced by more than 2 tetrahedra due to the edge collapse, then this edge is not collapsible
for (PxHashSet<PxI32>::Iterator iter = candidates.getIterator(); !iter.done(); ++iter)
{
PxI32 tetRef = *iter;
affectedTets.pushBack(tetRef);
Tetrahedron tet = getTet(allTet[tetRef], remove, keep);
if (containsDuplicates(tet))
continue;
remainingTets.pushBack(tet);
for (PxU32 j = 0; j < 4; ++j)
{
SortedTriangle tri(tet[neighborFaces[j][0]], tet[neighborFaces[j][1]], tet[neighborFaces[j][2]]);
if (const PxPair<const SortedTriangle, PxI32>* ptr = triangles.find(tri))
triangles[tri] = ptr->second + 1;
else
triangles.insert(tri, 1);
}
}
for (PxHashMap<SortedTriangle, PxI32, TriangleHash>::Iterator iter = triangles.getIterator(); !iter.done(); ++iter)
if (iter->second > 2)
return false;
if (tetAnalyzer == NULL)
return true;
qualityAfterCollapse = tetAnalyzer->quality(remainingTets);
return tetAnalyzer->improved(tetAnalyzer->quality(affectedTets), qualityAfterCollapse);
}
bool DelaunayTetrahedralizer::canCollapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove, PxF64 volumeChangeThreshold, BaseTetAnalyzer* tetAnalyzer)
{
PxF64 qualityAfterCollapse;
PxArray<PxI32> tetsA, tetsB;
stackMemory.clear();
physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToKeep, tetsA);
stackMemory.clear();
physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToRemove, tetsB);
return canCollapseEdge(edgeVertexToKeep, edgeVertexToRemove, tetsA, tetsB, qualityAfterCollapse, volumeChangeThreshold, tetAnalyzer);
}
bool DelaunayTetrahedralizer::canCollapseEdge(PxI32 edgeVertexAToKeep, PxI32 edgeVertexBToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB,
PxF64& qualityAfterCollapse, PxF64 volumeChangeThreshold, BaseTetAnalyzer* tetAnalyzer)
{
return physx::Ext::canCollapseEdge(edgeVertexAToKeep, edgeVertexBToRemove, centeredNormalizedPoints,
tetsConnectedToA, //physx::Ext::collectTetsConnectedToVertex(result, neighbors, vertexToTet, edgeVertexAToKeep),
tetsConnectedToB, //physx::Ext::collectTetsConnectedToVertex(result, neighbors, vertexToTet, edgeVertexBToRemove),
result, qualityAfterCollapse, volumeChangeThreshold, tetAnalyzer);
}
void collapseEdge(PxI32 keep, PxI32 remove, const PxArray<PxI32>& tetsConnectedToKeepVertex, const PxArray<PxI32>& tetsConnectedToRemoveVertex,
PxArray<Tetrahedron>& allTets, PxArray<PxI32>& neighborhood, PxArray<PxI32>& vertexToTet, PxArray<PxI32>& unusedTets, PxArray<PxI32>& changedTets)
{
PxArray<PxI32> removedTets;
changedTets.clear();
const PxArray<PxI32>& tets = tetsConnectedToRemoveVertex;
for (PxI32 i = tets.size() - 1; i >= 0; --i)
{
PxI32 tetId = tets[i];
Tetrahedron tet = allTets[tetId];
tet.replace(remove, keep);
if (containsDuplicates(tet))
{
for (PxU32 j = 0; j < 4; ++j)
{
if (vertexToTet[tet[j]] == tetId) vertexToTet[tet[j]] = -1;
tet[j] = -1;
}
removedTets.pushBack(tetId);
unusedTets.pushBack(tetId);
}
else
{
changedTets.pushBack(tetId);
}
allTets[tetId] = tet;
}
for (PxU32 i = 0; i < tetsConnectedToKeepVertex.size(); ++i)
{
PxI32 id = tetsConnectedToKeepVertex[i];
if (removedTets.find(id) == removedTets.end())
changedTets.pushBack(id);
}
for (PxU32 i = 0; i < removedTets.size(); ++i)
{
PxI32 id = removedTets[i];
for (PxI32 j = 0; j < 4; ++j)
{
PxI32 n = neighborhood[4 * id + j];
if (n >= 0)
neighborhood[n] = -1;
}
}
fixNeighborhoodLocally(removedTets, changedTets, allTets, neighborhood);
fixVertexToTet(vertexToTet, changedTets, allTets);
vertexToTet[remove] = -1;
}
void DelaunayTetrahedralizer::collapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove)
{
PxArray<PxI32> changedTets;
PxArray<PxI32> keepTetIds;
PxArray<PxI32> removeTetIds;
stackMemory.clear();
physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToKeep, keepTetIds);
stackMemory.clear();
physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToRemove, removeTetIds);
physx::Ext::collapseEdge(edgeVertexToKeep, edgeVertexToRemove,
keepTetIds,
removeTetIds,
result, neighbors, vertexToTet, unusedTets, changedTets);
}
void DelaunayTetrahedralizer::collapseEdge(PxI32 edgeVertexAToKeep, PxI32 edgeVertexBToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB)
{
PxArray<PxI32> changedTets;
physx::Ext::collapseEdge(edgeVertexAToKeep, edgeVertexBToRemove,
tetsConnectedToA, tetsConnectedToB,
result, neighbors, vertexToTet, unusedTets, changedTets);
}
bool buildRing(const PxArray<Edge>& edges, PxArray<PxI32>& result)
{
result.reserve(edges.size() + 1);
const Edge& first = edges[0];
result.pushBack(first.first);
result.pushBack(first.second);
PxU32 currentEdge = 0;
PxI32 connector = first.second;
for (PxU32 j = 1; j < edges.size(); ++j)
{
for (PxU32 i = 1; i < edges.size(); ++i)
{
if (i == currentEdge)
continue;
const Edge& e = edges[i];
if (e.first == connector)
{
currentEdge = i;
result.pushBack(e.second);
connector = e.second;
}
else if (e.second == connector)
{
currentEdge = i;
result.pushBack(e.first);
connector = e.first;
}
if (connector == result[0])
{
result.remove(result.size() - 1);
if (result.size() != edges.size())
{
result.clear();
return false; //Multiple segments - unexpected input
}
return true; //Cyclic
}
}
}
result.clear();
return false;
}
void addRange(PxHashSet<PxI32>& set, const PxArray<PxI32>& list)
{
for (PxU32 i = 0; i < list.size(); ++i)
set.insert(list[i]);
}
static Edge createEdge(PxI32 x, PxI32 y, bool swap)
{
if (swap)
return Edge(y, x);
else
return Edge(x, y);
}
Edge getOtherEdge(const Tetrahedron& tet, PxI32 x, PxI32 y)
{
x = tet.indexOf(x);
y = tet.indexOf(y);
bool swap = x > y;
if (swap)
PxSwap(x, y);
if (x == 0 && y == 1) return createEdge(tet[2], tet[3], swap);
if (x == 0 && y == 2) return createEdge(tet[3], tet[1], swap);
if (x == 0 && y == 3) return createEdge(tet[1], tet[2], swap);
if (x == 1 && y == 2) return createEdge(tet[0], tet[3], swap);
if (x == 1 && y == 3) return createEdge(tet[2], tet[0], swap);
if (x == 2 && y == 3) return createEdge(tet[0], tet[1], swap);
return Edge(-1, -1);
}
bool removeEdgeByFlip(PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& faces, PxHashSet<PxI32>& hashset, PxArray<PxI32>& tetIndices,
PxArray<Tetrahedron>& tets, PxArray<PxVec3d>& pts, PxArray<PxI32>& unusedTets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet,
BaseTetAnalyzer* qualityAnalyzer = NULL)
{
//validateNeighborhood(tets, neighbors);
PxArray<Edge> ringEdges;
ringEdges.reserve(tetIndices.size());
for (PxU32 i = 0; i < tetIndices.size(); ++i)
ringEdges.pushBack(getOtherEdge(tets[tetIndices[i]], edgeA, edgeB));
PxArray<PxI32> ring;
buildRing(ringEdges, ring);
if (ring.size() == 0)
return false;
PxArray<PxI32> ringCopy(ring);
const PxVec3d& a = pts[edgeA];
const PxVec3d& b = pts[edgeB];
PxArray<Tetrahedron> newTets;
newTets.reserve(ring.size() * 2);
PxArray<Triangle> newFaces;
while (ring.size() >= 3)
{
PxF64 shortestDist = DBL_MAX;
PxI32 id = -1;
for (PxI32 i = 0; i < PxI32(ring.size()); ++i)
{
const PxVec3d& s = pts[ring[(i - 1 + ring.size()) % ring.size()]];
const PxVec3d& middle = pts[ring[i]];
const PxVec3d& e = pts[ring[(i + 1) % ring.size()]];
const PxF64 d = (s - e).magnitudeSquared();
if (d < shortestDist)
{
const PxF64 vol1 = tetVolume(s, middle, e, b);
const PxF64 vol2 = tetVolume(a, s, middle, e);
if (vol1 > 0 && vol2 > 0)
{
shortestDist = d;
id = i;
}
}
}
if (id < 0)
return false;
{
const PxI32& s = ring[(id - 1 + ring.size()) % ring.size()];
const PxI32& middle = ring[id];
const PxI32& e = ring[(id + 1) % ring.size()];
newTets.pushBack(Tetrahedron(s, middle, e, edgeB));
newTets.pushBack(Tetrahedron(edgeA, s, middle, e));
newFaces.pushBack(Triangle(s, middle, e));
if (ring.size() > 3)
{
newFaces.pushBack(Triangle(s, e, edgeA));
newFaces.pushBack(Triangle(s, e, edgeB));
}
}
ring.remove(id);
}
//Analyze and decide if operation should be done
if (qualityAnalyzer != NULL && !qualityAnalyzer->improved(qualityAnalyzer->quality(tetIndices), qualityAnalyzer->quality(newTets)))
return false;
PxArray<PxI32> newTetIds;
for (PxU32 i = 0; i < tetIndices.size(); ++i)
{
for (PxI32 j = 0; j < 4; ++j)
{
PxI32 id = 4 * tetIndices[i] + j;
PxI32 neighborTet = neighbors[id] >> 2;
if (neighborTet >= 0 && tetIndices.find(neighborTet) == tetIndices.end() && newTetIds.find(neighborTet) == newTetIds.end())
newTetIds.pushBack(neighborTet);
}
}
PxHashSet<PxI32> set;
PxArray<PxI32> tetIds;
collectTetsConnectedToVertex(faces, hashset, tets, neighbors, vertexToTet, edgeA, tetIds);
addRange(set, tetIds);
faces.forceSize_Unsafe(0);
hashset.clear();
tetIds.forceSize_Unsafe(0);
collectTetsConnectedToVertex(faces, hashset, tets, neighbors, vertexToTet, edgeB, tetIds);
addRange(set, tetIds);
for (PxU32 i = 0; i < ringCopy.size(); ++i)
{
faces.forceSize_Unsafe(0);
hashset.clear();
tetIds.forceSize_Unsafe(0);
collectTetsConnectedToVertex(faces, hashset, tets, neighbors, vertexToTet, ringCopy[i], tetIds);
addRange(set, tetIds);
}
for (PxHashSet<PxI32>::Iterator iter = set.getIterator(); !iter.done(); ++iter)
{
PxI32 i = *iter;
const Tetrahedron& neighborTet = tets[i];
for (PxU32 j = 0; j < newFaces.size(); ++j)
if (neighborTet.containsFace(newFaces[j]))
return false;
for (PxU32 j = 0; j < newTets.size(); ++j)
{
const Tetrahedron& t = newTets[j];
if (Tetrahedron::identical(t, neighborTet))
return false;
}
}
for (PxU32 i = 0; i < tetIndices.size(); ++i)
{
tets[tetIndices[i]] = Tetrahedron(-1, -1, -1, -1);
unusedTets.pushBack(tetIndices[i]);
}
PxU32 l = newTetIds.size();
for (PxU32 i = 0; i < newTets.size(); ++i)
newTetIds.pushBack(storeNewTet(tets, neighbors, newTets[i], unusedTets));
fixNeighborhoodLocally(tetIndices, newTetIds, tets, neighbors);
tetIndices.clear();
for (PxU32 i = l; i < newTetIds.size(); ++i)
tetIndices.pushBack(newTetIds[i]);
fixVertexToTet(vertexToTet, tetIndices, tets);
return true;
}
bool DelaunayTetrahedralizer::removeEdgeByFlip(PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& tetIndices, BaseTetAnalyzer* qualityAnalyzer)
{
stackMemory.clear();
return physx::Ext::removeEdgeByFlip(edgeA, edgeB, stackMemory.faces, stackMemory.hashSet, tetIndices, result, centeredNormalizedPoints, unusedTets, neighbors, vertexToTet, qualityAnalyzer);
}
void DelaunayTetrahedralizer::addLockedEdges(const PxArray<Triangle>& triangles)
{
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& t = triangles[i];
lockedEdges.insert(key(t[0] + numAdditionalPointsAtBeginning, t[1] + numAdditionalPointsAtBeginning));
lockedEdges.insert(key(t[0] + numAdditionalPointsAtBeginning, t[2] + numAdditionalPointsAtBeginning));
lockedEdges.insert(key(t[1] + numAdditionalPointsAtBeginning, t[2] + numAdditionalPointsAtBeginning));
}
}
void DelaunayTetrahedralizer::addLockedTriangles(const PxArray<Triangle>& triangles)
{
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
lockedTriangles.insert(SortedTriangle(tri[0] + numAdditionalPointsAtBeginning, tri[1] + numAdditionalPointsAtBeginning, tri[2] + numAdditionalPointsAtBeginning));
}
}
void previewFlip3to2(PxI32 tip1, PxI32 tip2, PxI32 reflexEdgeA, PxI32 reflexEdgeB, PxI32 nonReflexTrianglePoint, Tetrahedron& tet1, Tetrahedron& tet2)
{
// 3->2 flip
tet1 = Tetrahedron(tip1, tip2, reflexEdgeA, nonReflexTrianglePoint);
tet2 = Tetrahedron(tip2, tip1, reflexEdgeB, nonReflexTrianglePoint);
}
bool previewFlip2to3(PxI32 tet1Id, PxI32 tet2Id, const PxArray<PxI32>& neighbors, const PxArray<Tetrahedron>& tets,
PxI32 tip1, PxI32 tip2, Triangle tri, Tetrahedron& tet1, Tetrahedron& tet2, Tetrahedron& tet3)
{
// 2->3 flip
tet1 = Tetrahedron(tip2, tip1, tri[0], tri[1]);
tet2 = Tetrahedron(tip2, tip1, tri[1], tri[2]);
tet3 = Tetrahedron(tip2, tip1, tri[2], tri[0]);
PxI32 n1 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[0], tri[1], tip1)];
PxI32 n2 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[0], tri[1], tip2)];
if (n1 >= 0 && (n1 >> 2) == (n2 >> 2))
{
if (Tetrahedron::identical(tet1, tets[n1 >> 2]))
return false;
}
PxI32 n3 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[1], tri[2], tip1)];
PxI32 n4 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[1], tri[2], tip2)];
if (n3 >= 0 && (n3 >> 2) == (n4 >> 2))
{
if (Tetrahedron::identical(tet2, tets[n3 >> 2]))
return false;
}
PxI32 n5 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[2], tri[0], tip1)];
PxI32 n6 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[2], tri[0], tip2)];
if (n5 >= 0 && (n5 >> 2) == (n6 >> 2))
{
if (Tetrahedron::identical(tet3, tets[n5 >> 2]))
return false;
}
return true;
}
bool previewFlip(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& neighbors, PxI32 faceId,
PxArray<Tetrahedron>& newTets, PxArray<PxI32>& removedTets,
const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges)
{
newTets.clear();
removedTets.clear();
PxI32 neighborPointer = neighbors[faceId];
if (neighborPointer < 0)
return false;
PxI32 tet1Id = faceId >> 2;
const PxI32* localTriangle1 = neighborFaces[faceId & 3];
Tetrahedron tet1 = tets[tet1Id];
Triangle tri(tet1[localTriangle1[0]], tet1[localTriangle1[1]], tet1[localTriangle1[2]]);
PxI32 localTip1 = tetTip[faceId & 3];
PxI32 localTip2 = tetTip[neighborPointer & 3];
PxI32 tip1 = tet1[localTip1];
PxI32 tet2Id = neighborPointer >> 2;
Tetrahedron tet2 = tets[tet2Id];
PxI32 tip2 = tet2[localTip2];
if (!tet2.contains(tri[0]) || !tet2.contains(tri[1]) || !tet2.contains(tri[2]))
{
return false;
}
PxI32 face1 = -1;
PxI32 face2 = -1;
PxI32 numReflexEdges = 0;
PxI32 reflexEdgeA = -1;
PxI32 reflexEdgeB = -1;
PxI32 nonReflexTrianglePoint = -1;
PxF64 ab = orient3D(points[tri[0]], points[tri[1]], points[tip1], points[tip2]);
if (ab < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[0], localTriangle1[1], localTip1); reflexEdgeA = tri[0]; reflexEdgeB = tri[1]; nonReflexTrianglePoint = tri[2]; face2 = localFaceId(tet2, tri[0], tri[1], tip2); }
PxF64 bc = orient3D(points[tri[1]], points[tri[2]], points[tip1], points[tip2]);
if (bc < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[1], localTriangle1[2], localTip1); reflexEdgeA = tri[1]; reflexEdgeB = tri[2]; nonReflexTrianglePoint = tri[0]; face2 = localFaceId(tet2, tri[1], tri[2], tip2); }
PxF64 ca = orient3D(points[tri[2]], points[tri[0]], points[tip1], points[tip2]);
if (ca < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[2], localTriangle1[0], localTip1); reflexEdgeA = tri[2]; reflexEdgeB = tri[0]; nonReflexTrianglePoint = tri[1]; face2 = localFaceId(tet2, tri[2], tri[0], tip2); }
if (numReflexEdges == 0)
{
if (!faceIsLocked(lockedFaces, tri[0], tri[1], tri[2]))
{
Tetrahedron tet3;
if (previewFlip2to3(tet1Id, tet2Id, neighbors, tets, tip1, tip2, tri, tet1, tet2, tet3))
{
newTets.pushBack(tet1); newTets.pushBack(tet2); newTets.pushBack(tet3);
removedTets.pushBack(tet1Id); removedTets.pushBack(tet2Id);
return true;
}
else return true;
}
}
else if (numReflexEdges == 1)
{
PxI32 candidate1 = neighbors[4 * tet1Id + face1] >> 2;
PxI32 candidate2 = neighbors[4 * tet2Id + face2] >> 2;
if (candidate1 == candidate2 && candidate1 >= 0)
{
if (!edgeIsLocked(lockedEdges, reflexEdgeA, reflexEdgeB) &&
!faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint) &&
!faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip1) &&
!faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip2))
{
previewFlip3to2(tip1, tip2, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint, tet1, tet2);
newTets.pushBack(tet1); newTets.pushBack(tet2);
removedTets.pushBack(tet1Id); removedTets.pushBack(tet2Id); removedTets.pushBack(candidate1);
return true;;
}
}
}
else if (numReflexEdges == 2)
{
//Cannot do anything
}
else if (numReflexEdges == 3)
{
}
return true;
}
void collectCommonFaces(const PxArray<PxI32>& a, const PxArray<PxI32>& b, const PxArray<PxI32>& neighbors, PxArray<PxI32>& result)
{
result.clear();
for (PxU32 i = 0; i < a.size(); ++i)
{
PxI32 tetId = a[i];
for (int j = 0; j < 4; ++j)
{
int id = 4 * tetId + j;
if (b.find(neighbors[id] >> 2) != b.end())
{
if (result.find(id) == result.end())
result.pushBack(id);
}
}
}
}
void previewFlip2to3(PxI32 tip1, PxI32 tip2, const Triangle& tri, Tetrahedron& tet1, Tetrahedron& tet2, Tetrahedron& tet3)
{
// 2->3 flip
tet1 = Tetrahedron(tip2, tip1, tri[0], tri[1]);
tet2 = Tetrahedron(tip2, tip1, tri[1], tri[2]);
tet3 = Tetrahedron(tip2, tip1, tri[2], tri[0]);
}
bool DelaunayTetrahedralizer::recoverEdgeByFlip(PxI32 eStart, PxI32 eEnd, RecoverEdgeMemoryCache& cache)
{
PxArray<PxI32>& tetsStart = cache.resultStart;
PxArray<PxI32>& tetsEnd = cache.resultEnd;
collectTetsConnectedToVertex(cache.facesStart, cache.tetsDoneStart, eStart, tetsStart);
collectTetsConnectedToVertex(cache.facesEnd, cache.tetsDoneEnd, eEnd, tetsEnd);
for (PxU32 i = 0; i < tetsEnd.size(); ++i)
{
const Tetrahedron& tet = result[tetsEnd[i]];
if (tet.contains(eStart))
return true;
}
PxArray<PxI32> commonFaces;
collectCommonFaces(tetsStart, tetsEnd, neighbors, commonFaces);
if (commonFaces.size() > 0)
{
for (PxU32 i = 0; i < commonFaces.size(); ++i)
{
PxI32 faceId = commonFaces[i];
PxI32 tetId = faceId >> 2;
const Tetrahedron& tet = result[tetId];
const PxI32* local = neighborFaces[faceId & 3];
Triangle tri(tet[local[0]], tet[local[1]], tet[local[2]]);
if (tri.contains(eStart) || tri.contains(eEnd))
continue;
int n = neighbors[faceId];
int tetId2 = n >> 2;
int tip1 = tet[tetTip[faceId & 3]];
int tip2 = result[tetId2][tetTip[n & 3]];
Tetrahedron tet1, tet2, tet3;
previewFlip2to3(tip1, tip2, tri, tet1, tet2, tet3);
if (tetVolume(tet1, centeredNormalizedPoints) > 0 &&
tetVolume(tet2, centeredNormalizedPoints) > 0 &&
tetVolume(tet3, centeredNormalizedPoints) > 0)
{
PxArray<PxI32> affectedFaces;
if (flip2to3(tetId, tetId2, neighbors, vertexToTet, result, unusedTets, affectedFaces, tip1, tip2, tri))
return true;
}
}
}
return false;
}
void insert(PxArray<int>& list, int a, int b, int id)
{
for (PxI32 i = 0; i < PxI32(list.size()); ++i)
if (list[i] == a || list[i] == b)
{
list.pushBack(-1);
for (PxI32 j = list.size() - 2; j > i; --j)
{
list[j + 1] = list[j];
}
list[i + 1] = id;
return;
}
PX_ASSERT(false);
}
void DelaunayTetrahedralizer::generateTetmeshEnforcingEdges(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles, PxArray<PxArray<PxI32>>& allEdges,
PxArray<PxArray<PxI32>>& pointToOriginalTriangle,
PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets)
{
clearLockedEdges();
clearLockedTriangles();
addLockedEdges(triangles);
addLockedTriangles(triangles);
points.resize(trianglePoints.size());
for (PxU32 i = 0; i < trianglePoints.size(); ++i)
points[i] = trianglePoints[i];
insertPoints(points, 0, points.size());
allEdges.clear();
allEdges.reserve(lockedEdges.size());
PxHashMap<PxU64, PxU32> edgeToIndex;
PxArray<PxI32> list;
for (PxHashSet<PxU64>::Iterator iter = lockedEdges.getIterator(); !iter.done(); ++iter)
{
edgeToIndex.insert(*iter, allEdges.size());
list.forceSize_Unsafe(0);
list.pushBack(PxI32((*iter) >> 32));
list.pushBack(PxI32((*iter)));
allEdges.pushBack(list);
}
pointToOriginalTriangle.clear();
for (PxU32 i = 0; i < points.size(); ++i)
pointToOriginalTriangle.pushBack(PxArray<PxI32>());
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
pointToOriginalTriangle[tri[0]].pushBack(i);
pointToOriginalTriangle[tri[1]].pushBack(i);
pointToOriginalTriangle[tri[2]].pushBack(i);
}
for (PxU32 i = 0;i < points.size(); ++i) {
PxArray<PxI32>& tempList = pointToOriginalTriangle[i];
PxSort(tempList.begin(), tempList.size());
}
PxArray<PxI32> intersection;
RecoverEdgeMemoryCache cache;
while (true) {
PxArray<PxU64> copy;
copy.reserve(lockedEdges.size());
for (PxHashSet<PxU64>::Iterator e = lockedEdges.getIterator(); !e.done(); ++e)
copy.pushBack(*e);
PxI32 missing = 0;
for (PxU32 k = 0; k < copy.size(); ++k)
{
PxU64 e = copy[k];
PxI32 a = PxI32(e >> 32);
PxI32 b = PxI32(e);
if (!recoverEdgeByFlip(a, b, cache))
{
PxU32 id = centeredNormalizedPoints.size();
PxU32 i = edgeToIndex[e];
if (allEdges[i].size() < 10)
{
PxVec3d p = (centeredNormalizedPoints[a] + centeredNormalizedPoints[b]) * 0.5;
points.pushBack(p);
insertPoints(points, points.size() - 1, points.size());
intersection.forceSize_Unsafe(0);
intersectionOfSortedLists(pointToOriginalTriangle[a - numAdditionalPointsAtBeginning], pointToOriginalTriangle[b - numAdditionalPointsAtBeginning], intersection);
pointToOriginalTriangle.pushBack(intersection);
insert(allEdges[i], a, b, id);
edgeToIndex.insert(key(a, id), i);
edgeToIndex.insert(key(b, id), i);
edgeToIndex.erase(e);
lockedEdges.erase(e);
lockedEdges.insert(key(a, id));
lockedEdges.insert(key(b, id));
++missing;
}
}
}
if (missing == 0)
break;
}
for (PxU32 i = 0; i < allEdges.size(); ++i)
{
PxArray<PxI32>& tempList = allEdges[i];
for (PxU32 j = 0; j < tempList.size(); ++j)
tempList[j] -= numAdditionalPointsAtBeginning;
}
exportTetrahedra(finalTets);
}
PxI32 optimizeByFlipping(PxArray<PxI32>& faces, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet,
const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, const BaseTetAnalyzer& qualityAnalyzer,
PxArray<PxI32>& affectedFaces,
const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges)
{
PxI32 counter = 0;
while (faces.size() > 0)
{
PxI32 faceId = faces.popBack();
if (faceId < 0)
continue;
PxArray<Tetrahedron> newTets;
PxArray<PxI32> removedTets;
if (!previewFlip(points, tets, neighbors, faceId, newTets, removedTets, lockedFaces, lockedEdges))
continue;
if (!qualityAnalyzer.improved(qualityAnalyzer.quality(removedTets), qualityAnalyzer.quality(newTets)))
continue;
affectedFaces.clear();
flip(points, tets, neighbors, vertexToTet, faceId, unusedTets, affectedFaces, lockedFaces, lockedEdges);
for (PxU32 j = 0; j < affectedFaces.size(); ++j)
if (faces.find(affectedFaces[j]) == faces.end())
faces.pushBack(affectedFaces[j]);
++counter;
}
return counter;
}
bool DelaunayTetrahedralizer::optimizeByFlipping(PxArray<PxI32>& affectedFaces, const BaseTetAnalyzer& qualityAnalyzer)
{
PxArray<PxI32> stack;
for (PxU32 i = 0; i < affectedFaces.size(); ++i)
stack.pushBack(affectedFaces[i]);
PxI32 counter = physx::Ext::optimizeByFlipping(stack, neighbors, vertexToTet, centeredNormalizedPoints, result, unusedTets, qualityAnalyzer, affectedFaces, lockedTriangles, lockedEdges);
return counter > 0;
}
void insertPointIntoEdge(PxI32 newPointIndex, PxI32 edgeA, PxI32 edgeB, PxArray<Tetrahedron>& tets,
PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<PxI32>& unusedTets, PxArray<PxI32>* affectedFaces, PxArray<PxI32>& affectedTets)
{
PxU32 l = affectedTets.size();
if (l == 0)
return;
PxArray<PxI32> removedTets;
for (PxU32 i = 0; i < affectedTets.size(); ++i)
removedTets.pushBack(affectedTets[i]);
PxArray<PxI32> newTets;
for (PxU32 i = 0; i < affectedTets.size(); ++i)
newTets.pushBack(affectedTets[i]);
for (PxU32 i = 0; i < l; ++i)
{
for (PxI32 j = 0; j < 4; ++j)
{
PxI32 id = 4 * affectedTets[i] + j;
PxI32 neighborTet = neighbors[id] >> 2;
if (neighborTet >= 0 && affectedTets.find(neighborTet) == affectedTets.end())
affectedTets.pushBack(neighborTet);
}
}
PxU32 l2 = affectedTets.size();
for (PxU32 i = 0; i < l; ++i)
{
PxI32 id = affectedTets[i];
const Tetrahedron& tet = tets[id];
Edge oppositeEdge = getOtherEdge(tet, edgeA, edgeB);
tets[id] = Tetrahedron(oppositeEdge.first, oppositeEdge.second, edgeA, newPointIndex);
PxI32 j = storeNewTet(tets, neighbors, Tetrahedron(oppositeEdge.first, oppositeEdge.second, newPointIndex, edgeB), unusedTets);
affectedTets.pushBack(j);
newTets.pushBack(j);
}
fixNeighborhoodLocally(removedTets, affectedTets, tets, neighbors, affectedFaces);
fixVertexToTet(vertexToTet, newTets, tets);
affectedTets.removeRange(l, l2 - l);
}
void DelaunayTetrahedralizer::insertPointIntoEdge(PxI32 newPointIndex, PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& affectedTets, BaseTetAnalyzer* qualityAnalyzer)
{
PxArray<PxI32> affectedFaces;
physx::Ext::insertPointIntoEdge(newPointIndex, edgeA, edgeB, result, neighbors, vertexToTet, unusedTets, &affectedFaces, affectedTets);
if (qualityAnalyzer != NULL)
optimizeByFlipping(affectedFaces, *qualityAnalyzer);
}
bool containsAll(const PxArray<PxI32>& list, const PxArray<PxI32>& itemsToBePresentInList)
{
for (PxU32 i = 0; i < itemsToBePresentInList.size(); ++i)
if (list.find(itemsToBePresentInList[i]) == list.end())
return false;
return true;
}
bool optimizeByCollapsing(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges,
PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints, BaseTetAnalyzer* qualityAnalyzer)
{
PxI32 l = PxI32(pointToOriginalTriangle.size());
bool success = false;
PxArray<PxI32> tetsA;
PxArray<PxI32> tetsB;
for (PxU32 i = 0; i < edges.size(); ++i)
{
const EdgeWithLength& e = edges[i];
tetsA.forceSize_Unsafe(0);
del.collectTetsConnectedToVertex(e.A, tetsA);
if (tetsA.empty()) continue;
bool edgeExists = false;
for (PxU32 j = 0; j < tetsA.size(); ++j)
{
const Tetrahedron& tet = del.tetrahedron(tetsA[j]);
if (tet.contains(e.B))
{
edgeExists = true;
break;
}
}
if (!edgeExists)
continue;
tetsB.forceSize_Unsafe(0);
del.collectTetsConnectedToVertex(e.B, tetsB);
if (tetsB.empty()) continue;
PxF64 firstQuality = 0, secondQuality = 0;
bool firstOptionValid = e.B >= numFixPoints && (e.B >= l || (e.A < l && containsAll(pointToOriginalTriangle[e.A], pointToOriginalTriangle[e.B]))) &&
del.canCollapseEdge(e.A, e.B, tetsA, tetsB, firstQuality, 0, qualityAnalyzer);
bool secondOptionValid = e.A >= numFixPoints && (e.A >= l || (e.B < l && containsAll(pointToOriginalTriangle[e.B], pointToOriginalTriangle[e.A]))) &&
del.canCollapseEdge(e.B, e.A, tetsB, tetsA, secondQuality, 0, qualityAnalyzer);
if (qualityAnalyzer != NULL && firstOptionValid && secondOptionValid)
{
if (qualityAnalyzer->improved(firstQuality, secondQuality))
firstOptionValid = false;
else
secondOptionValid = false;
}
if (firstOptionValid)
{
if (e.B >= numFixPoints)
{
del.collapseEdge(e.A, e.B, tetsA, tetsB);
if (e.B < l)
pointToOriginalTriangle[e.B].clear();
success = true;
}
}
else if (secondOptionValid)
{
if (e.A >= numFixPoints)
{
del.collapseEdge(e.B, e.A, tetsB, tetsA);
if (e.A < l)
pointToOriginalTriangle[e.A].clear();
success = true;
}
}
}
return success;
}
bool optimizeBySwapping(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges,
const PxArray<PxArray<PxI32>>& pointToOriginalTriangle, BaseTetAnalyzer* qualityAnalyzer)
{
PxI32 l = PxI32(pointToOriginalTriangle.size());
bool success = false;
PxArray<PxI32> tetIds;
for (PxU32 i = 0; i < edges.size(); ++i)
{
const EdgeWithLength& e = edges[i];
const bool isInteriorEdge = e.A >= l || e.B >= l || !intersectionOfSortedListsContainsElements(pointToOriginalTriangle[e.A], pointToOriginalTriangle[e.B]);
if (isInteriorEdge)
{
tetIds.forceSize_Unsafe(0);
del.collectTetsConnectedToEdge(e.A, e.B, tetIds);
if (tetIds.size() <= 2)
continue; //This would mean we have a surface edge
if (del.removeEdgeByFlip(e.A, e.B, tetIds, qualityAnalyzer))
success = true;
}
}
return success;
}
void patternSearchOptimize(PxI32 pointToModify, PxF64 step, PxArray<PxVec3d>& points, BaseTetAnalyzer& score, const PxArray<PxI32>& tetrahedra, PxF64 minStep)
{
const PxVec3d dir[] = { PxVec3d(1.0, 0.0, 0.0), PxVec3d(-1.0, 0.0, 0.0), PxVec3d(0.0, 1.0, 0.0), PxVec3d(0.0, -1.0, 0.0), PxVec3d(0.0, 0.0, 1.0), PxVec3d(0.0, 0.0, -1.0), };
const PxI32 oppositeDir[] = { 1, 0, 3, 2, 5, 4 };
PxF64 currentScore = score.quality(tetrahedra); // score();
PxVec3d p = points[pointToModify];
PxI32 skip = -1;
PxI32 maxIter = 100;
PxI32 iter = 0;
while (step > minStep && iter < maxIter)
{
PxF64 best = currentScore;
PxI32 id = -1;
for (PxI32 i = 0; i < 6; ++i)
{
if (i == skip)
continue; //That point was the best before current iteration - it cannot be the best anymore
points[pointToModify] = p + dir[i] * step;
PxF64 s = score.quality(tetrahedra); // score();
if (score.improved(best, s))
{
best = s;
id = i;
}
}
if (id >= 0)
{
p = p + dir[id] * step;
points[pointToModify] = p;
currentScore = best;
skip = oppositeDir[id];
}
else
{
points[pointToModify] = p;
step = step * 0.5;
skip = -1;
}
++iter;
}
}
bool optimizeBySplitting(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, const PxArray<PxArray<PxI32>>& pointToOriginalTriangle,
PxI32 maxPointsToInsert, bool sortByQuality, BaseTetAnalyzer* qualityAnalyzer, PxF64 qualityThreshold)
{
const PxF64 qualityThresholdPow3 = qualityThreshold * qualityThreshold * qualityThreshold;
PxArray<PxF64> tetQualityBuffer;
tetQualityBuffer.resize(del.numTetrahedra());
for (PxU32 i = 0; i < del.numTetrahedra(); ++i) {
const Tetrahedron& tet = del.tetrahedron(i);
if (tet[0] >= 0)
tetQualityBuffer[i] = evaluateAmipsEnergyPow3(del.point(tet[0]), del.point(tet[1]), del.point(tet[2]), del.point(tet[3]));
}
PxI32 l = PxI32(pointToOriginalTriangle.size());
PxArray<SplitEdge> edgesToSplit;
PxArray<PxI32> tetIds;
for (PxI32 i = edges.size() - 1; i >= 0; --i)
{
const EdgeWithLength& e = edges[i];
const bool isInteriorEdge = e.A >= l || e.B >= l || !intersectionOfSortedListsContainsElements(pointToOriginalTriangle[e.A], pointToOriginalTriangle[e.B]);
if (isInteriorEdge)
{
tetIds.forceSize_Unsafe(0);
del.collectTetsConnectedToEdge(e.A, e.B, tetIds);
if (tetIds.size() <= 2)
continue; //This would mean we got a surface edge...
PxF64 max = 0;
for (PxU32 j = 0; j < tetIds.size(); ++j)
{
if (tetQualityBuffer[tetIds[j]] > max)
max = tetQualityBuffer[tetIds[j]];
}
if (max > qualityThresholdPow3)
edgesToSplit.pushBack(SplitEdge(e.A, e.B, max, (del.point(e.A) - del.point(e.B)).magnitudeSquared(), isInteriorEdge));
}
}
if (sortByQuality)
{
PxSort(edgesToSplit.begin(), edgesToSplit.size(), PxGreater<SplitEdge>());
}
PxI32 counter = 0;
PxArray<PxI32> tetsConnectedToEdge;
PxArray<PxI32> tetsConnectedToVertex;
for (PxU32 i = 0; i < edgesToSplit.size(); ++i)
{
const SplitEdge& e = edgesToSplit[i];
if (i > 0 && edgesToSplit[i - 1].Q == e.Q)
continue;
if (counter == maxPointsToInsert)
break;
PxU32 id = del.addPoint((del.point(e.A) + del.point(e.B)) * 0.5);
tetsConnectedToEdge.forceSize_Unsafe(0);
del.collectTetsConnectedToEdge(e.A, e.B, tetsConnectedToEdge);
del.insertPointIntoEdge(id, e.A, e.B, tetsConnectedToEdge, qualityAnalyzer);
if (e.InteriorEdge && qualityAnalyzer)
{
tetsConnectedToVertex.forceSize_Unsafe(0);
del.collectTetsConnectedToVertex(id, tetsConnectedToVertex);
patternSearchOptimize(id, e.L, del.points(), *qualityAnalyzer, tetsConnectedToVertex, 0.01 * e.L);
}
++counter;
}
return edgesToSplit.size() > 0;
}
void updateEdges(PxArray<EdgeWithLength>& edges, PxHashSet<PxU64>& tetEdges, const PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points)
{
edges.clear();
tetEdges.clear();
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
if (tet[0] < 0) continue;
tetEdges.insert(key(tet[0], tet[1]));
tetEdges.insert(key(tet[0], tet[2]));
tetEdges.insert(key(tet[0], tet[3]));
tetEdges.insert(key(tet[1], tet[2]));
tetEdges.insert(key(tet[1], tet[3]));
tetEdges.insert(key(tet[2], tet[3]));
}
for (PxHashSet<PxU64>::Iterator iter = tetEdges.getIterator(); !iter.done(); ++iter)
{
PxU64 e = *iter;
PxI32 a = PxI32(e >> 32);
PxI32 b = PxI32(e);
edges.pushBack(EdgeWithLength(a, b, (points[a] - points[b]).magnitudeSquared()));
}
PxSort(edges.begin(), edges.size(), PxLess<EdgeWithLength>());
}
void optimize(DelaunayTetrahedralizer& del, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints,
PxArray<PxVec3d>& optimizedPoints, PxArray<Tetrahedron>& optimizedTets, PxI32 numPasses)
{
PxHashSet<PxU64> tetEdges;
PxArray<EdgeWithLength> edges;
updateEdges(edges, tetEdges, del.tetrahedra(), del.points());
MinimizeMaxAmipsEnergy qualityAnalyzer(del.points(), del.tetrahedra());
//MaximizeMinTetVolume qualityAnalyzer(del.points(), del.tetrahedra());
optimizedTets = PxArray<Tetrahedron>(del.tetrahedra());
optimizedPoints = PxArray<PxVec3d>(del.points());
PxF64 minVolBefore = minAbsTetVolume(del.points(), del.tetrahedra());
PxF64 maxEnergyBefore = maxEnergy(del.points(), del.tetrahedra());
PxI32 numPointsToInsertPerPass = PxMax(20, PxI32(0.05 * del.numPoints()));
for (PxI32 j = 0; j < numPasses; ++j)
{
//(1) Splitting
updateEdges(edges, tetEdges, del.tetrahedra(), del.points());
optimizeBySplitting(del, edges, pointToOriginalTriangle, numPointsToInsertPerPass, true, &qualityAnalyzer);
//(3) Swapping
updateEdges(edges, tetEdges, del.tetrahedra(), del.points());
optimizeBySwapping(del, edges, pointToOriginalTriangle, &qualityAnalyzer);
//(2) Collapsing
updateEdges(edges, tetEdges, del.tetrahedra(), del.points());
optimizeByCollapsing(del, edges, pointToOriginalTriangle, numFixPoints, &qualityAnalyzer);
//(4) Smoothing
//Note done here - seems not to improve the quality that much
PxF64 energy = maxEnergy(del.points(), del.tetrahedra());
PxF64 minVol = minAbsTetVolume(del.points(), del.tetrahedra());
if (energy / minVol >= maxEnergyBefore / minVolBefore/*minVol <= minVolBefore*/)
{
del.initialize(optimizedPoints, optimizedTets);
bool swapped = true, collapsed = true;
PxI32 maxReductionLoops = 30;
PxI32 counter = 0;
while (swapped || collapsed)
{
//(3) Swapping
updateEdges(edges, tetEdges, del.tetrahedra(), del.points());
swapped = optimizeBySwapping(del, edges, pointToOriginalTriangle, &qualityAnalyzer);
//(2) Collapsing
updateEdges(edges, tetEdges, del.tetrahedra(), del.points());
collapsed = optimizeByCollapsing(del, edges, pointToOriginalTriangle, numFixPoints, &qualityAnalyzer);
if (counter >= maxReductionLoops)
break;
++counter;
}
optimizedTets = PxArray<Tetrahedron>(del.tetrahedra());
optimizedPoints = PxArray<PxVec3d>(del.points());
return;
}
optimizedTets = PxArray<Tetrahedron>(del.tetrahedra());
optimizedPoints = PxArray<PxVec3d>(del.points());
minVolBefore = minVol;
maxEnergyBefore = energy;
}
}
}
}
| 76,979 | C++ | 34.295736 | 231 | 0.674327 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetSplitting.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 "ExtTetSplitting.h"
#include "ExtUtilities.h"
#include "foundation/PxBasicTemplates.h"
namespace physx
{
namespace Ext
{
//Last four bits are used
//Last bit set stands for A
//Second last bit stands for B
//Third last bit stands for C
//Fourth last bit stands for D
typedef PxU32 TetCorner;
typedef PxU32 TetEdge;
static const TetCorner None = 0x00000000;
static const TetCorner A = 0x00000001;
static const TetCorner B = 0x00000002;
static const TetCorner C = 0x00000004;
static const TetCorner D = 0x00000008;
static const TetEdge AB = 0x00000003;
static const TetEdge AC = 0x00000005;
static const TetEdge AD = 0x00000009;
static const TetEdge BC = 0x00000006;
static const TetEdge BD = 0x0000000A;
static const TetEdge CD = 0x0000000C;
static const TetCorner tetCorners[4] = { A, B, C, D };
//Specifies which edges of a tetrahedron should get a point inserted (=split)
struct TetSubdivisionInfo
{
//If an index has value -1 then this means that this edge won't get split
PxI32 ab;
PxI32 ac;
PxI32 ad;
PxI32 bc;
PxI32 bd;
PxI32 cd;
Tetrahedron tet;
PxI32 id;
PX_FORCE_INLINE TetSubdivisionInfo() : ab(-1), ac(-1), ad(-1), bc(-1), bd(-1), cd(-1), tet(Tetrahedron(-1, -1, -1, -1)), id(-1) {}
PX_FORCE_INLINE TetSubdivisionInfo(Tetrahedron tet_, PxI32 aBPointInsertIndex, PxI32 aCPointInsertIndex, PxI32 aDPointInsertIndex,
PxI32 bCPointInsertIndex, PxI32 bDPointInsertIndex, PxI32 cDPointInsertIndex, PxI32 id_ = -1) :
ab(aBPointInsertIndex), ac(aCPointInsertIndex), ad(aDPointInsertIndex), bc(bCPointInsertIndex), bd(bDPointInsertIndex), cd(cDPointInsertIndex), tet(tet_), id(id_)
{ }
PX_FORCE_INLINE void swapInternal(TetCorner corner1, TetCorner corner2, TetCorner& cornerToProcess)
{
if (cornerToProcess == corner1)
cornerToProcess = corner2;
else if (cornerToProcess == corner2)
cornerToProcess = corner1;
}
//Helper method for sorting
template<typename T>
void swap(T& a, T& b)
{
T tmp = a;
a = b;
b = tmp;
}
//Helper method for sorting
bool swap(TetCorner corner1, TetCorner corner2, TetCorner& additionalCornerToProcess1, TetCorner& additionalCornerToProcess2)
{
swapInternal(corner1, corner2, additionalCornerToProcess1);
swapInternal(corner1, corner2, additionalCornerToProcess2);
return swap(corner1, corner2);
}
//Helper method for sorting
bool swap(TetCorner corner1, TetCorner corner2, TetCorner& additionalCornerToProcess)
{
swapInternal(corner1, corner2, additionalCornerToProcess);
return swap(corner1, corner2);
}
//Helper method for sorting
bool swap(TetCorner corner1, TetCorner corner2)
{
if (corner1 == corner2)
return false;
if (corner1 > corner2)
{
TetCorner tmp = corner1;
corner1 = corner2;
corner2 = tmp;
}
if (corner1 == A && corner2 == B)
{
PxSwap(ad, bd);
PxSwap(ac, bc);
PxSwap(tet[0], tet[1]);
}
else if (corner1 == A && corner2 == C)
{
PxSwap(ad, cd);
PxSwap(ab, bc);
PxSwap(tet[0], tet[2]);
}
else if (corner1 == A && corner2 == D)
{
PxSwap(ac, cd);
PxSwap(ab, bd);
PxSwap(tet[0], tet[3]);
}
else if (corner1 == B && corner2 == C)
{
PxSwap(ac, ab);
PxSwap(cd, bd);
PxSwap(tet[1], tet[2]);
}
else if (corner1 == B && corner2 == D)
{
PxSwap(ab, ad);
PxSwap(bc, cd);
PxSwap(tet[1], tet[3]);
}
else if (corner1 == C && corner2 == D)
{
PxSwap(ac, ad);
PxSwap(bc, bd);
PxSwap(tet[2], tet[3]);
}
return true;
}
//Allows to sort the information such that edges of neighboring tets have the same orientation
PxI32 sort()
{
PxI32 counter = 0;
if (tet[0] > tet[1]) { swap(A, B); ++counter; }
if (tet[0] > tet[2]) { swap(A, C); ++counter; }
if (tet[0] > tet[3]) { swap(A, D); ++counter; }
if (tet[1] > tet[2]) { swap(B, C); ++counter; }
if (tet[1] > tet[3]) { swap(B, D); ++counter; }
if (tet[2] > tet[3]) { swap(C, D); ++counter; }
return counter;
}
};
//Returns true if the edge is adjacent to the specified corner
PX_FORCE_INLINE bool edgeContainsCorner(TetEdge edge, TetCorner corner)
{
return (edge & corner) != 0;
}
//Returns the common point of two edges, will be None if there is no common point
PX_FORCE_INLINE TetCorner getCommonPoint(TetEdge edge1, TetEdge edge2)
{
return edge1 & edge2;
}
//Extracts the global indices from a tet given a local edge
Edge getTetEdge(const Tetrahedron& tet, TetEdge edge)
{
switch (edge)
{
case AB:
return Edge(tet[0], tet[1]);
case AC:
return Edge(tet[0], tet[2]);
case AD:
return Edge(tet[0], tet[3]);
case BC:
return Edge(tet[1], tet[2]);
case BD:
return Edge(tet[1], tet[3]);
case CD:
return Edge(tet[2], tet[3]);
}
return Edge(-1, -1);
}
TetCorner getStart(TetEdge e)
{
switch (e)
{
case AB:
return A;
case AC:
return A;
case AD:
return A;
case BC:
return B;
case BD:
return B;
case CD:
return C;
}
return None;
}
TetCorner getEnd(TetEdge e)
{
switch (e)
{
case AB:
return B;
case AC:
return C;
case AD:
return D;
case BC:
return C;
case BD:
return D;
case CD:
return D;
}
return None;
}
PX_FORCE_INLINE TetEdge getOppositeEdge(TetEdge edge)
{
return 0x0000000F ^ edge;
}
//Finds the index of the first instance of value in list
PxI32 getIndexOfFirstValue(PxI32 list[4], PxI32 value = 0, PxI32 startAt = 0)
{
for (PxI32 i = startAt; i < 4; ++i)
if (list[i] == value)
return i;
PX_ASSERT(false); // we should never reach this line
return 0;
}
//Counts how many times every corner is referenced by the specified set of edges - useful for corner classification
void getCornerAccessCounter(TetEdge edges[6], PxI32 edgesLength, PxI32 cornerAccessCounter[4])
{
for (PxI32 i = 0; i < 4; ++i)
cornerAccessCounter[i] = 0;
for (PxI32 j = 0; j < edgesLength; ++j)
{
switch (edges[j])
{
case AB:
++cornerAccessCounter[0];
++cornerAccessCounter[1];
break;
case AC:
++cornerAccessCounter[0];
++cornerAccessCounter[2];
break;
case AD:
++cornerAccessCounter[0];
++cornerAccessCounter[3];
break;
case BC:
++cornerAccessCounter[1];
++cornerAccessCounter[2];
break;
case BD:
++cornerAccessCounter[1];
++cornerAccessCounter[3];
break;
case CD:
++cornerAccessCounter[2];
++cornerAccessCounter[3];
break;
}
}
}
//Returns the tet's edge that does not contain corner1 and neither corner2
Edge getRemainingEdge(const Tetrahedron& tet, PxI32 corner1, PxI32 corner2)
{
PxI32 indexer = 0;
Edge result(-1, -1);
for (PxU32 i = 0; i < 4; ++i)
{
if (tet[i] != corner1 && tet[i] != corner2)
{
if (indexer == 0)
result.first = tet[i];
else if (indexer == 1)
result.second = tet[i];
++indexer;
}
}
return result;
}
PX_FORCE_INLINE TetCorner getOtherCorner(TetEdge edge, TetCorner corner)
{
return edge ^ corner;
}
PX_FORCE_INLINE Tetrahedron flip(bool doFlip, Tetrahedron t)
{
if (doFlip) PxSwap(t[2], t[3]);
return t;
}
//Splits all tets according to the specification in tetSubdivisionInfos. The resulting mesh will be watertight if the tetSubdivisionInfos are specified such
//that all tets sharing and edge will get the same point inserted on their corresponding edge
void split(PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points, const PxArray<TetSubdivisionInfo>& tetSubdivisionInfos)
{
PxU32 originalNumTets = tets.size();
for (PxU32 i = 0; i < originalNumTets; ++i)
{
TetSubdivisionInfo info = tetSubdivisionInfos[i];
PxI32 counter = info.sort();
TetEdge splitEdges[6];
PxI32 splitEdgesLength = 0;
TetEdge nonSplitEdges[6];
PxI32 nonSplitEdgesLength = 0;
PxI32 insertionIndices[6];
PxI32 insertionIndicesLength = 0;
if (info.ab >= 0) { splitEdges[splitEdgesLength++] = AB; insertionIndices[insertionIndicesLength++] = info.ab; }
else nonSplitEdges[nonSplitEdgesLength++] = AB;
if (info.ac >= 0) { splitEdges[splitEdgesLength++] = AC; insertionIndices[insertionIndicesLength++] = info.ac; }
else nonSplitEdges[nonSplitEdgesLength++] = AC;
if (info.ad >= 0) { splitEdges[splitEdgesLength++] = AD; insertionIndices[insertionIndicesLength++] = info.ad; }
else nonSplitEdges[nonSplitEdgesLength++] = AD;
if (info.bc >= 0) { splitEdges[splitEdgesLength++] = BC; insertionIndices[insertionIndicesLength++] = info.bc; }
else nonSplitEdges[nonSplitEdgesLength++] = BC;
if (info.bd >= 0) { splitEdges[splitEdgesLength++] = BD; insertionIndices[insertionIndicesLength++] = info.bd; }
else nonSplitEdges[nonSplitEdgesLength++] = BD;
if (info.cd >= 0) { splitEdges[splitEdgesLength++] = CD; insertionIndices[insertionIndicesLength++] = info.cd; }
else nonSplitEdges[nonSplitEdgesLength++] = CD;
//Depending on how many tet edges get a point inserted, a different topology results.
//The created topology will make sure all neighboring tet faces will be tessellated identically to keep the mesh watertight
switch (splitEdgesLength)
{
case 0:
//Nothing to do here
break;
case 1:
{
PxI32 pointIndex = insertionIndices[0];
Edge splitEdge = getTetEdge(info.tet, splitEdges[0]);
Edge oppositeEdge = getTetEdge(info.tet, getOppositeEdge(splitEdges[0]));
tets[i] = Tetrahedron(oppositeEdge.first, oppositeEdge.second, splitEdge.first, pointIndex);
tets.pushBack(Tetrahedron(oppositeEdge.first, oppositeEdge.second, pointIndex, splitEdge.second));
break;
}
case 2:
{
TetCorner corner = getCommonPoint(splitEdges[0], splitEdges[1]);
if (corner != None)
{
//edges have a common point
//Rearrange such that common corner is a and first edge is from a to b while second edge is from a to c
TetCorner p1 = getOtherCorner(splitEdges[0], corner);
TetCorner p2 = getOtherCorner(splitEdges[1], corner);
if (info.swap(corner, A, p1, p2)) ++counter;
if (info.swap(p1, B, p2)) ++counter;
if (info.swap(p2, C)) ++counter;
if (info.tet[1] > info.tet[2])
{
if (info.swap(B, C)) ++counter;
}
const bool f = counter % 2 == 1;
tets[i] = flip(f, Tetrahedron(info.tet[0], info.tet[3], info.ab, info.ac));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.tet[1], info.ab, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.tet[2], info.tet[1], info.ac)));
}
else
{
//Edges don't have a common point (opposite edges)
TetEdge edge1 = splitEdges[0];
//TetEdge edge2 = splitEdges[1];
//Permute the tetrahedron such that edge1 becomes the edge AB
if (info.swap(getStart(edge1), A)) ++counter;
if (info.swap(getEnd(edge1), B)) ++counter;
if (info.tet[0] > info.tet[1])
{
if (info.swap(A, B)) ++counter;
}
if (info.tet[2] > info.tet[3])
{
if (info.swap(C, D)) ++counter;
}
const bool f = counter % 2 == 1;
tets[i] = flip(f, Tetrahedron(info.tet[0], info.ab, info.tet[2], info.cd));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.ab, info.cd, info.tet[2])));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ab, info.cd, info.tet[3])));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.ab, info.tet[3], info.cd)));
}
break;
}
case 3:
{
//There are three sub cases called a, b and c
TetCorner commonPoint01 = getCommonPoint(splitEdges[0], splitEdges[1]);
TetCorner commonPoint02 = getCommonPoint(splitEdges[0], splitEdges[2]);
TetCorner commonPoint12 = getCommonPoint(splitEdges[1], splitEdges[2]);
if (commonPoint01 == None || commonPoint02 == None || commonPoint12 == None)
{
//The three edges form a non closed strip
//The strip's end points are connected by a tet edge - map this edge such that it becomes edge AB
//Then sort AB
PxI32 cnt[4];
getCornerAccessCounter(splitEdges, splitEdgesLength, cnt);
PxI32 index = getIndexOfFirstValue(cnt, 1);
TetCorner refStart = tetCorners[index];
TetCorner refEnd = tetCorners[getIndexOfFirstValue(cnt, 1, index + 1)];
TetCorner cornerToMapOntoC = None;
if (edgeContainsCorner(splitEdges[0], refEnd))
{
cornerToMapOntoC = getOtherCorner(splitEdges[0], refEnd);
}
else if (edgeContainsCorner(splitEdges[1], refEnd))
{
cornerToMapOntoC = getOtherCorner(splitEdges[1], refEnd);
}
else if (edgeContainsCorner(splitEdges[2], refEnd))
{
cornerToMapOntoC = getOtherCorner(splitEdges[2], refEnd);
}
if (info.swap(refStart, A, refEnd, cornerToMapOntoC)) ++counter;
if (info.swap(refEnd, B, cornerToMapOntoC)) ++counter;
if (info.swap(cornerToMapOntoC, C)) ++counter;
if (info.tet[0] > info.tet[1])
{
if (info.swap(A, B)) ++counter;
if (info.swap(C, D)) ++counter;
}
const bool f = counter % 2 == 1;
tets[i] = flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bc, info.ad));
if (info.tet[0] > info.tet[2])
{
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.cd, info.ad, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.ad, info.bc)));
}
else
{
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.cd, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bc, info.cd)));
}
if (info.tet[1] > info.tet[3])
{
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.bc, info.ad, info.cd)));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.tet[1], info.ad, info.bc)));
}
else
{
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.tet[3], info.cd, info.ad)));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.bc, info.ad, info.cd)));
}
}
else if (edgeContainsCorner(splitEdges[2], commonPoint01))
{
//All three edges share one common point
//Permute tetrahedron such that the common tip point is a
if (info.swap(commonPoint01, A)) ++counter;
//Sort the remaining values
if (info.tet[1] > info.tet[2])
{
if (info.swap(B, C)) ++counter;
}
if (info.tet[2] > info.tet[3])
{
if (info.swap(C, D)) ++counter;
}
if (info.tet[1] > info.tet[2])
{
if (info.swap(B, C)) ++counter;
}
const bool f = counter % 2 == 1;
tets[i] = flip(f, Tetrahedron(info.tet[0], info.ab, info.ac, info.ad));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.ab, info.ad, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.tet[1], info.ad, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.tet[2], info.ad, info.tet[3])));
}
else
{
//Edges form a triangle
//Rearrange such that point opposite of triangle loop is point d
//Triangle loop is a, b and c, make sure they're sorted
if (!(commonPoint01 == A || commonPoint02 == A || commonPoint12 == A))
{
if (info.swap(A, D)) ++counter;
}
else if (!(commonPoint01 == B || commonPoint02 == B || commonPoint12 == B))
{
if (info.swap(B, D)) ++counter;
}
else if (!(commonPoint01 == C || commonPoint02 == C || commonPoint12 == C))
{
if (info.swap(C, D)) ++counter;
}
else if (!(commonPoint01 == D || commonPoint02 == D || commonPoint12 == D))
{
if (info.swap(D, D)) ++counter;
}
//Sort a,b and c
if (info.tet[0] > info.tet[1])
if (info.swap(A, B)) ++counter;
if (info.tet[1] > info.tet[2])
if (info.swap(B, C)) ++counter;
if (info.tet[0] > info.tet[1])
if (info.swap(A, B)) ++counter;
const bool f = counter % 2 == 1;
tets[i] = flip(f, Tetrahedron(info.tet[3], info.ab, info.ac, info.bc));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ab, info.ac, info.tet[0])));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ab, info.bc, info.tet[1])));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ac, info.bc, info.tet[2])));
}
break;
}
case 4:
{
TetCorner commonPoint = getCommonPoint(nonSplitEdges[0], nonSplitEdges[1]);
if (commonPoint != None)
{
//Three edges form a triangle and the two edges that are not split share a common point
TetCorner p1 = getOtherCorner(nonSplitEdges[0], commonPoint);
TetCorner p2 = getOtherCorner(nonSplitEdges[1], commonPoint);
if (info.swap(commonPoint, A, p1, p2)) ++counter;
if (info.swap(p1, B, p2)) ++counter;
if (info.swap(p2, C)) ++counter;
if (info.tet[1] > info.tet[2])
if (info.swap(B, C)) ++counter;
const bool f = counter % 2 == 0;
//Tip
tets[i] = flip(f, Tetrahedron(info.tet[3], info.ad, info.bd, info.cd));
//Center
tets.pushBack(flip(f, Tetrahedron(info.bd, info.ad, info.bc, info.cd)));
if (info.tet[0] < info.tet[1] && info.tet[0] < info.tet[2])
{
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bd, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.bc, info.cd)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bc, info.bd, info.ad)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bc, info.ad, info.cd)));
}
else if (info.tet[0] > info.tet[1] && info.tet[0] < info.tet[2])
{
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.bc, info.cd)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bc, info.ad, info.cd)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.ad, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.bc, info.bd, info.ad)));
}
else
{
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.ad, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.bc, info.bd, info.ad)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.tet[0], info.ad, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.bc, info.ad, info.cd)));
}
}
else
{
//All four edges form a loop
TetEdge edge1 = nonSplitEdges[0];
//Permute the tetrahedron such that edge1 becomes the edge AB
TetCorner end = getEnd(edge1);
if (info.swap(getStart(edge1), A, end)) ++counter;
if (info.swap(end, B)) ++counter;
//Sort
if (info.tet[0] > info.tet[1])
if (info.swap(A, B)) ++counter;
if (info.tet[2] > info.tet[3])
if (info.swap(C, D)) ++counter;
const bool f = counter % 2 == 1;
tets[i] = flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bc, info.bd));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.tet[3], info.ad, info.bd)));
PxF64 dist1 = (points[info.ad] - points[info.bc]).magnitudeSquared();
PxF64 dist2 = (points[info.ac] - points[info.bd]).magnitudeSquared();
if (dist1 < dist2)
{
//Diagonal from AD to BC
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bc, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bd, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.ad, info.ac, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.ad, info.bc, info.bd)));
}
else
{
//Diagonal from AC to BD
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bd, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ac, info.bd, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.bc, info.bd, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.bd, info.ad, info.ac)));
}
}
break;
}
case 5:
{
//There is only one edge that does not get split
//First create 2 small tetrahedra in every corner that is not an end point of the unsplit edge
TetEdge nonSplitEdge;
if (info.ab < 0)
nonSplitEdge = AB;
else if (info.ac < 0)
nonSplitEdge = AC;
else if (info.ad < 0)
nonSplitEdge = AD;
else if (info.bc < 0)
nonSplitEdge = BC;
else if (info.bd < 0)
nonSplitEdge = BD;
else //if (info.CDPointInsertIndex < 0)
nonSplitEdge = CD;
TetCorner end = getEnd(nonSplitEdge);
if (info.swap(getStart(nonSplitEdge), A, end)) ++counter;
if (info.swap(end, B)) ++counter;
if (info.tet[0] > info.tet[1])
if (info.swap(A, B)) ++counter;
if (info.tet[2] > info.tet[3])
if (info.swap(C, D)) ++counter;
const bool f = counter % 2 == 1;
//Two corner tets at corner C and corner D
tets[i] = flip(f, Tetrahedron(info.tet[2], info.ac, info.bc, info.cd));
tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ad, info.cd, info.bd)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bc, info.bd)));
//There are two possible diagonals -> take the shorter
PxF64 dist1 = (points[info.ac] - points[info.bd]).magnitudeSquared();
PxF64 dist2 = (points[info.ad] - points[info.bc]).magnitudeSquared();
if (dist1 < dist2)
{
//Diagonal from AC to BD
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bd, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ac, info.bd, info.bc)));
//Tip pyramid
tets.pushBack(flip(f, Tetrahedron(info.cd, info.bc, info.bd, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.cd, info.bd, info.ad, info.ac)));
}
else
{
//Diagonal from AD to BC
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ac, info.ad, info.bc)));
tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bd, info.bc, info.ad)));
//Tip pyramid
tets.pushBack(flip(f, Tetrahedron(info.cd, info.bc, info.ad, info.ac)));
tets.pushBack(flip(f, Tetrahedron(info.cd, info.bd, info.ad, info.bc)));
}
break;
}
case 6:
{
//First create a small tetrahedron in every corner
const bool f = counter % 2 == 1;
if (f)
info.swap(A, B);
tets[i] = Tetrahedron(info.tet[0], info.ab, info.ac, info.ad);
tets.pushBack(Tetrahedron(info.tet[1], info.ab, info.bd, info.bc));
tets.pushBack(Tetrahedron(info.tet[2], info.ac, info.bc, info.cd));
tets.pushBack(Tetrahedron(info.tet[3], info.ad, info.cd, info.bd));
//Now fill the remaining octahedron in the middle
//An octahedron can be constructed using 4 tetrahedra
//There are three diagonal candidates -> pick the shortest diagonal
PxF64 dist1 = (points[info.ab] - points[info.cd]).magnitudeSquared();
PxF64 dist2 = (points[info.ac] - points[info.bd]).magnitudeSquared();
PxF64 dist3 = (points[info.ad] - points[info.bc]).magnitudeSquared();
if (dist1 <= dist2 && dist1 <= dist3)
{
tets.pushBack(Tetrahedron(info.ab, info.cd, info.ad, info.bd));
tets.pushBack(Tetrahedron(info.ab, info.cd, info.bd, info.bc));
tets.pushBack(Tetrahedron(info.ab, info.cd, info.bc, info.ac));
tets.pushBack(Tetrahedron(info.ab, info.cd, info.ac, info.ad));
}
else if (dist2 <= dist1 && dist2 <= dist3)
{
tets.pushBack(Tetrahedron(info.ac, info.bd, info.cd, info.ad));
tets.pushBack(Tetrahedron(info.ac, info.bd, info.ad, info.ab));
tets.pushBack(Tetrahedron(info.ac, info.bd, info.ab, info.bc));
tets.pushBack(Tetrahedron(info.ac, info.bd, info.bc, info.cd));
}
else
{
tets.pushBack(Tetrahedron(info.ad, info.bc, info.bd, info.ab));
tets.pushBack(Tetrahedron(info.ad, info.bc, info.cd, info.bd));
tets.pushBack(Tetrahedron(info.ad, info.bc, info.ac, info.cd));
tets.pushBack(Tetrahedron(info.ad, info.bc, info.ab, info.ac));
}
break;
}
}
}
}
void split(PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points, const PxHashMap<PxU64, PxI32>& edgesToSplit)
{
PxArray<TetSubdivisionInfo> subdivisionInfos;
subdivisionInfos.resize(tets.size());
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
TetSubdivisionInfo info(tet, -1, -1, -1, -1, -1, -1, i);
if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[0], tet[1])))
info.ab = ptr->second;
if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[0], tet[2])))
info.ac = ptr->second;
if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[0], tet[3])))
info.ad = ptr->second;
if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[1], tet[2])))
info.bc = ptr->second;
if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[1], tet[3])))
info.bd = ptr->second;
if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[2], tet[3])))
info.cd = ptr->second;
subdivisionInfos[i] = info;
}
split(tets, points, subdivisionInfos);
}
}
}
| 26,502 | C++ | 31.922981 | 165 | 0.639046 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMarchingCubesTable.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_MARCHING_CUBES_TABLE_H
#define EXT_MARCHING_CUBES_TABLE_H
namespace physx
{
namespace Ext
{
// point numbering
// 7-----------6
// /| /|
// / | / |
// / | / |
// 4-----------5 |
// | | | |
// | 3-------|---2
// | / | /
// | / | /
// |/ |/
// 0-----------1
// edge numbering
// *-----6-----*
// /| /|
// 7 | 5 |
// / 11 / 10
// *-----4-----* |
// | | | |
// | *-----2-|---*
// 8 / 9 /
// | 3 | 1
// |/ |/
// *-----0-----*
// z
// | y
// | /
// |/
// 0---- x
int marchingCubeCorners[8][3] = { {0,0,0}, {1,0,0},{1,1,0},{0,1,0}, {0,0,1}, {1,0,1},{1,1,1},{0,1,1} };
int marchingCubeEdges[12][2] = { {0,1},{1,2},{2,3},{3,0},{4,5},{5,6},{6,7},{7,4},{0,4},{1,5},{2,6},{3,7} };
int firstMarchingCubesId[257] = {
0, 0, 3, 6, 12, 15, 21, 27, 36, 39, 45, 51, 60, 66, 75, 84, 90, 93, 99, 105, 114,
120, 129, 138, 150, 156, 165, 174, 186, 195, 207, 219, 228, 231, 237, 243, 252, 258, 267, 276, 288,
294, 303, 312, 324, 333, 345, 357, 366, 372, 381, 390, 396, 405, 417, 429, 438, 447, 459, 471, 480,
492, 507, 522, 528, 531, 537, 543, 552, 558, 567, 576, 588, 594, 603, 612, 624, 633, 645, 657, 666,
672, 681, 690, 702, 711, 723, 735, 750, 759, 771, 783, 798, 810, 825, 840, 852, 858, 867, 876, 888,
897, 909, 915, 924, 933, 945, 957, 972, 984, 999, 1008, 1014, 1023, 1035, 1047, 1056, 1068, 1083, 1092, 1098,
1110, 1125, 1140, 1152, 1167, 1173, 1185, 1188, 1191, 1197, 1203, 1212, 1218, 1227, 1236, 1248, 1254, 1263, 1272, 1284,
1293, 1305, 1317, 1326, 1332, 1341, 1350, 1362, 1371, 1383, 1395, 1410, 1419, 1425, 1437, 1446, 1458, 1467, 1482, 1488,
1494, 1503, 1512, 1524, 1533, 1545, 1557, 1572, 1581, 1593, 1605, 1620, 1632, 1647, 1662, 1674, 1683, 1695, 1707, 1716,
1728, 1743, 1758, 1770, 1782, 1791, 1806, 1812, 1827, 1839, 1845, 1848, 1854, 1863, 1872, 1884, 1893, 1905, 1917, 1932,
1941, 1953, 1965, 1980, 1986, 1995, 2004, 2010, 2019, 2031, 2043, 2058, 2070, 2085, 2100, 2106, 2118, 2127, 2142, 2154,
2163, 2169, 2181, 2184, 2193, 2205, 2217, 2232, 2244, 2259, 2268, 2280, 2292, 2307, 2322, 2328, 2337, 2349, 2355, 2358,
2364, 2373, 2382, 2388, 2397, 2409, 2415, 2418, 2427, 2433, 2445, 2448, 2454, 2457, 2460, 2460 };
int marchingCubesIds[2460] = {
0, 8, 3, 0, 1, 9, 1, 8, 3, 9, 8, 1, 1, 2, 10, 0, 8, 3, 1, 2, 10, 9, 2, 10, 0, 2, 9, 2, 8, 3, 2,
10, 8, 10, 9, 8, 3, 11, 2, 0, 11, 2, 8, 11, 0, 1, 9, 0, 2, 3, 11, 1, 11, 2, 1, 9, 11, 9, 8, 11, 3,
10, 1, 11, 10, 3, 0, 10, 1, 0, 8, 10, 8, 11, 10, 3, 9, 0, 3, 11, 9, 11, 10, 9, 9, 8, 10, 10, 8, 11, 4,
7, 8, 4, 3, 0, 7, 3, 4, 0, 1, 9, 8, 4, 7, 4, 1, 9, 4, 7, 1, 7, 3, 1, 1, 2, 10, 8, 4, 7, 3,
4, 7, 3, 0, 4, 1, 2, 10, 9, 2, 10, 9, 0, 2, 8, 4, 7, 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, 8,
4, 7, 3, 11, 2, 11, 4, 7, 11, 2, 4, 2, 0, 4, 9, 0, 1, 8, 4, 7, 2, 3, 11, 4, 7, 11, 9, 4, 11, 9,
11, 2, 9, 2, 1, 3, 10, 1, 3, 11, 10, 7, 8, 4, 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, 4, 7, 8, 9,
0, 11, 9, 11, 10, 11, 0, 3, 4, 7, 11, 4, 11, 9, 9, 11, 10, 9, 5, 4, 9, 5, 4, 0, 8, 3, 0, 5, 4, 1,
5, 0, 8, 5, 4, 8, 3, 5, 3, 1, 5, 1, 2, 10, 9, 5, 4, 3, 0, 8, 1, 2, 10, 4, 9, 5, 5, 2, 10, 5,
4, 2, 4, 0, 2, 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, 9, 5, 4, 2, 3, 11, 0, 11, 2, 0, 8, 11, 4,
9, 5, 0, 5, 4, 0, 1, 5, 2, 3, 11, 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, 10, 3, 11, 10, 1, 3, 9,
5, 4, 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, 5, 4, 8, 5,
8, 10, 10, 8, 11, 9, 7, 8, 5, 7, 9, 9, 3, 0, 9, 5, 3, 5, 7, 3, 0, 7, 8, 0, 1, 7, 1, 5, 7, 1,
5, 3, 3, 5, 7, 9, 7, 8, 9, 5, 7, 10, 1, 2, 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, 8, 0, 2, 8,
2, 5, 8, 5, 7, 10, 5, 2, 2, 10, 5, 2, 5, 3, 3, 5, 7, 7, 9, 5, 7, 8, 9, 3, 11, 2, 9, 5, 7, 9,
7, 2, 9, 2, 0, 2, 7, 11, 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, 11, 2, 1, 11, 1, 7, 7, 1, 5, 9,
5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, 11, 10, 0, 11,
0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, 11, 10, 5, 7, 11, 5, 10, 6, 5, 0, 8, 3, 5, 10, 6, 9, 0, 1, 5,
10, 6, 1, 8, 3, 1, 9, 8, 5, 10, 6, 1, 6, 5, 2, 6, 1, 1, 6, 5, 1, 2, 6, 3, 0, 8, 9, 6, 5, 9,
0, 6, 0, 2, 6, 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, 2, 3, 11, 10, 6, 5, 11, 0, 8, 11, 2, 0, 10,
6, 5, 0, 1, 9, 2, 3, 11, 5, 10, 6, 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, 6, 3, 11, 6, 5, 3, 5,
1, 3, 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, 6, 5, 9, 6,
9, 11, 11, 9, 8, 5, 10, 6, 4, 7, 8, 4, 3, 0, 4, 7, 3, 6, 5, 10, 1, 9, 0, 5, 10, 6, 8, 4, 7, 10,
6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, 6, 1, 2, 6, 5, 1, 4, 7, 8, 1, 2, 5, 5, 2, 6, 3, 0, 4, 3,
4, 7, 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, 3,
11, 2, 7, 8, 4, 10, 6, 5, 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, 0, 1, 9, 4, 7, 8, 2, 3, 11, 5,
10, 6, 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, 5,
1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, 6,
5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, 10, 4, 9, 6, 4, 10, 4, 10, 6, 4, 9, 10, 0, 8, 3, 10, 0, 1, 10,
6, 0, 6, 4, 0, 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, 1, 4, 9, 1, 2, 4, 2, 6, 4, 3, 0, 8, 1,
2, 9, 2, 4, 9, 2, 6, 4, 0, 2, 4, 4, 2, 6, 8, 3, 2, 8, 2, 4, 4, 2, 6, 10, 4, 9, 10, 6, 4, 11,
2, 3, 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, 6, 4, 1, 6,
1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, 8, 11, 1, 8, 1, 0, 11,
6, 1, 9, 1, 4, 6, 4, 1, 3, 11, 6, 3, 6, 0, 0, 6, 4, 6, 4, 8, 11, 6, 8, 7, 10, 6, 7, 8, 10, 8,
9, 10, 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, 10, 6, 7, 10,
7, 1, 1, 7, 3, 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7,
3, 9, 7, 8, 0, 7, 0, 6, 6, 0, 2, 7, 3, 2, 6, 7, 2, 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, 2,
0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, 11,
2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, 0, 9, 1, 11,
6, 7, 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, 7, 11, 6, 7, 6, 11, 3, 0, 8, 11, 7, 6, 0, 1, 9, 11,
7, 6, 8, 1, 9, 8, 3, 1, 11, 7, 6, 10, 1, 2, 6, 11, 7, 1, 2, 10, 3, 0, 8, 6, 11, 7, 2, 9, 0, 2,
10, 9, 6, 11, 7, 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, 7, 2, 3, 6, 2, 7, 7, 0, 8, 7, 6, 0, 6,
2, 0, 2, 7, 6, 2, 3, 7, 0, 1, 9, 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, 10, 7, 6, 10, 1, 7, 1,
3, 7, 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, 7, 6, 10, 7,
10, 8, 8, 10, 9, 6, 8, 4, 11, 8, 6, 3, 6, 11, 3, 0, 6, 0, 4, 6, 8, 6, 11, 8, 4, 6, 9, 0, 1, 9,
4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, 6, 8, 4, 6, 11, 8, 2, 10, 1, 1, 2, 10, 3, 0, 11, 0, 6, 11, 0,
4, 6, 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, 8,
2, 3, 8, 4, 2, 4, 6, 2, 0, 4, 2, 4, 6, 2, 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, 1, 9, 4, 1,
4, 2, 2, 4, 6, 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, 10, 1, 0, 10, 0, 6, 6, 0, 4, 4, 6, 3, 4,
3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, 10, 9, 4, 6, 10, 4, 4, 9, 5, 7, 6, 11, 0, 8, 3, 4, 9, 5, 11,
7, 6, 5, 0, 1, 5, 4, 0, 7, 6, 11, 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, 9, 5, 4, 10, 1, 2, 7,
6, 11, 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, 3, 4, 8, 3,
5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, 7, 2, 3, 7, 6, 2, 5, 4, 9, 9, 5, 4, 0, 8, 6, 0, 6, 2, 6,
8, 7, 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, 9,
5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, 4, 0, 10, 4,
10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, 6, 9, 5, 6, 11, 9, 11,
8, 9, 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, 6, 11, 3, 6,
3, 5, 5, 3, 1, 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1,
2, 10, 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, 5,
8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, 9, 5, 6, 9, 6, 0, 0, 6, 2, 1, 5, 8, 1, 8, 0, 5, 6, 8, 3,
8, 2, 6, 2, 8, 1, 5, 6, 2, 1, 6, 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, 10, 1, 0, 10,
0, 6, 9, 5, 0, 5, 6, 0, 0, 3, 8, 5, 6, 10, 10, 5, 6, 11, 5, 10, 7, 5, 11, 11, 5, 10, 11, 7, 5, 8,
3, 0, 5, 11, 7, 5, 10, 11, 1, 9, 0, 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, 11, 1, 2, 11, 7, 1, 7,
5, 1, 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, 7, 5, 2, 7,
2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, 2, 5, 10, 2, 3, 5, 3, 7, 5, 8, 2, 0, 8, 5, 2, 8, 7, 5, 10,
2, 5, 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, 1,
3, 5, 3, 7, 5, 0, 8, 7, 0, 7, 1, 1, 7, 5, 9, 0, 3, 9, 3, 5, 5, 3, 7, 9, 8, 7, 5, 9, 7, 5,
8, 4, 5, 10, 8, 10, 11, 8, 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, 0, 1, 9, 8, 4, 10, 8, 10, 11, 10,
4, 5, 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, 0,
4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, 9,
4, 5, 2, 11, 3, 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, 5, 10, 2, 5, 2, 4, 4, 2, 0, 3, 10, 2, 3,
5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, 8, 4, 5, 8, 5, 3, 3,
5, 1, 0, 4, 5, 1, 0, 5, 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, 9, 4, 5, 4, 11, 7, 4, 9, 11, 9,
10, 11, 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, 3, 1, 4, 3,
4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, 9, 7, 4, 9, 11, 7, 9,
1, 11, 2, 11, 1, 0, 8, 3, 11, 7, 4, 11, 4, 2, 2, 4, 0, 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, 2,
9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, 3, 7, 10, 3,
10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, 1, 10, 2, 8, 7, 4, 4, 9, 1, 4, 1, 7, 7, 1, 3, 4, 9, 1, 4,
1, 7, 0, 8, 1, 8, 7, 1, 4, 0, 3, 7, 4, 3, 4, 8, 7, 9, 10, 8, 10, 11, 8, 3, 0, 9, 3, 9, 11, 11,
9, 10, 0, 1, 10, 0, 10, 8, 8, 10, 11, 3, 1, 10, 11, 3, 10, 1, 2, 11, 1, 11, 9, 9, 11, 8, 3, 0, 9, 3,
9, 11, 1, 2, 9, 2, 11, 9, 0, 2, 11, 8, 0, 11, 3, 2, 11, 2, 3, 8, 2, 8, 10, 10, 8, 9, 9, 10, 2, 0,
9, 2, 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, 1, 10, 2, 1, 3, 8, 9, 1, 8, 0, 9, 1, 0, 3, 8 };
}
}
#endif
| 11,988 | C | 67.508571 | 121 | 0.436937 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtVoxelTetrahedralizer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_VOXEL_TETRAHEDRALIZER_H
#define EXT_VOXEL_TETRAHEDRALIZER_H
#include "ExtMultiList.h"
#include "ExtBVH.h"
#include "foundation/PxVec3.h"
#include "foundation/PxBounds3.h"
namespace physx
{
namespace Ext
{
// ------------------------------------------------------------------------------
class VoxelTetrahedralizer
{
public:
VoxelTetrahedralizer();
void clear();
void createTetMesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds,
PxI32 resolution, PxI32 numRelaxationIters = 5, PxF32 relMinTetVolume = 0.05f);
void readBack(PxArray<PxVec3>& tetVertices, PxArray<PxU32>& tetIndices);
private:
void voxelize(PxU32 resolution);
void createTets(bool subdivBorder, PxU32 numTetsPerVoxel);
void buildBVH();
void createUniqueTetVertices();
void findTargetPositions(PxF32 surfaceDist);
void conserveVolume(PxF32 relMinVolume);
void relax(PxI32 numIters, PxF32 relMinVolume);
// input mesh
PxArray<PxVec3> surfaceVerts;
PxArray<PxI32> surfaceTriIds;
PxBounds3 surfaceBounds;
// voxel grid
struct Voxel {
void init(PxI32 _xi, PxI32 _yi, PxI32 _zi)
{
xi = _xi; yi = _yi; zi = _zi;
for (PxI32 i = 0; i < 6; i++)
neighbors[i] = -1;
for (PxI32 i = 0; i < 8; i++)
ids[i] = -1;
parent = -1;
inner = false;
}
bool isAt(PxI32 _xi, PxI32 _yi, PxI32 _zi) {
return xi == _xi && yi == _yi && zi == _zi;
}
PxI32 xi, yi, zi;
PxI32 neighbors[6];
PxI32 parent;
PxI32 ids[8];
bool inner;
};
PxVec3 gridOrigin;
PxF32 gridSpacing;
PxArray<Voxel> voxels;
BVHDesc bvh;
// tet mesh
PxArray<PxVec3> tetVerts;
PxArray<PxVec3> origTetVerts;
PxArray<PxI32> tetIds;
// relaxation
PxArray<bool> isSurfaceVert;
PxArray<PxVec3> targetVertPos;
PxArray<PxI32> queryTris;
PxArray<PxI32> edgeIds;
};
}
}
#endif
| 3,601 | C | 29.786325 | 83 | 0.691752 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtInsideTester.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_INSIDE_TESTER_H
#define EXT_INSIDE_TESTER_H
// MM: tester whether a point is inside a triangle mesh
// all faces are projected onto the 3 canonical planes and hashed
// for fast ray mesh intersections
#include "foundation/PxVec3.h"
#include "foundation/PxArray.h"
#include "foundation/PxQuat.h"
#include "CmRandom.h"
namespace physx
{
namespace Ext
{
// ----------------------------------------------------------
class InsideTester
{
public:
void init(const PxVec3 *vertices, PxI32 numVertices, const PxI32 *triIndices, PxI32 numTris);
bool isInside(const PxVec3& pos);
private:
PxArray<PxVec3> mVertices;
PxArray<PxI32> mIndices;
struct Grid2d
{
void init(PxI32 dim0, const PxArray<PxVec3> &vertices, const PxArray<PxI32> &indices);
PxI32 numInside(const PxVec3&pos, const PxArray<PxVec3> &vertices, const PxArray<PxI32> &indices);
PxI32 dim0;
PxVec3 orig;
PxI32 num1, num2;
float spacing;
PxArray<PxI32> first;
PxArray<PxI32> tris;
PxArray<int> next;
Cm::RandomR250 rnd = Cm::RandomR250(0);
};
Grid2d mGrids[3];
};
}
}
#endif
| 2,826 | C | 35.714285 | 102 | 0.724699 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMeshSimplificator.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_MESH_SIMPLIFICATOR_H
#define EXT_MESH_SIMPLIFICATOR_H
#include "foundation/PxBounds3.h"
#include "foundation/PxArray.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "ExtQuadric.h"
#include "ExtRandomAccessHeap.h"
#include "GuSDF.h"
// ------------------------------------------------------------------------------
// MM: implementation of paper Garland and Heckbert: "Surface Simplification Using Quadric Error Metrics"
namespace physx
{
namespace Ext
{
struct PxVec3Ex
{
PxVec3 p;
PxU32 i = 0xFFFFFFFF;
explicit PxVec3Ex() : p(0.0f), i(0xFFFFFFFF)
{
}
explicit PxVec3Ex(PxVec3 point, PxU32 sourceTriangleIndex = 0xFFFFFFFF) : p(point), i(sourceTriangleIndex)
{
}
};
class MeshSimplificator
{
public:
MeshSimplificator();
void init(const PxSimpleTriangleMesh& inputMesh, PxReal edgeLengthCostWeight_ = 1e-1f, PxReal flatnessDetectionThreshold_ = 1e-2f, bool projectSimplifiedPointsOnInputMeshSurface = false);
void init(const PxArray<PxVec3> &vertices, const PxArray<PxU32> &triIds, PxReal edgeLengthCostWeight_ = 1e-1f, PxReal flatnessDetectionThreshold_ = 1e-2f, bool projectSimplifiedPointsOnInputMeshSurface = false);
void decimateByRatio(PxF32 relativeOutputMeshSize = 0.5f, PxF32 maximalEdgeLength = 0.0f);
void decimateBySize(PxI32 targetTriangleCount, PxF32 maximalEdgeLength = 0.0f);
void readBack(PxArray<PxVec3>& vertices, PxArray<PxU32>& triIds, PxArray<PxU32> *vertexMap = NULL, PxArray<PxU32> *outputVertexToInputTriangle = NULL);
~MeshSimplificator();
private:
PxArray<PxVec3Ex> vertices;
PxArray<PxI32> triIds;
PxArray<PxVec3> scaledOriginalVertices;
PxArray<PxU32> originalTriIds;
Gu::PxPointOntoTriangleMeshProjector* projector;
void init();
bool step(PxF32 maximalEdgeLength);
bool getAdjTris(PxI32 triNr, PxI32 vertNr, PxI32& valence, bool& open,
PxArray<PxI32>* tris) const;
bool getAdjTris(PxI32 triNr, PxI32 vertNr, PxArray<PxI32>& tris) const;
void replaceNeighbor(PxI32 triNr, PxI32 oldNeighbor, PxI32 newNeighbor);
PxI32 getEdgeId(PxI32 triNr, PxI32 edgeNr);
bool collapseEdge(PxI32 triNr, PxI32 edgeNr);
PxVec3Ex evalEdgeCost(PxI32 triNr, PxI32 edgeNr, PxReal& costt);
PxVec3Ex projectPoint(const PxVec3& p);
void findTriNeighbors();
void transformPointsToUnitBox(PxArray<PxVec3Ex>& points);
void transformPointsToOriginalPosition(PxArray<PxVec3>& points);
PxI32 numMeshTris;
PxArray<Quadric> quadrics;
PxArray<PxI32> vertMarks;
PxArray<PxI32> adjTris;
PxI32 currentVertMark;
PxArray<PxI32> triNeighbors;
//Scale input points into 0...1 unit-box
PxReal scaling;
PxVec3 origin;
PxReal edgeLengthCostWeight;
PxReal flatnessDetectionThreshold;
PxArray<PxI32> simplificationMap;
struct HeapElem
{
HeapElem() : triNr(0), edgeNr(0), cost(0.0f) {}
HeapElem(PxI32 triNr_, PxI32 edgeNr_, float cost_) :
triNr(triNr_), edgeNr(edgeNr_), cost(cost_) {}
PxI32 triNr, edgeNr;
float cost;
PX_FORCE_INLINE bool operator < (const HeapElem& e) const
{
return cost < e.cost;
}
};
RandomAccessHeap<HeapElem> heap;
};
}
}
#endif
| 4,756 | C | 33.977941 | 214 | 0.730866 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetUnionFind.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 UNION_FIND_H
#define UNION_FIND_H
#include "foundation/PxArray.h"
namespace physx
{
namespace Ext
{
class UnionFind {
public:
UnionFind() {}
UnionFind(PxI32 numSets) { init(numSets); }
void init(PxI32 numSets);
PxI32 find(PxI32 x);
void makeSet(PxI32 x, PxI32 y);
PxI32 computeSetNrs();
PxI32 getSetNr(PxI32 x);
private:
struct Entry {
PxI32 parent, rank;
PxI32 setNr;
};
PxArray<Entry> mEntries;
};
}
}
#endif
| 2,019 | C | 32.666666 | 74 | 0.7474 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMeshSimplificator.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 "ExtMeshSimplificator.h"
#include "foundation/PxSort.h"
namespace physx
{
namespace Ext
{
// -------------------------------------------------------------------------------------
MeshSimplificator::MeshSimplificator()
{
currentVertMark = 0;
numMeshTris = 0;
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::findTriNeighbors()
{
PxI32 numTris = PxI32(triIds.size()) / 3;
triNeighbors.clear();
triNeighbors.resize(3 * numTris, -1);
struct Edge
{
PX_FORCE_INLINE void init(PxI32 _id0, PxI32 _id1, PxI32 _triNr, PxI32 _edgeNr)
{
this->id0 = PxMin(_id0, _id1);
this->id1 = PxMax(_id0, _id1);
this->triNr = _triNr;
this->edgeNr = _edgeNr;
}
PX_FORCE_INLINE bool operator < (const Edge& e) const
{
return (id0 < e.id0 || (id0 == e.id0 && id1 < e.id1));
}
PX_FORCE_INLINE bool operator == (const Edge& e) const
{
return id0 == e.id0 && id1 == e.id1;
}
PxI32 id0, id1, triNr, edgeNr;
};
PxArray<Edge> edges(PxI32(triIds.size()));
for (PxI32 i = 0; i < numTris; i++)
{
for (PxI32 j = 0; j < 3; j++)
{
PxI32 id0 = triIds[3 * i + j];
PxI32 id1 = triIds[3 * i + (j + 1) % 3];
edges[3 * i + j].init(id0, id1, i, j);
}
}
PxSort(edges.begin(), edges.size());
PxI32 nr = 0;
while (nr < PxI32(edges.size()))
{
Edge& e0 = edges[nr];
nr++;
while (nr < PxI32(edges.size()) && edges[nr] == e0)
{
Edge& e1 = edges[nr];
triNeighbors[3 * e0.triNr + e0.edgeNr] = e1.triNr;
triNeighbors[3 * e1.triNr + e1.edgeNr] = e0.triNr;
nr++;
}
}
}
// -------------------------------------------------------------------------------------
bool MeshSimplificator::getAdjTris(PxI32 triNr, PxI32 vertNr, PxI32& valence, bool& open, PxArray<PxI32>* tris) const
{
open = false;
if (tris)
tris->clear();
PxI32 cnt = 0;
valence = 0;
PxI32 nr = triNr;
// counter clock
do
{
if (tris)
tris->pushBack(nr);
valence++;
if (triIds[3 * nr] == vertNr)
nr = triNeighbors[3 * nr + 2];
else if (triIds[3 * nr + 1] == vertNr)
nr = triNeighbors[3 * nr];
else
nr = triNeighbors[3 * nr + 1];
cnt++;
}
while (nr >= 0 && nr != triNr && cnt < 100);
if (cnt >= 100)
{
valence = 0;
return false;
}
cnt = 0;
if (nr < 0)
{ // open: search clockwise too
open = true;
nr = triNr;
do
{
if (nr != triNr)
{
if (tris)
tris->pushBack(nr);
valence++;
}
if (triIds[3 * nr] == vertNr)
nr = triNeighbors[3 * nr];
else if (triIds[3 * nr + 1] == vertNr)
nr = triNeighbors[3 * nr + 1];
else
nr = triNeighbors[3 * nr + 2];
cnt++;
}
while (nr >= 0 && nr != triNr && cnt < 100);
valence++; // num tris + 1 if open
if (cnt > 100)
{
valence = 0;
return false;
}
}
return true;
}
// -------------------------------------------------------------------------------------
bool MeshSimplificator::getAdjTris(PxI32 triNr, PxI32 vertNr, PxArray<PxI32>& tris) const
{
PxI32 valence;
bool open;
return getAdjTris(triNr, vertNr, valence, open, &tris);
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::replaceNeighbor(PxI32 triNr, PxI32 oldNeighbor, PxI32 newNeighbor)
{
if (triNr < 0)
return;
for (PxI32 i = 0; i < 3; i++)
{
if (triNeighbors[3 * triNr + i] == oldNeighbor)
triNeighbors[3 * triNr + i] = newNeighbor;
}
}
// -------------------------------------------------------------------------------------
PxI32 MeshSimplificator::getEdgeId(PxI32 triNr, PxI32 edgeNr)
{
PxI32 n = triNeighbors[3 * triNr + edgeNr];
if (n < 0 || triNr < n)
return 3 * triNr + edgeNr;
else
{
for (PxI32 i = 0; i < 3; i++)
{
if (triNeighbors[3 * n + i] == triNr)
return 3 * n + i;
}
}
return 0;
}
inline PxVec3Ex MeshSimplificator::projectPoint(const PxVec3& p)
{
PxU32 triangleId;
PxVec3 pos = projector->projectPoint(p, triangleId);
return PxVec3Ex(pos, triangleId);
}
// -------------------------------------------------------------------------------------
PxVec3Ex MeshSimplificator::evalEdgeCost(PxI32 triNr, PxI32 edgeNr, PxReal &cost)
{
const PxI32 numSteps = 10;
cost = -1.0f;
PxI32 id0 = triIds[3 * triNr + edgeNr];
PxI32 id1 = triIds[3 * triNr + (edgeNr + 1) % 3];
PxReal minCost = FLT_MAX;
PxReal maxCost = -FLT_MAX;
Quadric q; q = quadrics[id0] + quadrics[id1];
PxVec3Ex pos;
PxReal edgeLength = (vertices[id0].p - vertices[id1].p).magnitude();
for (PxI32 i = 0; i <= numSteps; i++)
{
float r = 1.0f / numSteps * i;
pos.p = vertices[id0].p * (1.0f - r) + vertices[id1].p * r;
if (projector)
pos = projectPoint(pos.p);
float c = q.outerProduct(pos.p);
c += edgeLengthCostWeight * edgeLength;
if (cost < 0.0f || c < cost)
{
cost = c;
}
if (cost > maxCost)
maxCost = cost;
if (cost < minCost)
minCost = cost;
}
if (maxCost - minCost < flatnessDetectionThreshold)
{
float r = 0.5f;
pos.p = vertices[id0].p * (1.0f - r) + vertices[id1].p * r;
if (projector)
pos = projectPoint(pos.p);
cost = q.outerProduct(pos.p) + edgeLengthCostWeight * edgeLength;
}
return pos;
}
// -------------------------------------------------------------------------------------
bool MeshSimplificator::collapseEdge(PxI32 triNr, PxI32 edgeNr)
{
if (triIds[3 * triNr] == triIds[3 * triNr + 1]) // the triangle deleted
return false;
PxI32 id0 = triIds[3 * triNr + edgeNr];
PxI32 id1 = triIds[3 * triNr + (edgeNr + 1) % 3];
PxI32 id2 = triIds[3 * triNr + (edgeNr + 2) % 3];
PxI32 id3 = -1;
PxI32 n = triNeighbors[3 * triNr + edgeNr];
PxI32 nEdgeNr = 0;
if (n >= 0)
{
if (triNeighbors[3 * n] == triNr) nEdgeNr = 0;
else if (triNeighbors[3 * n + 1] == triNr) nEdgeNr = 1;
else if (triNeighbors[3 * n + 2] == triNr) nEdgeNr = 2;
id3 = triIds[3 * n + (nEdgeNr + 2) % 3];
}
// not legal if there exists id != id0,id1 with (id0,id) and (id1,id) edges
// but (id,id0,id1) is not a triangle
bool OK = getAdjTris(triNr, id0, adjTris);
currentVertMark++;
for (PxI32 i = 0; i < PxI32(adjTris.size()); i++)
{
PxI32 adj = adjTris[i];
for (PxI32 j = 0; j < 3; j++)
vertMarks[triIds[3 * adj + j]] = currentVertMark;
}
OK = OK && getAdjTris(triNr, id1, adjTris);
if (!OK)
return false;
for (PxI32 i = 0; i < PxI32(adjTris.size()); i++)
{
PxI32 adj = adjTris[i];
for (PxI32 j = 0; j < 3; j++)
{
PxI32 id = triIds[3 * adj + j];
if (vertMarks[id] == currentVertMark &&
id != id0 && id != id1 && id != id2 && id != id3)
return false;
}
}
// new center pos
PxReal cost;
PxVec3Ex newPos = evalEdgeCost(triNr, edgeNr, cost);
//PxVec3 newPos = vertices[id0] * (1.0f - ratio) + vertices[id1] * ratio;
// any triangle flips?
for (PxI32 side = 0; side < 2; side++)
{
getAdjTris(triNr, side == 0 ? id0 : id1, adjTris);
PxI32 other = side == 0 ? id1 : id0;
for (PxU32 i = 0; i < adjTris.size(); i++)
{
PxI32 adj = adjTris[i];
PxVec3 p[3], q[3];
bool deleted = false;
for (PxI32 j = 0; j < 3; j++)
{
PxI32 id = triIds[3 * adj + j];
if (id == other)
deleted = true;
p[j] = vertices[id].p;
q[j] = (id == id0 || id == id1) ? newPos.p : p[j];
}
if (!deleted)
{
PxVec3 n0 = (p[1] - p[0]).cross(p[2] - p[0]);
PxVec3 n1 = (q[1] - q[0]).cross(q[2] - q[0]);
if (n0.dot(n1) <= 0.0f)
return false;
}
}
}
// remove adjacent edges from heap
for (PxI32 side = 0; side < 2; side++)
{
PxI32 id = side == 0 ? id0 : id1;
getAdjTris(triNr, id, adjTris);
for (PxU32 i = 0; i < adjTris.size(); i++)
{
PxI32 adj = adjTris[i];
for (PxI32 j = 0; j < 3; j++)
{
PxI32 adj0 = triIds[3 * adj + j];
PxI32 adj1 = triIds[3 * adj + (j + 1) % 3];
if (adj0 == id0 || adj0 == id1 || adj1 == id0 || adj1 == id1)
{
PxI32 edgeId = getEdgeId(adj, j);
heap.remove(edgeId);
}
}
}
}
// move vertex
if (id0 > id1) {
int id = id0; id0 = id1; id1 = id;
}
vertices[id0] = newPos;
quadrics[id0] += quadrics[id1];
// collapse edge
getAdjTris(triNr, id1, adjTris);
for (PxU32 i = 0; i < adjTris.size(); i++)
{
PxI32 adj = adjTris[i];
for (PxI32 j = 0; j < 3; j++) {
PxI32& id = triIds[3 * adj + j];
if (id == id1)
id = id0;
}
}
simplificationMap[id1] = id0;
// mark triangles as deleted (duplicate indices, can still be rendered)
triIds[3 * triNr + 2] = triIds[3 * triNr + 1] = triIds[3 * triNr];
numMeshTris--;
if (n >= 0)
{
triIds[3 * n + 2] = triIds[3 * n + 1] = triIds[3 * n];
numMeshTris--;
}
// update neighbors
PxI32 right = triNeighbors[3 * triNr + (edgeNr + 1) % 3];
PxI32 left = triNeighbors[3 * triNr + (edgeNr + 2) % 3];
replaceNeighbor(right, triNr, left);
replaceNeighbor(left, triNr, right);
PxI32 startTriNr = PxMax(right, left);
if (n >= 0)
{
right = triNeighbors[3 * n + (nEdgeNr + 1) % 3];
left = triNeighbors[3 * n + (nEdgeNr + 2) % 3];
replaceNeighbor(right, n, left);
replaceNeighbor(left, n, right);
startTriNr = PxMax(startTriNr, PxMax(right, left));
}
// add new edges to heap
if (startTriNr >= 0)
{
getAdjTris(startTriNr, id0, adjTris);
for (PxU32 i = 0; i < adjTris.size(); i++)
{
PxI32 adj = adjTris[i];
for (PxI32 j = 0; j < 3; j++)
{
PxI32 adj0 = triIds[3 * adj + j];
PxI32 adj1 = triIds[3 * adj + (j + 1) % 3];
if (adj0 == id0 || adj1 == id0)
{
evalEdgeCost(adj, j, cost);
PxI32 id = getEdgeId(adj, j);
heap.insert(HeapElem(adj, j, cost), id);
}
}
}
}
return true;
}
#if PX_LINUX
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
#endif
void minMax(const PxArray<PxVec3Ex>& points, PxVec3& min, PxVec3& max)
{
min = PxVec3(FLT_MAX, FLT_MAX, FLT_MAX);
max = PxVec3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
for (PxU32 i = 0; i < points.size(); ++i)
{
const PxVec3& p = points[i].p;
if (p.x > max.x) max.x = p.x; if (p.y > max.y) max.y = p.y; if (p.z > max.z) max.z = p.z;
if (p.x < min.x) min.x = p.x; if (p.y < min.y) min.y = p.y; if (p.z < min.z) min.z = p.z;
}
}
#if PX_LINUX
#pragma GCC diagnostic pop
#endif
void MeshSimplificator::transformPointsToUnitBox(PxArray<PxVec3Ex>& points)
{
PxVec3 min, max;
minMax(points, min, max);
origin = min;
PxVec3 size = max - min;
scaling = 1.0f / PxMax(PxMax(1e-6f, size.x), PxMax(size.y, size.z));
for (PxU32 i = 0; i < points.size(); ++i)
points[i].p = (points[i].p - min) * scaling;
}
void MeshSimplificator::transformPointsToOriginalPosition(PxArray<PxVec3>& points)
{
PxReal s = 1.0f / scaling;
for (PxU32 i = 0; i < points.size(); ++i)
points[i] = points[i] * s + origin;
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::init(const PxSimpleTriangleMesh& inputMesh, PxReal edgeLengthCostWeight_,
PxReal flatnessDetectionThreshold_, bool projectSimplifiedPointsOnInputMeshSurface)
{
edgeLengthCostWeight = edgeLengthCostWeight_;
flatnessDetectionThreshold = flatnessDetectionThreshold_;
vertices.resize(inputMesh.points.count);
for (PxU32 i = 0; i < inputMesh.points.count; i++)
vertices[i] = PxVec3Ex(inputMesh.points.at<PxVec3>(i));
transformPointsToUnitBox(vertices);
PxI32 numIndices = 3 * inputMesh.triangles.count;
triIds.resize(numIndices);
if (inputMesh.flags & PxMeshFlag::e16_BIT_INDICES)
{
for (PxI32 i = 0; i < numIndices; i++)
triIds[i] = PxI32(inputMesh.triangles.at<PxU16>(i));
}
else
{
for (PxI32 i = 0; i < numIndices; i++)
triIds[i] = PxI32(inputMesh.triangles.at<PxU32>(i));
}
for (PxU32 i = 0; i < triIds.size(); i++)
vertices[triIds[i]].i = i / 3;
if (projectSimplifiedPointsOnInputMeshSurface)
{
originalTriIds.resize(triIds.size());
for (PxU32 i = 0; i < triIds.size(); ++i)
originalTriIds[i] = triIds[i];
scaledOriginalVertices.resize(inputMesh.points.count);
for (PxU32 i = 0; i < inputMesh.points.count; i++)
scaledOriginalVertices[i] = vertices[i].p;
projector = Gu::PxCreatePointOntoTriangleMeshProjector(scaledOriginalVertices.begin(), originalTriIds.begin(), inputMesh.triangles.count);
}
else
projector = NULL;
init();
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::init(const PxArray<PxVec3> &inputVertices, const PxArray<PxU32> &inputTriIds, PxReal edgeLengthCostWeight_,
PxReal flatnessDetectionThreshold_, bool projectSimplifiedPointsOnInputMeshSurface)
{
edgeLengthCostWeight = edgeLengthCostWeight_;
flatnessDetectionThreshold = flatnessDetectionThreshold_;
vertices.resize(inputVertices.size());
for (PxU32 i = 0; i < inputVertices.size(); i++)
vertices[i] = PxVec3Ex(inputVertices[i]);
for (PxU32 i = 0; i < inputTriIds.size(); i++)
vertices[inputTriIds[i]].i = i / 3;
transformPointsToUnitBox(vertices);
triIds.resize(inputTriIds.size());
for (PxU32 i = 0; i < inputTriIds.size(); i++)
triIds[i] = PxI32(inputTriIds[i]);
if (projectSimplifiedPointsOnInputMeshSurface)
{
scaledOriginalVertices.resize(inputVertices.size());
for (PxU32 i = 0; i < inputVertices.size(); i++)
scaledOriginalVertices[i] = vertices[i].p;
projector = Gu::PxCreatePointOntoTriangleMeshProjector(scaledOriginalVertices.begin(), inputTriIds.begin(), inputTriIds.size() / 3);
}
else
projector = NULL;
init();
}
MeshSimplificator::~MeshSimplificator()
{
if (projector)
{
PX_RELEASE(projector)
}
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::init()
{
vertMarks.clear();
vertMarks.resize(vertices.size(), 0);
currentVertMark = 0;
findTriNeighbors();
// init vertex quadrics
quadrics.resize(vertices.size());
for (PxU32 i = 0; i < vertices.size(); i++)
quadrics[i].zero();
Quadric q;
PxI32 numTris = PxI32(triIds.size()) / 3;
for (PxI32 i = 0; i < numTris; i++)
{
PxI32 id0 = triIds[3 * i];
PxI32 id1 = triIds[3 * i + 1];
PxI32 id2 = triIds[3 * i + 2];
q.setFromPlane(vertices[id0].p, vertices[id1].p, vertices[id2].p);
quadrics[id0] += q;
quadrics[id1] += q;
quadrics[id2] += q;
}
// init heap
heap.clear();
for (PxI32 i = 0; i < numTris; i++)
{
for (PxI32 j = 0; j < 3; j++)
{
PxI32 n = triNeighbors[3 * i + j];
if (n < 0 || i < n)
{
PxReal cost;
evalEdgeCost(i, j, cost);
heap.insert(HeapElem(i, j, cost), getEdgeId(i, j));
}
}
}
numMeshTris = numTris;
// init simplification map
simplificationMap.resize(vertices.size());
for (PxI32 i = 0; i < PxI32(vertices.size()); i++)
simplificationMap[i] = i; // each vertex is a root
}
// -------------------------------------------------------------------------------------
bool MeshSimplificator::step(PxF32 maximalEdgeLength)
{
int heapMinSize = 20;
if (heap.size() < heapMinSize)
return false;
while (heap.size() > heapMinSize)
{
HeapElem e = heap.deleteMin();
PxI32 id0 = triIds[3 * e.triNr + e.edgeNr];
PxI32 id1 = triIds[3 * e.triNr + (e.edgeNr + 1) % 3];
PxF32 length = (vertices[id0].p - vertices[id1].p).magnitude();
if (maximalEdgeLength == 0.0f || length < maximalEdgeLength)
{
collapseEdge(e.triNr, e.edgeNr);
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::decimateByRatio(PxF32 relativeOutputMeshSize, PxF32 maximalEdgeLength)
{
relativeOutputMeshSize = PxClamp(relativeOutputMeshSize, 0.1f, 0.99f);
PxI32 numSteps = PxI32(PxFloor(PxF32(heap.size()) * (1.0f - relativeOutputMeshSize)));
for (PxI32 i = 0; i < numSteps; i++)
{
if (!step(maximalEdgeLength))
break;
}
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::decimateBySize(PxI32 targetTriangleCount, PxF32 maximalEdgeLength)
{
while (numMeshTris > targetTriangleCount)
{
if (!step(maximalEdgeLength))
break;
}
}
// -------------------------------------------------------------------------------------
void MeshSimplificator::readBack(PxArray<PxVec3>& outVertices, PxArray<PxU32>& outTriIds, PxArray<PxU32> *vertexMap, PxArray<PxU32> *outputVertexToInputTriangle)
{
outVertices.clear();
outTriIds.clear();
PxArray<PxI32> idMap(vertices.size(), -1);
PxI32 numTris = PxI32(triIds.size()) / 3;
for (PxI32 i = 0; i < numTris; i++)
{
if (triIds[3 * i] == triIds[3 * i + 1]) // deleted
continue;
for (PxI32 j = 0; j < 3; j++)
{
PxI32 id = triIds[3 * i + j];
if (idMap[id] < 0)
{
idMap[id] = outVertices.size();
outVertices.pushBack(vertices[id].p);
if(outputVertexToInputTriangle && projector)
outputVertexToInputTriangle->pushBack(vertices[id].i);
}
outTriIds.pushBack(PxU32(idMap[id]));
}
}
transformPointsToOriginalPosition(outVertices);
if (vertexMap)
{
for (PxU32 i = 0; i < simplificationMap.size(); ++i)
{
PxI32 id = i;
while (id != simplificationMap[id])
{
id = simplificationMap[id];
}
const PxI32 finalLink = id;
id = i;
simplificationMap[i] = finalLink;
while (id != simplificationMap[id])
{
PxI32 oldId = id;
id = simplificationMap[id];
simplificationMap[oldId] = finalLink;
}
}
vertexMap->resize(vertices.size());
for (PxU32 i = 0; i < simplificationMap.size(); ++i)
{
PxI32 mapped = idMap[simplificationMap[i]];
(*vertexMap)[i] = mapped;
}
}
}
}
}
| 20,191 | C++ | 26.472109 | 163 | 0.551483 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtRemesher.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_REMESHER_H
#define EXT_REMESHER_H
#include "foundation/PxBounds3.h"
#include "foundation/PxArray.h"
namespace physx
{
namespace Ext
{
// ------------------------------------------------------------------------------
class Remesher {
public:
Remesher() {}
~Remesher() {}
void remesh(const PxVec3* verts, PxU32 nbVertices, const PxU32* triIds, PxU32 nbTriangleIndices, PxU32 resolution = 100, PxArray<PxU32> *vertexMap = nullptr);
void remesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds, PxU32 resolution = 100, PxArray<PxU32> *vertexMap = nullptr);
void clear();
void readBack(PxArray<PxVec3>& vertices, PxArray<PxU32>& triIds);
private:
PxArray<PxVec3> vertices;
PxArray<PxI32> triIds;
void addCell(PxI32 xi, PxI32 yi, PxI32 zi);
PxI32 getCellNr(PxI32 xi, PxI32 yi, PxI32 zi) const;
bool cellExists(PxI32 xi, PxI32 yi, PxI32 zi) const;
void removeDuplicateVertices();
void pruneInternalSurfaces();
void computeNormals();
void findTriNeighbors();
void project(const PxVec3* inputVerts, const PxU32* inputTriIds, PxU32 nbTriangleIndices,
float searchDist, float surfaceDist);
void createVertexMap(const PxVec3* verts, PxU32 nbVertices, const PxVec3 &gridOrigin, PxF32 &gridSpacing,
PxArray<PxU32> &vertexMap);
// -------------------------------------------------------------------------------------
struct Cell
{
void init(PxI32 _xi, PxI32 _yi, PxI32 _zi) {
this->xi = _xi; this->yi = _yi; this->zi = _zi;
this->next = -1;
}
PxI32 xi, yi, zi;
PxI32 next;
};
PxArray<Cell> cells;
PxArray<PxI32> firstCell;
PxArray<PxVec3> normals;
PxArray<PxI32> triNeighbors;
PxArray<PxI32> cellOfVertex;
PxArray<PxBounds3> bvhBounds;
PxArray<PxI32> bvhTris;
};
}
}
#endif
| 3,394 | C | 34 | 161 | 0.69122 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMultiList.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_MULTI_LIST_H
#define EXT_MULTI_LIST_H
// MM: Multiple linked lists in a common array with a free list
#include "foundation/PxArray.h"
namespace physx
{
namespace Ext
{
//-----------------------------------------------------------------------------
template <class T>
class MultiList {
public:
MultiList(PxI32 maxId = 0) {
firstFree = -1;
if (maxId > 0)
first.reserve(maxId + 1);
}
void reserve(int maxId) {
first.reserve(maxId + 1);
}
void clear();
PxI32 add(PxI32 id, const T &item);
bool addUnique(PxI32 id, const T &item);
bool exists(PxI32 id, const T &item) const;
void remove(PxI32 id, const T &item);
void removeAll(PxI32 id);
PxI32 size(PxI32 id) const;
PxI32 getPairNr(PxI32 id, const T &item) const;
void replace(PxI32 id, const T &before, const T &after);
void getItems(PxI32 id) const;
mutable PxArray<T> queryItems;
void initIteration(PxI32 id, PxI32& iterator);
bool iterate(T& item, PxI32& iterator);
void getPointers(PxI32 id);
mutable PxArray<T*> queryPointers;
private:
PxArray<PxI32> first;
PxArray<T> items;
PxArray<PxI32> next;
PxI32 firstFree;
};
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::clear()
{
first.clear();
next.clear();
items.clear();
queryItems.clear();
queryPointers.clear();
firstFree = -1;
}
//-----------------------------------------------------------------------------
template <class T>
PxI32 MultiList<T>::add(PxI32 id, const T &item)
{
if (id >= PxI32(first.size()))
first.resize(id + 1, -1);
PxI32 pos = firstFree;
if (pos >= 0)
firstFree = next[firstFree];
else
{
pos = PxI32(items.size());
items.resize(items.size() + 1);
next.resize(items.size() + 1);
}
next[pos] = first[id];
first[id] = pos;
items[pos] = item;
return pos;
}
//-----------------------------------------------------------------------------
template <class T>
bool MultiList<T>::addUnique(PxI32 id, const T &item)
{
if (exists(id, item))
return false;
add(id, item);
return true;
}
//-----------------------------------------------------------------------------
template <class T>
bool MultiList<T>::exists(PxI32 id, const T &item) const
{
return getPairNr(id, item) >= 0;
}
//-----------------------------------------------------------------------------
template <class T>
PxI32 MultiList<T>::size(PxI32 id) const
{
if (id >= PxI32(first.size()))
return 0;
PxI32 num = 0;
PxI32 nr = first[id];
while (nr >= 0)
{
num++;
nr = next[nr];
}
return num;
}
//-----------------------------------------------------------------------------
template <class T>
PxI32 MultiList<T>::getPairNr(PxI32 id, const T &item) const
{
if (id < 0 || id >= PxI32(first.size()))
return -1;
PxI32 nr = first[id];
while (nr >= 0)
{
if (items[nr] == item)
return nr;
nr = next[nr];
}
return -1;
}
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::remove(PxI32 id, const T &itemNr)
{
PxI32 nr = first[id];
PxI32 prev = -1;
while (nr >= 0 && items[nr] != itemNr)
{
prev = nr;
nr = next[nr];
}
if (nr < 0)
return;
if (prev >= 0)
next[prev] = next[nr];
else
first[id] = next[nr];
next[nr] = firstFree;
firstFree = nr;
}
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::replace(PxI32 id, const T &before, const T &after)
{
PxI32 nr = first[id];
while (nr >= 0)
{
if (items[nr] == before)
items[nr] = after;
nr = next[nr];
}
}
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::removeAll(PxI32 id)
{
if (id >= PxI32(first.size()))
return;
PxI32 nr = first[id];
if (nr < 0)
return;
PxI32 prev = -1;
while (nr >= 0)
{
prev = nr;
nr = next[nr];
}
next[prev] = firstFree;
firstFree = first[id];
first[id] = -1;
}
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::getItems(PxI32 id) const
{
queryItems.clear();
if (id >= PxI32(first.size()))
return;
PxI32 nr = first[id];
while (nr >= 0)
{
queryItems.push_back(items[nr]);
nr = next[nr];
}
}
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::initIteration(PxI32 id, PxI32& iterator)
{
if (id >= PxI32(first.size()))
iterator = -1;
else
iterator = first[id];
}
//-----------------------------------------------------------------------------
template <class T>
bool MultiList<T>::iterate(T& item, PxI32& iterator)
{
if (iterator >= 0)
{
item = items[iterator];
iterator = next[iterator];
return true;
}
return false;
}
//-----------------------------------------------------------------------------
template <class T>
void MultiList<T>::getPointers(PxI32 id)
{
queryPointers.clear();
if (id >= PxI32(first.size()))
return;
PxI32 nr = first[id];
while (nr >= 0)
{
queryPointers.push_back(&items[nr]);
nr = next[nr];
}
}
}
}
#endif
| 7,212 | C | 25.039711 | 81 | 0.529257 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayBoundaryInserter.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 "ExtDelaunayBoundaryInserter.h"
#include "ExtTetSplitting.h"
#include "ExtFastWindingNumber.h"
#include "ExtTetUnionFind.h"
#include "ExtVec3.h"
#include "foundation/PxSort.h"
#include "foundation/PxBasicTemplates.h"
#include "CmRandom.h"
#include "tet/ExtUtilities.h"
#include "GuAABBTree.h"
#include "GuAABBTreeQuery.h"
#include "GuIntersectionTriangleTriangle.h"
#include "GuIntersectionTetrahedronBox.h"
#include "foundation/PxMathUtils.h"
#include "GuInternal.h"
#include "common/GuMeshAnalysis.h"
#include <stdio.h>
#define PI 3.141592653589793238462643383
namespace physx
{
namespace Ext
{
using namespace Gu;
template<typename T>
bool contains(const PxArray<T>& list, const T& value)
{
for (PxU32 i = 0; i < list.size(); ++i)
if (list[i] == value)
return true;
return false;
}
//Returns a value proportional to the signed volume of the tetrahedron specified by the points a, b, c and d
//Usualy only the result's sign is used in algorithms checking for intersections etc.
PX_FORCE_INLINE PxF64 orient3D(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d)
{
return (a - d).dot((b - d).cross(c - d));
}
PX_FORCE_INLINE PxF64 sign(const PxF64 value)
{
if (value == 0)
return 0.0;
if (value > 0)
return 1.0;
return -1.0;
}
PX_FORCE_INLINE PxF64 signedDistancePointPlane(const PxVec3d& point, const PxVec3d& normal, PxF64 planeD)
{
return point.dot(normal) + planeD;
}
PX_FORCE_INLINE bool lineSegmentIntersectsTriangle(const PxVec3d& segmentStart, const PxVec3d& segmentEnd,
const PxVec3d& triA, const PxVec3d& triB, const PxVec3d& triC, PxVec3d& intersectionPoint)
{
PxVec3d n = (triB - triA).cross(triC - triA);
PxF64 l2 = n.magnitudeSquared();
if (l2 < 1e-12)
return false;
//const PxF64 s = orient3D(segmentStart, triA, triB, triC);
//const PxF64 e = orient3D(segmentEnd, triA, triB, triC);
PxF64 planeD = -n.dot(triA);
PxF64 s = signedDistancePointPlane(segmentStart, n, planeD);
PxF64 e = signedDistancePointPlane(segmentEnd, n, planeD);
if (s == 0 || e == 0)
return false;
if (/*s == 0 || e == 0 ||*/ sign(s) != sign(e))
{
const PxF64 ab = orient3D(segmentStart, segmentEnd, triA, triB);
const PxF64 bc = orient3D(segmentStart, segmentEnd, triB, triC);
const PxF64 ca = orient3D(segmentStart, segmentEnd, triC, triA);
const bool signAB = ab > 0;
const bool signBC = bc > 0;
const bool signCA = ca > 0;
if ((ab == 0 && signBC == signCA) ||
(bc == 0 && signAB == signCA) ||
(ca == 0 && signAB == signBC) ||
(signAB == signBC && signAB == signCA))
{
s = PxAbs(s);
e = PxAbs(e);
intersectionPoint = (segmentEnd * s + segmentStart * e) / (s + e);
return true;
}
return false;
}
else
return false;
}
//Helper class that controls the BVH traversal when checking if a specified edge intersects a triangle mesh with a BVH build around it
//Edges intersecting the triangle mesh are scheduled to get split at the point where they intersect the mesh's surface
class IntersectionFixingTraversalController
{
private:
const PxArray<Triangle>& triangles;
PxArray<PxVec3d>& points;
PxHashMap<PxU64, PxI32>& edgesToSplit;
PxArray<PxArray<PxI32>>& pointToOriginalTriangle;
PxU64 edge;
PxI32 a;
PxI32 b;
//PxF32 minX, minY, minZ, maxX, maxY, maxZ;
PxBounds3 box;
bool repeat = false;
public:
PX_FORCE_INLINE IntersectionFixingTraversalController(const PxArray<Triangle>& triangles_, PxArray<PxVec3d>& points_,
PxHashMap<PxU64, PxI32>& edgesToSplit_, PxArray<PxArray<PxI32>>& pointToOriginalTriangle_) :
triangles(triangles_), points(points_), edgesToSplit(edgesToSplit_), pointToOriginalTriangle(pointToOriginalTriangle_)
{ }
bool shouldRepeat() const { return repeat; }
void resetRepeat() { repeat = false; }
PX_FORCE_INLINE void update(PxU64 e)
{
edge = e;
a = PxI32(e >> 32);
b = PxI32(e);
const PxVec3d& pA = points[a];
const PxVec3d& pB = points[b];
box = PxBounds3(PxVec3(PxF32(PxMin(pA.x, pB.x)), PxF32(PxMin(pA.y, pB.y)), PxF32(PxMin(pA.z, pB.z))),
PxVec3(PxF32(PxMax(pA.x, pB.x)), PxF32(PxMax(pA.y, pB.y)), PxF32(PxMax(pA.z, pB.z))));
}
PX_FORCE_INLINE TraversalControl::Enum analyze(const BVHNode& node, PxI32)
{
if (node.isLeaf())
{
PxI32 j = node.getPrimitiveIndex();
if (!contains(pointToOriginalTriangle[a], PxI32(j)) && !contains(pointToOriginalTriangle[b], PxI32(j)))
{
const Triangle& tri = triangles[j];
const PxVec3d& triA = points[tri[0]];
const PxVec3d& triB = points[tri[1]];
const PxVec3d& triC = points[tri[2]];
PxVec3d intersectionPoint;
if (lineSegmentIntersectsTriangle(points[a], points[b], triA, triB, triC, intersectionPoint))
{
if (edgesToSplit.find(edge) == NULL)
{
edgesToSplit.insert(edge, PxI32(points.size()));
points.pushBack(intersectionPoint);
PxArray<PxI32> arr;
arr.pushBack(j);
pointToOriginalTriangle.pushBack(arr);
}
else
{
repeat = true;
}
}
}
return TraversalControl::eDontGoDeeper;
}
if (node.mBV.intersects(box))
return TraversalControl::eGoDeeper;
return TraversalControl::eDontGoDeeper;
}
private:
PX_NOCOPY(IntersectionFixingTraversalController)
};
#if PX_LINUX
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
#endif
void minMax(const PxArray<PxVec3d>& points, PxVec3d& min, PxVec3d& max)
{
min = PxVec3d(DBL_MAX, DBL_MAX, DBL_MAX);
max = PxVec3d(-DBL_MAX, -DBL_MAX, -DBL_MAX);
for (PxU32 i = 0; i < points.size(); ++i)
{
const PxVec3d& p = points[i];
if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z))
continue;
if (p.x > max.x) max.x = p.x; if (p.y > max.y) max.y = p.y; if (p.z > max.z) max.z = p.z;
if (p.x < min.x) min.x = p.x; if (p.y < min.y) min.y = p.y; if (p.z < min.z) min.z = p.z;
}
}
#if PX_LINUX
#pragma GCC diagnostic pop
#endif
//Creates a delaunay tetrahedralization out of the specified points
void generateDelaunay3D(const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tetrahedra)
{
PxVec3d min, max;
minMax(points, min, max);
DelaunayTetrahedralizer delaunay(min, max);
delaunay.insertPoints(points, 0, points.size(), tetrahedra);
}
PX_FORCE_INLINE PxF64 determinant(const PxVec3d& col1, const PxVec3d& col2, const PxVec3d& col3)
{
return col1.dot(col2.cross(col3));
}
//Simple but slow implementation of winding numbers to determine if a point is inside a mesh or not
//https://igl.ethz.ch/projects/winding-number/robust-inside-outside-segmentation-using-generalized-winding-numbers-siggraph-2013-jacobson-et-al.pdf
PxF64 windingNumber(const PxArray<PxVec3d>& points, const PxArray<Triangle>& triangles, const PxVec3d& p)
{
PxF64 sum = 0;
for (PxU32 i = 0; i < triangles.size(); i++)
{
const Triangle& tri = triangles[i];
const PxVec3d a = points[tri[0]] - p;
const PxVec3d b = points[tri[1]] - p;
const PxVec3d c = points[tri[2]] - p;
PxF64 la = a.magnitude(), lb = b.magnitude(), lc = c.magnitude();
PxF64 omega = atan2(determinant(a, b, c), (la * lb * lc + a.dot(b) * lc + b.dot(c) * la + c.dot(a) * lb));
sum += omega;
}
sum *= 2;
sum /= (4 * PI);
return sum;
}
//Helper class to record the subdivision history of an edge
struct SubdivisionEdge
{
PxI32 Start;
PxI32 End;
PxI32 ChildA;
PxI32 ChildB;
PX_FORCE_INLINE SubdivisionEdge(PxI32 start, PxI32 end, PxI32 childA = -1, PxI32 childB = -1) : Start(start), End(end), ChildA(childA), ChildB(childB) { }
PX_FORCE_INLINE bool HasChildren() const { return ChildA >= 0; }
};
//A memory friendly implementation to compute a full batch of winding numbers for every specified query point in testPoints
void multiWindingNumberMemoryFriendly(const PxArray<PxVec3d>& meshPoints, const PxArray<Triangle>& meshTriangles,
const PxArray<PxVec3d>& testPoints, PxArray<PxF64>& result)
{
PxU32 l = testPoints.size();
result.resize(l);
for (PxU32 i = 0; i < l; ++i)
result[i] = 0.0;
for (PxU32 i = 0; i < meshTriangles.size(); i++)
{
const Triangle& tri = meshTriangles[i];
const PxVec3d aa = meshPoints[tri[0]];
const PxVec3d bb = meshPoints[tri[1]];
const PxVec3d cc = meshPoints[tri[2]];
for (PxU32 j = 0; j < l; ++j)
{
const PxVec3d p = testPoints[j];
PxVec3d a = aa;
PxVec3d b = bb;
PxVec3d c = cc;
a.x -= p.x; a.y -= p.y; a.z -= p.z;
b.x -= p.x; b.y -= p.y; b.z -= p.z;
c.x -= p.x; c.y -= p.y; c.z -= p.z;
const PxF64 la = sqrt(a.x * a.x + a.y * a.y + a.z * a.z),
lb = sqrt(b.x * b.x + b.y * b.y + b.z * b.z),
lc = sqrt(c.x * c.x + c.y * c.y + c.z * c.z);
const PxF64 y = a.x * b.y * c.z - a.x * b.z * c.y - a.y * b.x * c.z + a.y * b.z * c.x + a.z * b.x * c.y - a.z * b.y * c.x;
const PxF64 x = (la * lb * lc + (a.x * b.x + a.y * b.y + a.z * b.z) * lc +
(b.x * c.x + b.y * c.y + b.z * c.z) * la + (c.x * a.x + c.y * a.y + c.z * a.z) * lb);
const PxF64 omega = atan2(y, x);
result[j] += omega;
}
}
PxF64 scaling = 2.0 / (4 * PI);
for (PxU32 i = 0; i < l; ++i)
result[i] *= scaling;
}
//Generates a tetmesh matching the surface of the specified triangle mesh exactly - might insert additional points on the
//triangle mesh's surface. I also provides access about the location of newly created points.
void generateTetmesh(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles,
PxArray<SubdivisionEdge>& allEdges, PxI32& numOriginalEdges, PxArray<PxArray<PxI32>>& pointToOriginalTriangle,
PxI32& numPointsBelongingToMultipleTriangles, PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets)
{
points.resize(trianglePoints.size());
for (PxU32 i = 0; i < trianglePoints.size(); ++i)
points[i] = trianglePoints[i];
PxVec3d min, max;
minMax(points, min, max);
PxHashSet<PxU64> edges;
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
edges.insert(key(tri[0], tri[1]));
edges.insert(key(tri[1], tri[2]));
edges.insert(key(tri[0], tri[2]));
}
numOriginalEdges = PxI32(edges.size());
allEdges.clear();
for (PxHashSet<PxU64>::Iterator iter = edges.getIterator(); !iter.done(); ++iter)
{
allEdges.pushBack(SubdivisionEdge(PxI32((*iter) >> 32), PxI32(*iter)));
}
pointToOriginalTriangle.clear();
for (PxU32 i = 0; i < points.size(); ++i)
pointToOriginalTriangle.pushBack(PxArray<PxI32>());
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
pointToOriginalTriangle[tri[0]].pushBack(i);
pointToOriginalTriangle[tri[1]].pushBack(i);
pointToOriginalTriangle[tri[2]].pushBack(i);
}
for (PxU32 i = 0; i < points.size(); ++i) {
PxArray<PxI32>& list = pointToOriginalTriangle[i];
PxSort(list.begin(), list.size());
}
PxArray<Tetrahedron> tets;
DelaunayTetrahedralizer del(min, max);
PxU32 prevCount = 0;
bool success = true;
PxHashSet<PxU64> tetEdges;
PxArray<PxI32> intersection;
//Subdivide edges and insert new points ond edges into delaunay tetrahedralization until
//all required edges are present in the tetrahedralization
while (success)
{
success = false;
del.insertPoints(points, prevCount, points.size(), tets);
prevCount = points.size();
tetEdges.clear();
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
tetEdges.insert(key(tet[0], tet[1]));
tetEdges.insert(key(tet[0], tet[2]));
tetEdges.insert(key(tet[0], tet[3]));
tetEdges.insert(key(tet[1], tet[2]));
tetEdges.insert(key(tet[1], tet[3]));
tetEdges.insert(key(tet[2], tet[3]));
}
PxU32 l = allEdges.size();
for (PxU32 i = 0; i < l; ++i)
{
SubdivisionEdge e = allEdges[i]; //Copy the edge here because we modify the list below and the reference could get invalid if the list resizes internally
if (e.HasChildren())
continue;
const PxU64 k = key(e.Start, e.End);
if (!tetEdges.contains(k))
{
allEdges.pushBack(SubdivisionEdge(e.Start, PxI32(points.size())));
allEdges.pushBack(SubdivisionEdge(PxI32(points.size()), e.End));
e.ChildA = PxI32(allEdges.size()) - 2;
e.ChildB = PxI32(allEdges.size()) - 1;
allEdges[i] = e; //Write the modified edge back since we did not capture a reference but made a copy
points.pushBack((points[e.Start] + points[e.End]) * 0.5);
intersection.clear();
intersectionOfSortedLists(pointToOriginalTriangle[e.Start], pointToOriginalTriangle[e.End], intersection);
pointToOriginalTriangle.pushBack(intersection);
success = true;
}
}
}
for (PxU32 i = 0; i < tets.size(); ++i)
{
Tetrahedron& tet = tets[i];
if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0)
PxSwap(tet[0], tet[1]);
}
PxHashMap<PxU64, PxI32> edgesToSplit;
numPointsBelongingToMultipleTriangles = PxI32(points.size());
//Split all tetrahedron edges that penetrate the triangle mesh's surface
PxArray<BVHNode> tree;
buildTree(triangles, points, tree);
IntersectionFixingTraversalController controller(triangles, points, edgesToSplit, pointToOriginalTriangle);
for (PxHashSet<PxU64>::Iterator iter = tetEdges.getIterator(); !iter.done(); ++iter)
{
const PxU64 edge = *iter;
controller.update(edge);
traverseBVH(tree.begin(), controller);
}
split(tets, points, edgesToSplit);
//Remove all tetrahedra that are outside of the triangle mesh
PxHashMap<PxU32, ClusterApproximationF64> clusters;
precomputeClusterInformation(tree, triangles, points, clusters);
PxArray<PxF64> windingNumbers;
windingNumbers.resize(tets.size());
PxF64 sign = 1;
PxF64 windingNumberSum = 0;
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
PxVec3d q = (points[tet[0]] + points[tet[1]] + points[tet[2]] + points[tet[3]]) * 0.25;
PxF64 windingNumber = computeWindingNumber(tree, q, 2.0, clusters, triangles, points);
windingNumbers[i] = windingNumber;
windingNumberSum += windingNumber;
}
if (windingNumberSum < 0.0)
sign = -1;
//Array<PxVec3d> tetCenters;
//tetCenters.resize(tets.size());
//for (PxU32 i = 0; i < tets.size(); ++i)
//{
// const Tetrahedron& tet = tets[i];
// tetCenters[i] = (points[tet.A] + points[tet.B] + points[tet.c] + points[tet.D]) * 0.25;
//}
//multiWindingNumberMemoryFriendly(points, triangles, tetCenters, windingNumbers);
finalTets.clear();
for (PxU32 i = 0; i < windingNumbers.size(); ++i)
if (sign * windingNumbers[i] > 0.5)
finalTets.pushBack(tets[i]);
for (PxU32 i = 0; i < finalTets.size(); ++i)
{
Tetrahedron& tet = finalTets[i];
if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0)
PxSwap(tet[0], tet[1]);
}
}
void generateTetmesh(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles,
PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets)
{
PxArray<SubdivisionEdge> allEdges;
PxI32 numOriginalEdges;
PxArray<PxArray<PxI32>> pointToOriginalTriangle;
PxI32 numPointsBelongingToMultipleTriangles;
generateTetmesh(trianglePoints, triangles, allEdges, numOriginalEdges, pointToOriginalTriangle, numPointsBelongingToMultipleTriangles, points, finalTets);
}
static const PxI32 tetFaces[4][3] = { {0, 1, 2}, {0, 3, 1}, {0, 2, 3}, {1, 3, 2} };
void extractTetmeshSurface(const PxArray<PxI32>& tets, PxArray<PxI32>& triangles)
{
PxHashMap<SortedTriangle, PxI32, TriangleHash> tris;
for (PxU32 i = 0; i < tets.size(); i += 4)
{
for (PxU32 j = 0; j < 4; ++j)
{
SortedTriangle tri(tets[i + tetFaces[j][0]], tets[i + tetFaces[j][1]], tets[i + tetFaces[j][2]]);
if (const PxPair<const SortedTriangle, PxI32>* ptr = tris.find(tri))
tris[tri] = ptr->second + 1;
else
tris.insert(tri, 1);
}
}
triangles.clear();
for (PxHashMap<SortedTriangle, PxI32, TriangleHash>::Iterator iter = tris.getIterator(); !iter.done(); ++iter)
{
if (iter->second == 1) {
triangles.pushBack(iter->first.A);
if (iter->first.Flipped)
{
triangles.pushBack(iter->first.C);
triangles.pushBack(iter->first.B);
}
else
{
triangles.pushBack(iter->first.B);
triangles.pushBack(iter->first.C);
}
}
}
}
struct TriangleWithTetLink
{
PxI32 triA;
PxI32 triB;
PxI32 triC;
PxI32 tetId;
TriangleWithTetLink(PxI32 triA_, PxI32 triB_, PxI32 triC_, PxI32 tetId_) : triA(triA_), triB(triB_), triC(triC_), tetId(tetId_)
{}
};
void extractTetmeshSurfaceWithTetLink(const PxArray<Tetrahedron>& tets, PxArray<TriangleWithTetLink>& surface)
{
PxHashMap<SortedTriangle, PxI32, TriangleHash> tris;
for (PxU32 i = 0; i < tets.size(); ++i)
{
if (tets[i][0] < 0)
continue;
for (PxU32 j = 0; j < 4; ++j)
{
SortedTriangle tri(tets[i][tetFaces[j][0]], tets[i][tetFaces[j][1]], tets[i][tetFaces[j][2]]);
if (tris.find(tri))
tris[tri] = -1;
else
tris.insert(tri, i);
}
}
surface.clear();
for (PxHashMap<SortedTriangle, PxI32, TriangleHash>::Iterator iter = tris.getIterator(); !iter.done(); ++iter)
{
if (iter->second >= 0)
surface.pushBack(TriangleWithTetLink(iter->first.A, iter->first.B, iter->first.C, iter->second));
}
}
//Removes vertices not referenced by any tetrahedron and maps the tet's indices to match the compacted vertex list
void removeUnusedVertices(PxArray<PxVec3d>& vertices, PxArray<Tetrahedron>& tets, PxU32 numPointsToKeepAtBeginning = 0)
{
PxArray<PxI32> compressorMap;
compressorMap.resize(vertices.size());
for (PxU32 i = 0; i < numPointsToKeepAtBeginning; ++i)
compressorMap[i] = 0;
for (PxU32 i = numPointsToKeepAtBeginning; i < compressorMap.size(); ++i)
compressorMap[i] = -1;
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
compressorMap[tet[0]] = 0;
compressorMap[tet[1]] = 0;
compressorMap[tet[2]] = 0;
compressorMap[tet[3]] = 0;
}
PxU32 indexer = 0;
for (PxU32 i = 0; i < compressorMap.size(); ++i)
{
if (compressorMap[i] >= 0)
{
compressorMap[i] = indexer;
vertices[indexer] = vertices[i];
indexer++;
}
}
for (PxU32 i = 0; i < tets.size(); ++i)
{
Tetrahedron& tet = tets[i];
if (tet[0] < 0)
continue;
tet[0] = compressorMap[tet[0]];
tet[1] = compressorMap[tet[1]];
tet[2] = compressorMap[tet[2]];
tet[3] = compressorMap[tet[3]];
}
if (indexer < vertices.size())
vertices.removeRange(indexer, vertices.size() - indexer);
}
PxF64 tetQuality(const PxVec3d& p0, const PxVec3d& p1, const PxVec3d& p2, const PxVec3d& p3)
{
const PxVec3d d0 = p1 - p0;
const PxVec3d d1 = p2 - p0;
const PxVec3d d2 = p3 - p0;
const PxVec3d d3 = p2 - p1;
const PxVec3d d4 = p3 - p2;
const PxVec3d d5 = p1 - p3;
PxF64 s0 = d0.magnitudeSquared();
PxF64 s1 = d1.magnitudeSquared();
PxF64 s2 = d2.magnitudeSquared();
PxF64 s3 = d3.magnitudeSquared();
PxF64 s4 = d4.magnitudeSquared();
PxF64 s5 = d5.magnitudeSquared();
PxF64 ms = (1.0 / 6.0) * (s0 + s1 + s2 + s3 + s4 + s5);
PxF64 rms = PxSqrt(ms);
PxF64 s = 12.0 / PxSqrt(2.0);
PxF64 vol = PxAbs((1.0 / 6.0) * d0.dot(d1.cross(d2)));
return s * vol / (rms * rms * rms); // Ideal tet has quality 1
}
//The face must be one of the 4 faces from the tetrahedron, otherwise the result will be incorrect
PX_FORCE_INLINE PxI32 getTetCornerOppositeToFace(const Tetrahedron& tet, PxI32 faceA, PxI32 faceB, PxI32 faceC)
{
return tet[0] + tet[1] + tet[2] + tet[3] - faceA - faceB - faceC;
}
void improveTetmesh(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets, PxI32 numPointsBelongingToMultipleTriangles,
PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxArray<PxArray<PxI32>>& edges, PxI32 numOriginalPoints)
{
DelaunayTetrahedralizer del(points, finalTets);
bool success = true;
//Collapse edges as long as we find collapsible edges
//Only collaps edges such that the input triangle mesh's edges are preserved
while (success)
{
success = false;
PxArray<PxI32> adjTets;
// Try to remove points that are on the interior of an original face
for (PxU32 i = numPointsBelongingToMultipleTriangles; i < points.size(); ++i)
{
PxI32 tri = pointToOriginalTriangle[i][0];
adjTets.forceSize_Unsafe(0);
del.collectTetsConnectedToVertex(i, adjTets);
for (PxU32 j = 0; j < adjTets.size(); ++j)
{
const Tetrahedron& tet = del.tetrahedron(adjTets[j]);
if (tet[0] < 0)
continue;
for (PxI32 k = 0; k < 4; ++k) {
PxI32 id = tet[k];
if (id != PxI32(i) && contains(pointToOriginalTriangle[id], tri))
{
if (del.canCollapseEdge(id, i))
{
del.collapseEdge(id, i);
break;
}
}
}
}
}
// Try to remove points that are on the edge between two original faces
for (PxU32 i = 0; i < edges.size(); ++i)
{
PxArray<PxI32>& edge = edges[i];
if (edge.size() == 2)
continue;
for (PxU32 j = edge.size() - 1; j >= 1; --j)
{
const PxI32 remove = edge[j - 1];
const PxI32 keep = edge[j];
if (remove >= numOriginalPoints && del.canCollapseEdge(keep, remove))
{
del.collapseEdge(keep, remove);
success = true;
edge.remove(j - 1);
}
}
for (PxU32 j = 1; j < edge.size(); ++j)
{
const PxI32 keep = edge[j - 1];
const PxI32 remove = edge[j];
if (remove >= numOriginalPoints && del.canCollapseEdge(keep, remove))
{
del.collapseEdge(keep, remove);
success = true;
edge.remove(j);
--j;
}
}
}
}
optimize(del, pointToOriginalTriangle, numOriginalPoints, points, finalTets, 10);
//Remove sliver tets on surface
success = true;
while (success)
{
success = false;
PxArray<TriangleWithTetLink> surface;
extractTetmeshSurfaceWithTetLink(finalTets, surface);
for (PxU32 i = 0; i < surface.size(); ++i)
{
const TriangleWithTetLink& link = surface[i];
const Tetrahedron& tet = finalTets[link.tetId];
if (tet[0] < 0)
continue;
PxI32 other = getTetCornerOppositeToFace(tet, link.triA, link.triB, link.triC);
const PxVec3d& a = points[link.triA];
const PxVec3d& b = points[link.triB];
const PxVec3d& c = points[link.triC];
PxVec3d n = (b - a).cross(c - a);
//n.normalize();
PxF64 planeD = -(n.dot(a));
PxF64 dist = PxAbs(signedDistancePointPlane(points[other], n, planeD));
if (dist < 1e-4 * n.magnitude())
{
finalTets[link.tetId] = Tetrahedron(-1, -1, -1, -1);
success = true;
}
}
}
PxU32 indexer = 0;
for (PxU32 i = 0; i < finalTets.size(); ++i)
{
const Tetrahedron& tet = finalTets[i];
if (tet[0] >= 0)
finalTets[indexer++] = tet;
}
if (indexer < finalTets.size())
finalTets.removeRange(indexer, finalTets.size() - indexer);
removeUnusedVertices(points, finalTets, numOriginalPoints);
for (PxU32 i = 0; i < finalTets.size(); ++i)
{
Tetrahedron& tet = finalTets[i];
if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0)
PxSwap(tet[0], tet[1]);
}
}
PxU32 removeDisconnectedIslands(PxI32* finalTets, PxU32 numTets)
{
//Detect islands
PxArray<PxI32> neighborhood;
buildNeighborhood(finalTets, numTets, neighborhood);
PxArray<PxI32> tetColors;
tetColors.resize(numTets, -1);
PxU32 start = 0;
PxI32 color = -1;
PxArray<PxI32> stack;
while (true)
{
stack.clear();
while (start < tetColors.size())
{
if (tetColors[start] < 0)
{
stack.pushBack(start);
++color;
tetColors[start] = color;
break;
}
++start;
}
if (start == tetColors.size())
break;
while (stack.size() > 0)
{
PxI32 id = stack.popBack();
for (PxI32 i = 0; i < 4; ++i)
{
PxI32 a = neighborhood[4 * id + i];
PxI32 tetId = a >> 2;
if (tetId >= 0 && tetColors[tetId] == -1)
{
stack.pushBack(tetId);
tetColors[tetId] = color;
}
}
}
}
if (color > 0)
{
//Found more than one island: Count number of tets per color
PxArray<PxU32> numTetsPerColor;
numTetsPerColor.resize(color + 1, 0);
for (PxU32 i = 0; i < tetColors.size(); ++i)
numTetsPerColor[tetColors[i]] += 1;
PxI32 colorWithHighestTetCount = 0;
for (PxU32 i = 1; i < numTetsPerColor.size(); ++i)
if (numTetsPerColor[i] > numTetsPerColor[colorWithHighestTetCount])
colorWithHighestTetCount = i;
PxU32 indexer = 0;
for (PxU32 i = 0; i < numTets; ++i)
{
for (PxU32 j = 0; j < 4; ++j)
finalTets[4 * indexer + j] = finalTets[4 * i + j];
if (tetColors[i] == colorWithHighestTetCount)
++indexer;
}
//if (indexer < finalTets.size())
// finalTets.removeRange(indexer, finalTets.size() - indexer);
return numTets - indexer;
}
return 0;
}
void removeDisconnectedIslands(PxArray<Tetrahedron>& finalTets)
{
PxU32 numRemoveAtEnd = removeDisconnectedIslands(reinterpret_cast<PxI32*>(finalTets.begin()), finalTets.size());
if (numRemoveAtEnd > 0)
finalTets.removeRange(finalTets.size() - numRemoveAtEnd, numRemoveAtEnd);
}
//Generates a tetmesh matching the surface of the specified triangle mesh exactly - might insert additional points on the
//triangle mesh's surface. It will try to remove as many points inserted during construction as possible by applying an
//edge collapse post processing step.
void generateTetsWithCollapse(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles,
PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets)
{
const PxI32 numOriginalPoints = PxI32(trianglePoints.size());
PxArray<PxArray<PxI32>> pointToOriginalTriangle;
PxI32 numPointsBelongingToMultipleTriangles;
PxArray<PxArray<PxI32>> edges;
PxVec3d min, max;
minMax(trianglePoints, min, max);
DelaunayTetrahedralizer del(min, max);
PxArray<Tetrahedron> tets;
del.generateTetmeshEnforcingEdges(trianglePoints, triangles, edges, pointToOriginalTriangle, points, tets);
PxHashSet<PxU64> tetEdges;
numPointsBelongingToMultipleTriangles = points.size();
PxHashMap<PxU64, PxI32> edgesToSplit;
IntersectionFixingTraversalController controller(triangles, points, edgesToSplit, pointToOriginalTriangle);
PxArray<BVHNode> tree;
buildTree(triangles, points, tree);
PxI32 counter = 0;
do
{
controller.resetRepeat();
tetEdges.clear();
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
tetEdges.insert(key(tet[0], tet[1]));
tetEdges.insert(key(tet[0], tet[2]));
tetEdges.insert(key(tet[0], tet[3]));
tetEdges.insert(key(tet[1], tet[2]));
tetEdges.insert(key(tet[1], tet[3]));
tetEdges.insert(key(tet[2], tet[3]));
}
edgesToSplit.clear();
for (PxHashSet<PxU64>::Iterator iter = tetEdges.getIterator(); !iter.done(); ++iter)
{
const PxU64 edge = *iter;
controller.update(edge);
traverseBVH(tree.begin(), controller);
}
split(tets, points, /*remaining*/edgesToSplit);
++counter;
if (counter >= 2)
break;
} while (controller.shouldRepeat());
//Remove all tetrahedra that are outside of the triangle mesh
PxHashMap<PxU32, ClusterApproximationF64> clusters;
precomputeClusterInformation(tree, triangles, points, clusters);
PxArray<PxF64> windingNumbers;
windingNumbers.resize(tets.size());
PxF64 sign = 1;
PxF64 windingNumberSum = 0;
for (PxU32 i = 0; i < tets.size(); ++i)
{
const Tetrahedron& tet = tets[i];
PxVec3d q = (points[tet[0]] + points[tet[1]] + points[tet[2]] + points[tet[3]]) * 0.25;
PxF64 windingNumber = computeWindingNumber(tree, q, 2.0, clusters, triangles, points);
windingNumbers[i] = windingNumber;
windingNumberSum += windingNumber;
}
if (windingNumberSum < 0.0)
sign = -1;
finalTets.clear();
for (PxU32 i = 0; i < windingNumbers.size(); ++i)
if (sign * windingNumbers[i] > 0.5)
finalTets.pushBack(tets[i]);
for (PxU32 i = 0; i < finalTets.size(); ++i)
{
Tetrahedron& tet = finalTets[i];
if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0)
PxSwap(tet[0], tet[1]);
}
improveTetmesh(points, finalTets, numPointsBelongingToMultipleTriangles, pointToOriginalTriangle, edges, numOriginalPoints);
}
bool convexTetmesh(PxArray<PxVec3d>& points, const PxArray<Triangle>& tris, PxArray<Tetrahedron>& tets)
{
PxVec3d centroid = PxVec3d(0.0, 0.0, 0.0);
PxI32 counter = 0;
for (PxU32 i = 0; i < points.size(); ++i)
{
const PxVec3d& p = points[i];
if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z))
continue;
centroid += p;
++counter;
}
centroid /= counter;
PxF64 volSign = 0;
PxU32 centerIndex = points.size();
points.pushBack(centroid);
tets.clear();
tets.reserve(tris.size());
for (PxU32 i = 0; i < tris.size(); ++i)
{
const Triangle& tri = tris[i];
Tetrahedron tet = Tetrahedron(centerIndex, tri[0], tri[1], tri[2]);
const PxF64 vol = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]);
if (vol < 0)
PxSwap(tet[2], tet[3]);
tets.pushBack(tet);
if (volSign == 0)
{
volSign = vol > 0 ? 1 : -1;
}
else if (volSign * vol < 0)
{
points.remove(points.size() - 1);
tets.clear();
return false;
}
}
return true;
}
void convert(const PxArray<PxF32>& points, PxArray<PxVec3d>& result)
{
result.resize(points.size() / 3);
for (PxU32 i = 0; i < result.size(); ++i)
result[i] = PxVec3d(PxF64(points[3 * i]), PxF64(points[3 * i + 1]), PxF64(points[3 * i + 2]));
}
void convert(const PxArray<PxVec3d>& points, PxArray<PxF32>& result)
{
result.resize(3 * points.size());
for (PxU32 i = 0; i < points.size(); ++i)
{
const PxVec3d& p = points[i];
result[3 * i] = PxF32(p.x);
result[3 * i + 1] = PxF32(p.y);
result[3 * i + 2] = PxF32(p.z);
}
}
void convert(const PxArray<PxVec3d>& points, PxArray<PxVec3>& result)
{
result.resize(points.size());
for (PxU32 i = 0; i < points.size(); ++i)
{
const PxVec3d& p = points[i];
result[i] = PxVec3(PxF32(p.x), PxF32(p.y), PxF32(p.z));
}
}
void convert(const PxBoundedData& points, PxArray<PxVec3d>& result)
{
result.resize(points.count);
for (PxU32 i = 0; i < points.count; ++i)
{
const PxVec3& p = points.at<PxVec3>(i);
result[i] = PxVec3d(PxF64(p.x), PxF64(p.y), PxF64(p.z));
}
}
void convert(const PxArray<PxI32>& indices, PxArray<Triangle>& result)
{
//static cast possible?
result.resize(indices.size() / 3);
for (PxU32 i = 0; i < result.size(); ++i)
result[i] = Triangle(indices[3 * i], indices[3 * i + 1], indices[3 * i + 2]);
}
void convert(const PxBoundedData& indices, bool has16bitIndices, PxArray<Triangle>& result)
{
result.resize(indices.count);
if (has16bitIndices)
{
for (PxU32 i = 0; i < indices.count; ++i)
{
const Triangle16& tri = indices.at<Triangle16>(i);
result[i] = Triangle(tri[0], tri[1], tri[2]);
}
}
else
{
for (PxU32 i = 0; i < indices.count; ++i)
result[i] = indices.at<Triangle>(i);
}
}
void convert(const PxArray<Tetrahedron>& tetrahedra, PxArray<PxU32>& result)
{
//static cast possible?
result.resize(4 * tetrahedra.size());
for (PxU32 i = 0; i < tetrahedra.size(); ++i)
{
const Tetrahedron& t = tetrahedra[i];
result[4 * i] = t[0];
result[4 * i + 1] = t[1];
result[4 * i + 2] = t[2];
result[4 * i + 3] = t[3];
}
}
//Keep for debugging & verification
void writeTets(const char* path, const PxArray<PxVec3>& tetPoints, const PxArray<PxU32>& tets)
{
FILE *fp;
fp = fopen(path, "w+");
fprintf(fp, "# Tetrahedral mesh generated using\n\n");
fprintf(fp, "# %d vertices\n", tetPoints.size());
for (PxU32 i = 0; i < tetPoints.size(); ++i)
{
fprintf(fp, "v %f %f %f\n", PxF64(tetPoints[i].x), PxF64(tetPoints[i].y), PxF64(tetPoints[i].z));
}
fprintf(fp, "\n");
fprintf(fp, "# %d tetrahedra\n", (tets.size() / 4));
for (PxU32 i = 0; i < tets.size(); i += 4)
{
fprintf(fp, "t %d %d %d %d\n", tets[i], tets[i + 1], tets[i + 2], tets[i + 3]);
}
fclose(fp);
}
//Keep for debugging & verification
void writeOFF(const char* path, const PxArray<PxF32>& vertices, const PxArray<PxI32>& tris)
{
FILE *fp;
fp = fopen(path, "w+");
fprintf(fp, "OFF\n");
fprintf(fp, "%d %d 0\n", vertices.size() / 3, tris.size() / 3);
for (PxU32 i = 0; i < vertices.size(); i += 3)
{
fprintf(fp, "%f %f %f\n", PxF64(vertices[i]), PxF64(vertices[i + 1]), PxF64(vertices[i + 2]));
}
for (PxU32 i = 0; i < tris.size(); i += 3)
{
fprintf(fp, "3 %d %d %d\n", tris[i], tris[i + 1], tris[i + 2]);
}
fclose(fp);
}
//Keep for debugging & verification
void writeSTL(const char* path, const PxArray<PxVec3>& vertices, const PxArray<PxI32>& tris)
{
FILE *fp;
fp = fopen(path, "w+");
fprintf(fp, "solid mesh\n");
for (PxU32 i = 0; i < tris.size(); i += 3)
{
const PxI32* tri = &tris[i];
const PxVec3& a = vertices[tri[0]];
const PxVec3& b = vertices[tri[1]];
const PxVec3& c = vertices[tri[2]];
PxVec3 n = (b - a).cross(c - a);
n.normalize();
fprintf(fp, "facet normal %f %f %f\n", PxF64(n.x), PxF64(n.y), PxF64(n.z));
fprintf(fp, "%s", "outer loop\n");
fprintf(fp, " vertex %f %f %f\n", PxF64(a.x), PxF64(a.y), PxF64(a.z));
fprintf(fp, " vertex %f %f %f\n", PxF64(b.x), PxF64(b.y), PxF64(b.z));
fprintf(fp, " vertex %f %f %f\n", PxF64(c.x), PxF64(c.y), PxF64(c.z));
fprintf(fp, "%s", "endloop\n");
fprintf(fp, "%s", "endfacet\n");
}
fprintf(fp, "endsolid mesh\n");
fclose(fp);
}
void generateTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTriangles, const bool has16bitIndices,
PxArray<PxVec3>& tetPoints, PxArray<PxU32>& finalTets)
{
//writeOFF("c:\\tmp\\debug.off", trianglePoints, triangles);
PxArray<PxVec3d> points;
convert(inputPoints, points);
PxArray<Triangle> tris;
convert(inputTriangles, has16bitIndices, tris);
//PxTriangleMeshAnalysisResults result = validateTriangleMesh(inputPoints, inputTriangles, has16bitIndices);
//PX_ASSERT(!(result & PxTriangleMeshAnalysisResult::eMESH_IS_INVALID));
PxArray<PxI32> map;
MeshAnalyzer::mapDuplicatePoints<PxVec3d, PxF64>(points.begin(), points.size(), map);
for (PxI32 i = 0; i < PxI32(points.size()); ++i)
{
if(map[i] != i)
points[i] = PxVec3d(PxF64(NAN), PxF64(NAN), PxF64(NAN));
}
for (PxU32 i = 0; i < tris.size(); ++i)
{
Triangle& t = tris[i];
for (PxU32 j = 0; j < 3; ++j)
t[j] = map[t[j]];
if (t[0] == t[1] || t[1] == t[2] || t[0] == t[2])
{
tris[i] = tris[tris.size() - 1];
tris.remove(tris.size() - 1);
--i;
}
}
PxArray<PxVec3d> tetPts;
PxArray<Tetrahedron> tets;
//if (makeTriOrientationConsistent(tris))
{
if (convexTetmesh(points, tris, tets))
{
tetPts.clear();
tetPts.reserve(tris.size());
for (PxU32 i = 0/*l*/; i < map.size(); ++i)
{
tetPts.pushBack(points[map[i]]);
}
for (PxU32 i = map.size(); i < points.size(); ++i)
{
tetPts.pushBack(points[i]);
}
}
else
{
//Transform points such that the are located inside the unit cube
PxVec3d min, max;
minMax(points, min, max);
PxVec3d size = max - min;
PxF64 scaling = 1.0 / PxMax(size.x, PxMax(size.y, size.z));
//Add some noise to avoid geometric degeneracies
Cm::RandomR250 r(0);
PxF64 randomMagnitude = 1e-6;
for (PxU32 i = 0; i < points.size(); ++i)
{
PxVec3d& p = points[i];
p = (p - min) * scaling;
p.x += PxF64(r.rand(-0.5f, 0.5f)) * randomMagnitude;
p.y += PxF64(r.rand(-0.5f, 0.5f)) * randomMagnitude;
p.z += PxF64(r.rand(-0.5f, 0.5f)) * randomMagnitude;
}
generateTetsWithCollapse(points, tris, tetPts, tets);
//Scale back to original size
scaling = 1.0 / scaling;
//for (PxU32 i = 0; i < l; ++i)
// tetPts[i] = PxVec3d(trianglePoints[3 * i], trianglePoints[3 * i + 1], trianglePoints[3 * i + 2]);
for (PxU32 i = 0; i < map.size(); ++i)
{
tetPts[i] = tetPts[map[i]];
}
for (PxU32 i = 0; i < tetPts.size(); ++i)
{
tetPts[i] = tetPts[i] * scaling + min;
}
}
}
convert(tetPts, tetPoints);
convert(tets, finalTets);
//writeTets("c:\\tmp\\bottle.tet", tetPoints, finalTets);
}
PX_FORCE_INLINE PxF32 tetVolume(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d)
{
return (-1.0f / 6.0f) * (a - d).dot((b - d).cross(c - d));
}
void pointMasses(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxF32 density, PxArray<PxF32>& mass)
{
mass.resize(tetVerts.size());
for (PxU32 i = 0; i < mass.size(); ++i)
mass[i] = 0.0f;
//const PxVec3* verts = (PxVec3*)&tetVerts[0];
for (PxU32 i = 0; i < tets.size(); i += 4)
{
PxF32 weightDiv4 = density * 0.25f * PxAbs(tetVolume(tetVerts[tets[i]], tetVerts[tets[i + 1]], tetVerts[tets[i + 2]], tetVerts[tets[i + 3]]));
mass[tets[i]] += weightDiv4;
mass[tets[i + 1]] += weightDiv4;
mass[tets[i + 2]] += weightDiv4;
mass[tets[i + 3]] += weightDiv4;
}
}
void restPoses(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxArray<PxMat33>& restPoses)
{
restPoses.resize(tets.size() / 4);
//const PxVec3* verts = (PxVec3*)&tetVerts[0];
for (PxU32 i = 0; i < tets.size(); i += 4)
{
const PxVec3 u1 = tetVerts[tets[i + 1]] - tetVerts[tets[i]];
const PxVec3 u2 = tetVerts[tets[i + 2]] - tetVerts[tets[i]];
const PxVec3 u3 = tetVerts[tets[i + 3]] - tetVerts[tets[i]];
const PxMat33 m = PxMat33(u1, u2, u3);
const PxMat33 rest = m.getInverse();
restPoses[i / 4] = rest;
}
}
void tetFibers(const PxArray<PxVec3>& /*tetVerts*/, const PxArray<PxU32>& tets, PxArray<PxVec3>& tetFibers)
{
//Just use dummy data for the moment. Could solve a heat equation on the tetmesh to get better fibers but the boundary conditions of the heat quations need to be known
tetFibers.resize(tets.size() / 4);
for (PxU32 i = 0; i < tets.size(); i += 4)
{
tetFibers[i / 4] = PxVec3(1.0f, 0.f, 0.f);
}
}
void minMax(const PxBoundedData& points, PxVec3& min, PxVec3& max)
{
min = PxVec3(PX_MAX_F32);
max = PxVec3(-PX_MAX_F32);
for (PxU32 i = 0; i < points.count; ++i)
{
const PxVec3& p = points.at<PxVec3>(i);
if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z))
continue;
max = max.maximum(p);
min = min.minimum(p);
}
}
const PxI32 xNegFace[4] = { 0, 1, 2, 3 };
const PxI32 xPosFace[4] = { 4, 5, 6, 7 };
const PxI32 yNegFace[4] = { 0, 1, 4, 5 };
const PxI32 yPosFace[4] = { 2, 3, 6, 7 };
const PxI32 zNegFace[4] = { 0, 2, 4, 6 };
const PxI32 zPosFace[4] = { 1, 3, 5, 7 };
const PxI32 offsetsX[8] = { 0, 0, 0, 0, 1, 1, 1, 1 };
const PxI32 offsetsY[8] = { 0, 0, 1, 1, 0, 0, 1, 1 };
const PxI32 offsetsZ[8] = { 0, 1, 0, 1, 0, 1, 0, 1 };
const PxI32 tets6PerVoxel[24] = { 0,1,6,2, 0,1,4,6, 1,4,6,5, 1,2,3,6, 1,3,7,6, 1,5,6,7 };
const PxU32 tets5PerVoxel[] = {
0, 6, 3, 5, 0, 1, 5, 3, 6, 7, 3, 5, 4, 5, 6, 0, 2, 3, 0, 6,
1, 7, 4, 2, 1, 0, 2, 4, 7, 6, 4, 2, 5, 4, 1, 7, 3, 2, 7, 1 };
struct VoxelNodes
{
PxI32 c[8];
// XYZ
PxI32 c000() { return c[0]; }
PxI32 c001() { return c[1]; }
PxI32 c010() { return c[2]; }
PxI32 c011() { return c[3]; }
PxI32 c100() { return c[4]; }
PxI32 c101() { return c[5]; }
PxI32 c110() { return c[6]; }
PxI32 c111() { return c[7]; }
VoxelNodes(PxI32& nodeIndexer)
{
for (PxI32 i = 0; i < 8; ++i)
c[i] = nodeIndexer++;
}
};
static const PxI32 neighborFacesAscending[4][3] = { { 0, 1, 2 }, { 0, 1, 3 }, { 0, 2, 3 }, { 1, 2, 3 } };
struct Vox
{
PxU32 mLocationX, mLocationY, mLocationZ;
PxArray<PxI32> mTets;
PxArray<PxArray<PxI32>> mClusters;
PxArray<VoxelNodes> mNodes;
PxU32 mBaseTetIndex;
PxU32 mNumEmittedTets;
Vox(PxU32 locationX, PxU32 locationY, PxU32 locationZ) : mLocationX(locationX), mLocationY(locationY), mLocationZ(locationZ), mBaseTetIndex(0), mNumEmittedTets(0)
{ }
void operator=(const Vox &v)
{
mLocationX = v.mLocationX;
mLocationY = v.mLocationY;
mLocationZ = v.mLocationZ;
mTets = v.mTets;
mClusters = v.mClusters;
mNodes = v.mNodes;
mBaseTetIndex = v.mBaseTetIndex;
mNumEmittedTets = v.mNumEmittedTets;
}
void initNodes(PxI32& nodeIndexer)
{
for (PxU32 i = 0; i < mClusters.size(); ++i)
mNodes.pushBack(VoxelNodes(nodeIndexer));
}
void buildLocalTetAdjacency(const PxBoundedData& tetrahedra, const PxArray<PxI32>& indices, PxArray<PxI32>& result)
{
PxU32 l = 4 * indices.size();
result.clear();
result.resize(l, -1);
PxHashMap<PxU64, PxI32> faces(indices.size());
for (PxU32 i = 0; i < indices.size(); ++i)
{
Tetrahedron tet = tetrahedra.at<Tetrahedron>(indices[i]);
if (tet[0] < 0)
continue;
tet.sort();
for (PxI32 j = 0; j < 4; ++j)
{
const PxU64 tri = ((PxU64(tet[neighborFacesAscending[j][0]])) << 42) | ((PxU64(tet[neighborFacesAscending[j][1]])) << 21) | ((PxU64(tet[neighborFacesAscending[j][2]])));
if (const PxPair<const PxU64, PxI32>* ptr = faces.find(tri))
{
result[4 * i + j] = ptr->second;
result[ptr->second] = 4 * i + j;
faces.erase(tri); //Keep memory low
}
else
faces.insert(tri, 4 * i + j);
}
}
}
void computeClusters(const PxBoundedData& tetrahedra)
{
PxArray<PxI32> adj;
buildLocalTetAdjacency(tetrahedra, mTets, adj);
PxArray<bool> done;
done.resize(mTets.size(), false);
PxU32 start = 0;
PxArray<PxI32> stack;
while (true)
{
stack.clear();
while (start < done.size())
{
if (!done[start])
{
stack.pushBack(start);
done[start] = true;
PxArray<PxI32> c;
c.pushBack(mTets[start]);
mClusters.pushBack(c);
break;
}
++start;
}
if (start == done.size())
break;
while (stack.size() > 0)
{
PxI32 id = stack.popBack();
for (PxI32 i = 0; i < 4; ++i)
{
PxI32 a = adj[4 * id + i];
PxI32 tetId = a >> 2;
if (tetId >= 0 && !done[tetId])
{
stack.pushBack(tetId);
done[tetId] = true;
mClusters[mClusters.size() - 1].pushBack(mTets[tetId]);
}
}
}
}
#if PX_DEBUG
if (mClusters.size() > 1)
{
PxI32 abc = 0;
++abc;
}
#endif
for (PxU32 i = 0; i < mClusters.size(); ++i)
PxSort(mClusters[i].begin(), mClusters[i].size());
}
void embed(PxArray<PxReal>& embeddingError, PxI32 id, const PxVec3& p, const PxU32 startIndex, const PxU32 endIndex, const Tetrahedron* voxelTets, const PxArray<PxVec3>& voxelPoints, PxI32* embeddings)
{
//PxVec4 best(1000, 1000, 1000, 1000);
PxReal bestError = embeddingError[id];
PxI32 bestIndex = -1;
for (PxU32 i = startIndex; i < endIndex; ++i)
{
const Tetrahedron& candidate = voxelTets[i];
PxVec4 bary;
computeBarycentric(voxelPoints[candidate[0]], voxelPoints[candidate[1]], voxelPoints[candidate[2]], voxelPoints[candidate[3]], p, bary);
const PxReal eps = 0;
if ((bary.x >= -eps && bary.x <= 1.f + eps) && (bary.y >= -eps && bary.y <= 1.f + eps) &&
(bary.z >= -eps && bary.z <= 1.f + eps) && (bary.w >= -eps && bary.w <= 1.f + eps))
{
embeddings[id] = i;
embeddingError[id] = 0;
return;
}
else
{
PxReal error = 0;
PxReal min = PxMin(PxMin(bary.x, bary.y), PxMin(bary.z, bary.w));
if (min < 0)
error = -min;
PxReal max = PxMax(PxMax(bary.x, bary.y), PxMax(bary.z, bary.w));
if (max > 1)
{
PxReal e = max - 1;
if (e > error)
error = e;
}
if (error < bestError)
{
//best = bary;
bestError = error;
bestIndex = i;
}
}
}
if (bestIndex >= 0)
{
embeddings[id] = bestIndex;
embeddingError[id] = bestError;
}
}
bool embed(const PxU32 anchorNodeIndex, const PxBoundedData& colTets, PxI32 numTetsPerVoxel, PxArray<PxReal>& embeddingError, PxI32 id, const PxVec3& p, const Tetrahedron* voxelTets, const PxArray<PxVec3>& voxelPoints, PxI32* embeddings)
{
if (mClusters.size() > 1)
{
for (PxU32 i = 0; i < mClusters.size(); ++i)
{
const PxArray<PxI32>& c = mClusters[i];
for (PxU32 j = 0; j < c.size(); ++j)
{
const Tetrahedron& candidate = colTets.at<Tetrahedron>(c[j]);
if (candidate.contains(anchorNodeIndex))
{
embed(embeddingError, id, p, mBaseTetIndex + i * numTetsPerVoxel, mBaseTetIndex + (i + 1) * numTetsPerVoxel, voxelTets, voxelPoints, embeddings);
return true;
}
}
}
return false;
}
embed(embeddingError, id, p, mBaseTetIndex, mBaseTetIndex + numTetsPerVoxel, voxelTets, voxelPoints, embeddings);
return true;
}
void embed(const PxBoundedData& colPoints, const PxBoundedData& colTets, PxI32 numTetsPerVoxel, PxArray<PxReal>& embeddingError, PxI32 id, const PxVec3& p, const Tetrahedron* voxelTets, const PxArray<PxVec3>& voxelPoints, PxI32* embeddings)
{
PxReal bestError = embeddingError[id];
PxI32 bestIndex = 0;
if (mClusters.size() > 1)
{
for (PxU32 i = 0; i < mClusters.size(); ++i)
{
const PxArray<PxI32>& c = mClusters[i];
for (PxU32 j = 0; j < c.size(); ++j)
{
const Tetrahedron& candidate = colTets.at<Tetrahedron>(c[j]);
PxVec4 bary;
computeBarycentric(colPoints.at< PxVec3>(candidate[0]), colPoints.at<PxVec3>(candidate[1]), colPoints.at<PxVec3>(candidate[2]), colPoints.at<PxVec3>(candidate[3]), p, bary);
const PxReal eps = 0;
if ((bary.x >= -eps && bary.x <= 1.f + eps) && (bary.y >= -eps && bary.y <= 1.f + eps) &&
(bary.z >= -eps && bary.z <= 1.f + eps) && (bary.w >= -eps && bary.w <= 1.f + eps))
{
embed(embeddingError, id, p, mBaseTetIndex + i * numTetsPerVoxel, mBaseTetIndex + (i + 1) * numTetsPerVoxel, voxelTets, voxelPoints, embeddings);
return;
}
else
{
PxReal error = 0;
PxReal min = PxMin(PxMin(bary.x, bary.y), PxMin(bary.z, bary.w));
if (min < 0)
error = -min;
PxReal max = PxMax(PxMax(bary.x, bary.y), PxMax(bary.z, bary.w));
if (max > 1)
{
PxReal e = max - 1;
if (e > error)
error = e;
}
if (error < bestError)
{
//best = bary;
bestError = error;
bestIndex = i;
}
}
}
}
}
if (bestIndex >= 0)
{
embed(embeddingError, id, p, mBaseTetIndex + bestIndex * numTetsPerVoxel, mBaseTetIndex + (bestIndex + 1) * numTetsPerVoxel, voxelTets, voxelPoints, embeddings);
}
}
void emitTets(PxArray<PxU32>& voxelTets, PxArray<PxVec3>& voxelPoints, PxI32* embeddings,/* UnionFind uf,*/ const PxVec3& voxelBlockMin, const PxVec3& voxelSize,
const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxArray<PxReal>& embeddingError, const PxI32& numTetsPerVoxel)
{
for (PxU32 i = 0; i < mNodes.size(); ++i)
{
const VoxelNodes& n = mNodes[i];
for (PxI32 j = 0; j < 8; ++j)
{
PxI32 id = n.c[j];
voxelPoints[id] = PxVec3(voxelBlockMin.x + (mLocationX + offsetsX[j]) * voxelSize.x,
voxelBlockMin.y + (mLocationY + offsetsY[j]) * voxelSize.y,
voxelBlockMin.z + (mLocationZ + offsetsZ[j]) * voxelSize.z);
}
//Emit 5 or 6 tets
if (numTetsPerVoxel == 5)
{
PxI32 flip = (mLocationX + mLocationY + mLocationZ) % 2;
PxI32 offset = flip * 20;
for (PxI32 j = 0; j < 20; j += 4)
{
PxI32 a = n.c[tets5PerVoxel[j + 0 + offset]];
PxI32 b = n.c[tets5PerVoxel[j + 1 + offset]];
PxI32 c = n.c[tets5PerVoxel[j + 2 + offset]];
PxI32 d = n.c[tets5PerVoxel[j + 3 + offset]];
//Tetrahedron tet(a, b, c, d);
//voxelTets.pushBack(tet);
voxelTets.pushBack(a);
voxelTets.pushBack(b);
voxelTets.pushBack(c);
voxelTets.pushBack(d);
}
}
else
{
for (PxI32 j = 0; j < 24; j += 4)
{
PxI32 a = n.c[tets6PerVoxel[j + 0]];
PxI32 b = n.c[tets6PerVoxel[j + 1]];
PxI32 c = n.c[tets6PerVoxel[j + 2]];
PxI32 d = n.c[tets6PerVoxel[j + 3]];
//Tetrahedron tet(a, b, c, d);
//voxelTets.pushBack(tet);
voxelTets.pushBack(a);
voxelTets.pushBack(b);
voxelTets.pushBack(c);
voxelTets.pushBack(d);
}
}
if (embeddings)
{
PxVec3 min(voxelBlockMin.x + (mLocationX + 0) * voxelSize.x,
voxelBlockMin.y + (mLocationY + 0) * voxelSize.y,
voxelBlockMin.z + (mLocationZ + 0) * voxelSize.z);
PxVec3 max(voxelBlockMin.x + (mLocationX + 1) * voxelSize.x,
voxelBlockMin.y + (mLocationY + 1) * voxelSize.y,
voxelBlockMin.z + (mLocationZ + 1) * voxelSize.z);
PxBounds3 box(min, max);
box.fattenFast(1e-5f);
//Embedding
const PxArray<PxI32>& cluster = mClusters[i];
Tetrahedron* voxelTetPtr = reinterpret_cast<Tetrahedron*>(voxelTets.begin());
for (PxU32 j = 0; j < cluster.size(); ++j)
{
const Tetrahedron& tet = inputTets.at<Tetrahedron>(cluster[j]);
const PxU32 end = voxelTets.size() / 4;
const PxU32 start = end - numTetsPerVoxel;
for (PxU32 k = 0; k < 4; ++k)
if (embeddingError[tet[k]] > 0 && box.contains(inputPoints.at<PxVec3>(tet[k])))
embed(embeddingError, tet[k], inputPoints.at<PxVec3>(tet[k]), start, end, voxelTetPtr, voxelPoints, embeddings);
}
}
}
}
void mapNodes(UnionFind& uf)
{
for (PxU32 i = 0; i < mNodes.size(); ++i)
{
VoxelNodes& n = mNodes[i];
for (PxI32 j = 0; j < 8; ++j)
n.c[j] = uf.getSetNr(n.c[j]);
mNodes[i] = n;
}
}
};
struct Int3
{
PxU32 x;
PxU32 y;
PxU32 z;
};
#if PX_LINUX
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
#endif
void getVoxelRange(const PxBoundedData& points, Tetrahedron tet, const PxVec3& voxelBlockMin, const PxVec3& voxelSize,
PxU32 numVoxelsX, PxU32 numVoxelsY, PxU32 numVoxelsZ, Int3& min, Int3& max, PxBounds3& box, PxReal enlarge)
{
PxVec3 mi = points.at<PxVec3>(tet[0]);
PxVec3 ma = mi;
for (PxI32 i = 1; i < 4; ++i) {
const PxVec3& p = points.at<PxVec3>(tet[i]);
if (p.x < mi.x) mi.x = p.x; if (p.y < mi.y) mi.y = p.y; if (p.z < mi.z) mi.z = p.z;
if (p.x > ma.x) ma.x = p.x; if (p.y > ma.y) ma.y = p.y; if (p.z > ma.z) ma.z = p.z;
}
mi.x -= enlarge;
mi.y -= enlarge;
mi.z -= enlarge;
ma.x += enlarge;
ma.y += enlarge;
ma.z += enlarge;
box.minimum = mi;
box.maximum = ma;
min.x = PxU32((mi.x - voxelBlockMin.x) / voxelSize.x);
min.y = PxU32((mi.y - voxelBlockMin.y) / voxelSize.y);
min.z = PxU32((mi.z - voxelBlockMin.z) / voxelSize.z);
max.x = PxU32((ma.x - voxelBlockMin.x) / voxelSize.x);
max.y = PxU32((ma.y - voxelBlockMin.y) / voxelSize.y);
max.z = PxU32((ma.z - voxelBlockMin.z) / voxelSize.z);
min.x = PxMax(0u, min.x);
min.y = PxMax(0u, min.y);
min.z = PxMax(0u, min.z);
max.x = PxMin(numVoxelsX - 1, max.x);
max.y = PxMin(numVoxelsY - 1, max.y);
max.z = PxMin(numVoxelsZ - 1, max.z);
}
#if PX_LINUX
#pragma GCC diagnostic pop
#endif
PX_FORCE_INLINE void connect(const VoxelNodes& voxelNodesA, const PxI32* faceVoxelA, const VoxelNodes& voxelNodesB, const PxI32* faceVoxelB, UnionFind& uf)
{
for (PxI32 i = 0; i < 4; ++i)
uf.makeSet(voxelNodesA.c[faceVoxelA[i]], voxelNodesB.c[faceVoxelB[i]]);
}
PX_FORCE_INLINE bool intersectionOfSortedListsNotEmpty(const PxArray<PxI32>& sorted1, const PxArray<PxI32>& sorted2)
{
PxU32 a = 0;
PxU32 b = 0;
while (a < sorted1.size() && b < sorted2.size())
{
if (sorted1[a] == sorted2[b])
return true;
else if (sorted1[a] > sorted2[b])
++b;
else
++a;
}
return false;
}
void connect(const Vox& voxelA, const PxI32* faceVoxelA, const Vox& voxelB, const PxI32* faceVoxelB, UnionFind& uf)
{
for (PxU32 i = 0; i < voxelA.mClusters.size(); ++i)
{
const PxArray<PxI32>& clusterA = voxelA.mClusters[i];
for (PxU32 j = 0; j < voxelB.mClusters.size(); ++j)
{
const PxArray<PxI32>& clusterB = voxelB.mClusters[j];
if (intersectionOfSortedListsNotEmpty(clusterA, clusterB))
connect(voxelA.mNodes[i], faceVoxelA, voxelB.mNodes[j], faceVoxelB, uf);
}
}
}
PX_FORCE_INLINE PxU32 cell(PxU32 x, PxU32 y, PxU32 z, PxU32 numX, PxU32 numXtimesNumY)
{
return x + y * numX + z * numXtimesNumY;
}
Int3 getCell(const PxVec3& p, const PxVec3& voxelBlockMin, const PxVec3& voxelSize, const PxU32 numVoxelsX, const PxU32 numVoxelsY, const PxU32 numVoxelsZ)
{
Int3 cell;
PxVec3 c = p - voxelBlockMin;
cell.x = PxU32(c.x / voxelSize.x);
cell.y = PxU32(c.y / voxelSize.y);
cell.z = PxU32(c.z / voxelSize.z);
if (cell.x >= numVoxelsX) cell.x = numVoxelsX - 1;
if (cell.y >= numVoxelsY) cell.y = numVoxelsY - 1;
if (cell.z >= numVoxelsZ) cell.z = numVoxelsZ - 1;
return cell;
}
PX_FORCE_INLINE PxReal aabbDistanceSquaredToPoint(const PxVec3& min, const PxVec3& max, const PxVec3& p)
{
PxReal sqDist = 0.0f;
if (p.x < min.x) sqDist += (min.x - p.x) * (min.x - p.x);
if (p.x > max.x) sqDist += (p.x - max.x) * (p.x - max.x);
if (p.y < min.y) sqDist += (min.y - p.y) * (min.y - p.y);
if (p.y > max.y) sqDist += (p.y - max.y) * (p.y - max.y);
if (p.z < min.z) sqDist += (min.z - p.z) * (min.z - p.z);
if (p.z > max.z) sqDist += (p.z - max.z) * (p.z - max.z);
return sqDist;
}
PxI32 getVoxelId(PxArray<PxI32> voxelIds, const PxVec3& p, const PxVec3& voxelBlockMin, const PxVec3& voxelSize, const PxU32 numVoxelsX, const PxU32 numVoxelsY, const PxU32 numVoxelsZ)
{
PxVec3 pt = p - voxelBlockMin;
PxU32 ix = PxU32(PxMax(0.0f, pt.x / voxelSize.x));
PxU32 iy = PxU32(PxMax(0.0f, pt.y / voxelSize.y));
PxU32 iz = PxU32(PxMax(0.0f, pt.z / voxelSize.z));
if (ix >= numVoxelsX) ix = numVoxelsX - 1;
if (iy >= numVoxelsY) iy = numVoxelsY - 1;
if (iz >= numVoxelsZ) iz = numVoxelsZ - 1;
PxU32 id = cell(ix, iy, iz, numVoxelsX, numVoxelsX * numVoxelsY);
if (voxelIds[id] >= 0)
return voxelIds[id];
const PxI32 numOffsets = 6;
const PxI32 offsets[numOffsets][3] = { {-1, 0, 0}, {+1, 0, 0}, {0, -1, 0}, {0, +1, 0}, {0, 0, -1}, {0, 0, +1} };
PxReal minDist = FLT_MAX;
for (PxU32 i = 0; i < numOffsets; ++i)
{
const PxI32* o = offsets[i];
PxI32 newX = ix + o[0];
PxI32 newY = iy + o[1];
PxI32 newZ = iz + o[2];
if (newX >= 0 && newX < PxI32(numVoxelsX) && newY >= 0 && newY < PxI32(numVoxelsY) && newZ >= 0 && newZ < PxI32(numVoxelsZ))
{
PxU32 candidate = cell(newX, newY, newZ, numVoxelsX, numVoxelsX * numVoxelsY);
if (voxelIds[candidate] >= 0)
{
PxVec3 min(voxelBlockMin.x + newX * voxelSize.x, voxelBlockMin.y + newY * voxelSize.y, voxelBlockMin.z + newZ * voxelSize.z);
PxVec3 max = min + voxelSize;
PxReal d = aabbDistanceSquaredToPoint(min, max, p);
if (d < minDist)
{
id = candidate;
minDist = d;
}
}
}
}
PxI32 result = voxelIds[id];
if (result < 0)
{
//Search the closest voxel over all voxels
minDist = FLT_MAX;
for (PxU32 newX = 0; newX < numVoxelsX; ++newX)
for (PxU32 newY = 0; newY < numVoxelsY; ++newY)
for (PxU32 newZ = 0; newZ < numVoxelsZ; ++newZ)
{
PxU32 candidate = cell(newX, newY, newZ, numVoxelsX, numVoxelsX * numVoxelsY);
if (voxelIds[candidate] >= 0)
{
PxVec3 min(voxelBlockMin.x + newX * voxelSize.x, voxelBlockMin.y + newY * voxelSize.y, voxelBlockMin.z + newZ * voxelSize.z);
PxVec3 max = min + voxelSize;
PxReal d = aabbDistanceSquaredToPoint(min, max, p);
if (d < minDist)
{
id = candidate;
minDist = d;
}
}
}
}
result = voxelIds[id];
if (result < 0)
return 0;
return result;
}
void generateVoxelTetmesh(const PxBoundedData& inputPointsOrig, const PxBoundedData& inputTets, PxU32 numVoxelsX, PxU32 numVoxelsY, PxU32 numVoxelsZ,
PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel)
{
if (inputTets.count == 0)
return; //No input, so there is no basis for creating an output
PxU32 xy = numVoxelsX * numVoxelsY;
PxVec3 origMin, origMax;
minMax(inputPointsOrig, origMin, origMax);
PxVec3 size = origMax - origMin;
PxReal scaling = 1.0f / PxMax(size.x, PxMax(size.y, size.z));
PxArray<PxVec3> scaledPoints;
scaledPoints.resize(inputPointsOrig.count);
for (PxU32 i = 0; i < inputPointsOrig.count; ++i)
{
PxVec3 p = inputPointsOrig.at<PxVec3>(i);
scaledPoints[i] = (p - origMin) * scaling;
}
PxBoundedData inputPoints;
inputPoints.count = inputPointsOrig.count;
inputPoints.stride = sizeof(PxVec3);
inputPoints.data = scaledPoints.begin();
PxVec3 voxelBlockMin, voxelBlockMax;
minMax(inputPoints, voxelBlockMin, voxelBlockMax);
PxVec3 voxelBlockSize = voxelBlockMax - voxelBlockMin;
PxVec3 voxelSize(voxelBlockSize.x / numVoxelsX, voxelBlockSize.y / numVoxelsY, voxelBlockSize.z / numVoxelsZ);
PxArray<PxI32> voxelIds;
voxelIds.resize(numVoxelsX * numVoxelsY * numVoxelsZ, -1);
PxArray<Vox> voxels;
for(PxU32 i=0;i< inputTets.count;++i)
{
Int3 min, max;
const Tetrahedron& tet = inputTets.at<Tetrahedron>(i);
PxBounds3 tetBox;
getVoxelRange(inputPoints, tet, voxelBlockMin, voxelSize, numVoxelsX, numVoxelsY, numVoxelsZ, min, max, tetBox, 1.e-4f);
//bool success = false;
for (PxU32 x = min.x; x <= max.x; ++x)
{
for (PxU32 y = min.y; y <= max.y; ++y)
{
for (PxU32 z = min.z; z <= max.z; ++z)
{
PxBounds3 box(PxVec3(voxelBlockMin.x + x * voxelSize.x, voxelBlockMin.y + y * voxelSize.y, voxelBlockMin.z + z * voxelSize.z),
PxVec3(voxelBlockMin.x + (x + 1) * voxelSize.x, voxelBlockMin.y + (y + 1) * voxelSize.y, voxelBlockMin.z + (z + 1) * voxelSize.z));
if (intersectTetrahedronBox(inputPoints.at<PxVec3>(tet[0]), inputPoints.at<PxVec3>(tet[1]), inputPoints.at<PxVec3>(tet[2]), inputPoints.at<PxVec3>(tet[3]), box))
{
//success = true;
PxI32 voxelId = voxelIds[cell(x, y, z, numVoxelsX, xy)];
if (voxelId < 0)
{
voxelId = voxels.size();
voxelIds[cell(x, y, z, numVoxelsX, xy)] = voxelId;
voxels.pushBack(Vox(x, y, z));
}
Vox& v = voxels[voxelId];
v.mTets.pushBack(i);
}
}
}
}
/*if (!success)
{
PxI32 abc = 0;
++abc;
}*/
}
PxI32 nodeIndexer = 0;
for(PxU32 i=0;i<voxels.size();++i)
{
voxels[i].computeClusters(inputTets);
}
for (PxU32 i = 0; i < voxels.size(); ++i)
{
voxels[i].initNodes(nodeIndexer);
}
UnionFind uf(nodeIndexer);
for (PxU32 i = 0; i < voxels.size(); ++i)
{
Vox& v = voxels[i];
if (v.mLocationX > 0 && voxelIds[cell(v.mLocationX - 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)] >= 0)
connect(voxels[voxelIds[cell(v.mLocationX - 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)]], xPosFace, v, xNegFace, uf);
if (v.mLocationX < numVoxelsX - 1 && voxelIds[cell(v.mLocationX + 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)] >= 0)
connect(v, xPosFace, voxels[voxelIds[cell(v.mLocationX + 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)]], xNegFace, uf);
if (v.mLocationY > 0 && voxelIds[cell(v.mLocationX, v.mLocationY - 1, v.mLocationZ, numVoxelsX, xy)] >= 0)
connect(voxels[voxelIds[cell(v.mLocationX, v.mLocationY - 1, v.mLocationZ, numVoxelsX, xy)]], yPosFace, v, yNegFace, uf);
if (v.mLocationY < numVoxelsY - 1 && voxelIds[cell(v.mLocationX, v.mLocationY + 1, v.mLocationZ, numVoxelsX, xy)] >= 0)
connect(v, yPosFace, voxels[voxelIds[cell(v.mLocationX, v.mLocationY + 1, v.mLocationZ, numVoxelsX, xy)]], yNegFace, uf);
if (v.mLocationZ > 0 && voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ - 1, numVoxelsX, xy)] >= 0)
connect(voxels[voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ - 1, numVoxelsX, xy)]], zPosFace, v, zNegFace, uf);
if (v.mLocationZ < numVoxelsZ - 1 && voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ + 1, numVoxelsX, xy)] >= 0)
connect(v, zPosFace, voxels[voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ + 1, numVoxelsX, xy)]], zNegFace, uf);
}
PxI32 numVertices = uf.computeSetNrs();
for (PxU32 i = 0; i < voxels.size(); ++i)
{
voxels[i].mapNodes(uf);
}
//const PxU32 numTetsPerVoxel = 5;
voxelPoints.resize(numVertices);
//intputPointToOutputTetIndex.resize(numInputPoints);
voxelTets.clear();
PxArray<PxReal> embeddingError;
embeddingError.resize(inputPoints.count, 1000);
for (PxU32 i = 0; i < voxels.size(); ++i)
{
Vox& v = voxels[i];
v.mBaseTetIndex = voxelTets.size() / 4;
v.emitTets(voxelTets, voxelPoints, intputPointToOutputTetIndex, voxelBlockMin, voxelSize, inputPoints, inputTets, embeddingError, numTetsPerVoxel);
v.mNumEmittedTets = voxelTets.size() / 4 - v.mBaseTetIndex;
}
#if PX_DEBUG
PxArray<bool> pointUsed;
pointUsed.resize(inputPoints.count, false);
for (PxU32 i = 0; i < inputTets.count; ++i)
{
const Tetrahedron& tet = inputTets.at<Tetrahedron>(i);
for (PxU32 j = 0; j < 4; ++j)
pointUsed[tet[j]] = true;
}
#endif
Tetrahedron* voxelTetPtr = reinterpret_cast<Tetrahedron*>(voxelTets.begin());
for (PxU32 i = 0; i < embeddingError.size(); ++i)
{
if (embeddingError[i] == 1000)
{
const PxVec3& p = inputPoints.at<PxVec3>(i);
PxI32 voxelId = getVoxelId(voxelIds, p, voxelBlockMin, voxelSize, numVoxelsX, numVoxelsY, numVoxelsZ);
PX_ASSERT(voxelId >= 0);
Vox& vox = voxels[voxelId];
if (anchorNodeIndices && anchorNodeIndices[i] < inputPoints.count)
{
if (!vox.embed(anchorNodeIndices[i], inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex))
{
PxVec3 pt = inputPoints.at<PxVec3>(anchorNodeIndices[i]);
voxelId = getVoxelId(voxelIds, pt, voxelBlockMin, voxelSize, numVoxelsX, numVoxelsY, numVoxelsZ);
PX_ASSERT(voxelId >= 0);
Vox& v = voxels[voxelId];
if (!v.embed(anchorNodeIndices[i], inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex))
v.embed(inputPoints, inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex);
}
}
else
vox.embed(inputPoints, inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex);
}
}
//Scale back to original size
scaling = 1.0f / scaling;
for(PxU32 i=0;i<voxelPoints.size();++i)
voxelPoints[i] = voxelPoints[i] * scaling + origMin;
}
void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxReal voxelEdgeLength,
PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel)
{
PxVec3 min, max;
minMax(inputPoints, min, max);
PxVec3 blockSize = max - min;
PxU32 numCellsX = PxMax(1u, PxU32(blockSize.x / voxelEdgeLength + 0.5f));
PxU32 numCellsY = PxMax(1u, PxU32(blockSize.y / voxelEdgeLength + 0.5f));
PxU32 numCellsZ = PxMax(1u, PxU32(blockSize.z / voxelEdgeLength + 0.5f));
generateVoxelTetmesh(inputPoints, inputTets, numCellsX, numCellsY, numCellsZ, voxelPoints, voxelTets, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel);
}
void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxU32 numVoxelsAlongLongestBoundingBoxAxis,
PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel)
{
PxVec3 min, max;
minMax(inputPoints, min, max);
PxVec3 size = max - min;
PxReal voxelEdgeLength = PxMax(size.x, PxMax(size.y, size.z)) / numVoxelsAlongLongestBoundingBoxAxis;
generateVoxelTetmesh(inputPoints, inputTets, voxelEdgeLength, voxelPoints, voxelTets, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel);
}
static PxReal computeMeshVolume(const PxArray<PxVec3>& points, const PxArray<Triangle>& triangles)
{
PxVec3 center(0, 0, 0);
for (PxU32 i = 0; i < points.size(); ++i)
{
center += points[i];
}
center /= PxReal(points.size());
PxReal volume = 0;
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
volume += tetVolume(points[tri[0]], points[tri[1]], points[tri[2]], center);
}
return PxAbs(volume);
}
static PxTriangleMeshAnalysisResults validateConnectivity(const PxArray<Triangle>& triangles)
{
PxArray<bool> flip;
PxHashMap<PxU64, PxI32> edges;
PxArray<PxArray<PxU32>> connectedTriangleGroups;
if (!MeshAnalyzer::buildConsistentTriangleOrientationMap(triangles.begin(), triangles.size(), flip, edges, connectedTriangleGroups))
return PxTriangleMeshAnalysisResult::Enum::eEDGE_SHARED_BY_MORE_THAN_TWO_TRIANGLES;
PxTriangleMeshAnalysisResults result = PxTriangleMeshAnalysisResult::eVALID;
for (PxHashMap<PxU64, PxI32>::Iterator iter = edges.getIterator(); !iter.done(); ++iter)
if (iter->second >= 0)
{
result = result | PxTriangleMeshAnalysisResult::eOPEN_BOUNDARIES;
break;
}
for (PxU32 i = 0; i < flip.size(); ++i)
{
if (flip[i])
{
return result | PxTriangleMeshAnalysisResult::Enum::eINCONSISTENT_TRIANGLE_ORIENTATION;
}
}
return result;
}
static bool trianglesIntersect(const Triangle& tri1, const Triangle& tri2, const PxArray<PxVec3>& points)
{
int counter = 0;
if (tri1.contains(tri2[0])) ++counter;
if (tri1.contains(tri2[1])) ++counter;
if (tri1.contains(tri2[2])) ++counter;
if (counter > 0)
return false; //Triangles share at leat one point
return Gu::trianglesIntersect(points[tri1[0]], points[tri1[1]], points[tri1[2]], points[tri2[0]], points[tri2[1]], points[tri2[2]]);
}
static PxBounds3 triBounds(const PxArray<PxVec3>& points, const Triangle& tri, PxReal enlargement)
{
PxBounds3 box = PxBounds3::empty();
box.include(points[tri[0]]);
box.include(points[tri[1]]);
box.include(points[tri[2]]);
box.fattenFast(enlargement);
return box;
}
static bool meshContainsSelfIntersections(const PxArray<PxVec3>& points, const PxArray<Triangle>& triangles)
{
PxReal enlargement = 1e-6f;
AABBTreeBounds boxes;
boxes.init(triangles.size());
for (PxU32 i = 0; i < triangles.size(); ++i)
{
boxes.getBounds()[i] = triBounds(points, triangles[i], enlargement);
}
PxArray<Gu::BVHNode> tree;
Gu::buildAABBTree(triangles.size(), boxes, tree);
PxArray<PxI32> candidateTriangleIndices;
IntersectionCollectingTraversalController tc(candidateTriangleIndices);
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
PxBounds3 box = triBounds(points, tri, enlargement);
tc.reset(box);
traverseBVH(tree, tc);
for (PxU32 j = 0; j < candidateTriangleIndices.size(); ++j)
{
Triangle tri2 = triangles[j];
if (trianglesIntersect(tri, tri2, points))
return true;
}
}
return false;
}
static PxReal maxDotProduct(const PxVec3& a, const PxVec3& b, const PxVec3& c)
{
const PxVec3 ab = b - a;
const PxVec3 ac = c - a;
const PxVec3 bc = c - b;
PxReal maxDot = ab.dot(ac) / PxSqrt(ab.magnitudeSquared() * ac.magnitudeSquared());
PxReal dot = ac.dot(bc) / PxSqrt(ac.magnitudeSquared() * bc.magnitudeSquared());
if (dot > maxDot) maxDot = dot;
dot = -ab.dot(bc) / PxSqrt(ab.magnitudeSquared() * bc.magnitudeSquared());
if (dot > maxDot) maxDot = dot;
return maxDot;
}
static PxReal minimumAngle(const PxArray<PxVec3>& points, const PxArray<Triangle>& triangles)
{
PxReal maxDot = -1;
for (PxU32 i = 0; i < triangles.size(); ++i)
{
const Triangle& tri = triangles[i];
PxReal dot = maxDotProduct(points[tri[0]], points[tri[1]], points[tri[2]]);
if (dot > maxDot)
maxDot = dot;
}
if (maxDot > 1)
maxDot = 1;
return PxAcos(maxDot); //Converts to the minimal angle
}
PxTetrahedronMeshAnalysisResults validateTetrahedronMesh(const PxBoundedData& points, const PxBoundedData& tetrahedra, const bool has16BitIndices, const PxReal minTetVolumeThreshold)
{
PxTetrahedronMeshAnalysisResults result = PxTetrahedronMeshAnalysisResult::eVALID;
PxArray<Tetrahedron> tets;
tets.reserve(tetrahedra.count);
for (PxU32 i = 0; i < tetrahedra.count; ++i)
{
Tetrahedron t;
if (has16BitIndices)
{
Tetrahedron16 t16 = tetrahedra.at<Tetrahedron16>(i);
t = Tetrahedron(t16[0], t16[1], t16[2], t16[3]);
}
else
t = tetrahedra.at<Tetrahedron>(i);
tets.pushBack(t);
}
for (PxU32 i = 0; i < tetrahedra.count; ++i)
{
const Tetrahedron& tetInd = tets[i];
const PxReal volume = computeTetrahedronVolume(points.at<PxVec3>(tetInd.v[0]), points.at<PxVec3>(tetInd.v[1]), points.at<PxVec3>(tetInd.v[2]), points.at<PxVec3>(tetInd.v[3]));
if (volume <= minTetVolumeThreshold)
{
result |= PxTetrahedronMeshAnalysisResult::eDEGENERATE_TETRAHEDRON;
break;
}
}
if (result & PxTetrahedronMeshAnalysisResult::eDEGENERATE_TETRAHEDRON) result |= PxTetrahedronMeshAnalysisResult::eMESH_IS_INVALID;
return result;
}
PxTriangleMeshAnalysisResults validateTriangleMesh(const PxBoundedData& points, const PxBoundedData& triangles, const bool has16BitIndices, const PxReal minVolumeThreshold, const PxReal minTriangleAngleRadians)
{
PxVec3 min, max;
minMax(points, min, max);
PxVec3 size = max - min;
PxReal scaling = 1.0f / PxMax(PxMax(size.x, size.y), PxMax(1e-6f, size.z));
PxArray<PxVec3> normalizedPoints;
normalizedPoints.reserve(points.count);
PxTriangleMeshAnalysisResults result = PxTriangleMeshAnalysisResult::eVALID;
if (has16BitIndices && points.count > PX_MAX_U16)
result |= PxTriangleMeshAnalysisResult::eREQUIRES_32BIT_INDEX_BUFFER;
for (PxU32 i = 0; i < points.count; ++i)
{
const PxVec3& p = points.at<PxVec3>(i);
if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z))
{
result |= PxTriangleMeshAnalysisResult::eCONTAINS_INVALID_POINTS;
normalizedPoints.pushBack(p);
continue;
}
normalizedPoints.pushBack((p - min) * scaling);
}
PxArray<PxI32> map;
MeshAnalyzer::mapDuplicatePoints<PxVec3, PxF32>(normalizedPoints.begin(), normalizedPoints.size(), map);
PxArray<Triangle> mappedTriangles;
mappedTriangles.reserve(triangles.count);
for (PxU32 i = 0; i < triangles.count; ++i)
{
Triangle t;
if (has16BitIndices)
{
Triangle16 t16 = triangles.at<Triangle16>(i);
t = Triangle(t16[0], t16[1], t16[2]);
}
else
t = triangles.at<Triangle>(i);
for (PxU32 j = 0; j < 3; ++j)
{
PxI32 id = t[j];
if (id < 0 || id >= PxI32(points.count))
{
return PxTriangleMeshAnalysisResult::eTRIANGLE_INDEX_OUT_OF_RANGE | PxTriangleMeshAnalysisResult::eMESH_IS_INVALID;
}
}
mappedTriangles.pushBack(t);
}
for (PxU32 i = 0; i < map.size(); ++i)
if (map[i] != PxI32(i))
{
result = result | PxTriangleMeshAnalysisResult::eCONTAINS_DUPLICATE_POINTS;
break;
}
if(minimumAngle(normalizedPoints, mappedTriangles) < minTriangleAngleRadians)
result = result | PxTriangleMeshAnalysisResult::eCONTAINS_ACUTE_ANGLED_TRIANGLES;
PxReal volume = computeMeshVolume(normalizedPoints, mappedTriangles);
if (volume < minVolumeThreshold)
result = result | PxTriangleMeshAnalysisResult::eZERO_VOLUME;
result = result | validateConnectivity(mappedTriangles);
if(meshContainsSelfIntersections(normalizedPoints, mappedTriangles))
result = result | PxTriangleMeshAnalysisResult::eSELF_INTERSECTIONS;
if (result & PxTriangleMeshAnalysisResult::eZERO_VOLUME) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID;
if (result & PxTriangleMeshAnalysisResult::eOPEN_BOUNDARIES) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC;
if (result & PxTriangleMeshAnalysisResult::eSELF_INTERSECTIONS) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC;
if (result & PxTriangleMeshAnalysisResult::eINCONSISTENT_TRIANGLE_ORIENTATION) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID;
if (result & PxTriangleMeshAnalysisResult::eCONTAINS_ACUTE_ANGLED_TRIANGLES) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC;
if (result & PxTriangleMeshAnalysisResult::eEDGE_SHARED_BY_MORE_THAN_TWO_TRIANGLES) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC;
if (result & PxTriangleMeshAnalysisResult::eCONTAINS_INVALID_POINTS) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID;
if (result & PxTriangleMeshAnalysisResult::eREQUIRES_32BIT_INDEX_BUFFER) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID;
return result;
}
//Consistent triangle orientation
}
}
| 74,608 | C++ | 30.533812 | 242 | 0.642491 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtRandomAccessHeap.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_RANDOM_ACCESS_HEAP_H
#define EXT_RANDOM_ACCESS_HEAP_H
#include "foundation/PxArray.h"
// MM: heap which allows the modification of the priorities of entries stored anywhere in the tree
// for this, every entry gets an id via which it can be accessed
// used in ExtMeshSimplificator to sort edges w.r.t. their error metric
// ------------------------------------------------------------------------------
namespace physx
{
namespace Ext
{
template <class T> class RandomAccessHeap
{
public:
RandomAccessHeap() {
heap.resize(1); // dummy such that root is at 1 for faster parent child computation
ids.resize(1);
nextId = 0;
}
void resizeFast(PxArray<PxI32>& arr, PxU32 newSize, PxI32 value = 0)
{
if (newSize < arr.size())
arr.removeRange(newSize, arr.size() - newSize);
else
{
while (arr.size() < newSize)
arr.pushBack(value);
}
}
PxI32 insert(T elem, PxI32 id = -1) // id for ability to alter the entry later or to identify duplicates
{
if (id < 0) {
id = nextId;
nextId++;
}
else if (id >= nextId)
nextId = id + 1;
if (id >= 0 && id < PxI32(posOfId.size()) && posOfId[id] >= 0)
return id; // already in heap
heap.pushBack(elem);
ids.pushBack(id);
if (id >= PxI32(posOfId.size()))
resizeFast(posOfId, id + 1, -1);
posOfId[id] = heap.size() - 1;
percolate(PxI32(heap.size()) - 1);
return id;
}
bool remove(PxI32 id)
{
PxI32 i = posOfId[id];
if (i < 0)
return false;
posOfId[id] = -1;
T prev = heap[i];
heap[i] = heap.back();
heap.popBack();
ids[i] = ids.back();
ids.popBack();
if (i < PxI32(heap.size()))
{
posOfId[ids[i]] = i;
if (heap.size() > 1)
{
if (heap[i] < prev)
percolate(i);
else
siftDown(i);
}
}
return true;
}
T deleteMin()
{
T min(-1, -1, 0.0f);
if (heap.size() > 1)
{
min = heap[1];
posOfId[ids[1]] = -1;
heap[1] = heap.back();
heap.popBack();
ids[1] = ids.back();
ids.popBack();
posOfId[ids[1]] = 1;
siftDown(1);
}
return min;
}
void makeHeap(const PxArray<T> &elems) // O(n) instead of inserting one after the other O(n log n)
{
heap.resize(elems.size() + 1);
ids.resize(elems.size() + 1);
posOfId.resize(elems.size());
for (PxU32 i = 0; i < elems.size(); i++)
{
heap[i + 1] = elems[i];
ids[i + 1] = i;
posOfId[ids[i + 1]] = i + 1;
}
PxI32 n = (heap.size() - 1) >> 1;
for (PxI32 i = n; i >= 1; i--)
siftDown(i);
}
void clear()
{
heap.capacity() == 0 ? heap.resize(1) : heap.forceSize_Unsafe(1);
ids.capacity() == 0 ? ids.resize(1) : ids.forceSize_Unsafe(1);
posOfId.forceSize_Unsafe(0);
nextId = 0;
}
PX_FORCE_INLINE PxI32 size() { return heap.size() - 1; }
PX_FORCE_INLINE bool empty() { return heap.size() <= 1; }
private:
void siftDown(PxI32 i)
{
PxI32 n = PxI32(heap.size()) - 1;
PxI32 k = i;
PxI32 j;
do
{
j = k;
if (2 * j < n && heap[2 * j] < heap[k])
k = 2 * j;
if (2 * j < n && heap[2 * j + 1] < heap[k])
k = 2 * j + 1;
T temp = heap[j]; heap[j] = heap[k]; heap[k] = temp;
PxI32 id = ids[j]; ids[j] = ids[k]; ids[k] = id;
posOfId[ids[j]] = j;
posOfId[ids[k]] = k;
}
while (j != k);
}
void percolate(PxI32 i)
{
PxI32 k = i;
PxI32 j;
do
{
j = k;
if (j > 1 && !(heap[j >> 1] < heap[k]))
k = j >> 1;
T temp = heap[j]; heap[j] = heap[k]; heap[k] = temp;
PxI32 id = ids[j]; ids[j] = ids[k]; ids[k] = id;
posOfId[ids[j]] = j;
posOfId[ids[k]] = k;
}
while (j != k);
}
PxArray<T> heap;
PxArray<PxI32> ids;
PxArray<PxI32> posOfId;
PxI32 nextId;
};
}
}
#endif
| 5,482 | C | 24.03653 | 108 | 0.582087 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtFastWindingNumber.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_FAST_WINDING_NUMBER_H
#define EXT_FAST_WINDING_NUMBER_H
#include "ExtVec3.h"
#include "GuWindingNumberT.h"
namespace physx
{
namespace Ext
{
using Triangle = Gu::IndexedTriangleT<PxI32>;
using Triangle16 = Gu::IndexedTriangleT<PxI16>;
typedef Gu::ClusterApproximationT<PxF64, PxVec3d> ClusterApproximationF64;
typedef Gu::SecondOrderClusterApproximationT<PxF64, PxVec3d> SecondOrderClusterApproximationF64;
PxF64 computeWindingNumber(const PxArray<Gu::BVHNode>& tree, const PxVec3d& q, PxF64 beta, const PxHashMap<PxU32, ClusterApproximationF64>& clusters,
const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points);
void precomputeClusterInformation(PxArray<Gu::BVHNode>& tree, const PxArray<Triangle>& triangles,
const PxArray<PxVec3d>& points, PxHashMap<PxU32, ClusterApproximationF64>& result, PxI32 rootNodeIndex = 0);
}
}
#endif
| 2,439 | C | 44.185184 | 150 | 0.777368 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtUtilities.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_TET_CPU_BVH_H
#define EXT_TET_CPU_BVH_H
#include "foundation/PxArray.h"
#include "foundation/PxBounds3.h"
#include "GuBVH.h"
#include "GuAABBTree.h"
#include "GuAABBTreeNode.h"
#include "GuAABBTreeBounds.h"
#include "GuAABBTreeQuery.h"
#include "GuTriangle.h"
#include "ExtVec3.h"
namespace physx
{
namespace Ext
{
using Triangle = Gu::IndexedTriangleT<PxI32>;
//Creates an unique 64bit bit key out of two 32bit values, the key is order independent, useful as hash key for edges
//Use this functions to compute the edge keys used in the edgesToSplit parameter of the split function below.
PX_FORCE_INLINE PxU64 key(PxI32 a, PxI32 b)
{
if (a < b)
return ((PxU64(a)) << 32) | (PxU64(b));
else
return ((PxU64(b)) << 32) | (PxU64(a));
}
void buildTree(const PxU32* triangles, const PxU32 numTriangles, const PxVec3d* points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f);
//Builds a BVH from a set of triangles
PX_FORCE_INLINE void buildTree(const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f)
{
buildTree(reinterpret_cast<const PxU32*>(triangles.begin()), triangles.size(), points.begin(), tree, enlargement);
}
template<typename T>
void traverseBVH(const PxArray<Gu::BVHNode>& nodes, T& traversalController, PxI32 rootNodeIndex = 0)
{
traverseBVH(nodes.begin(), traversalController, rootNodeIndex);
}
class IntersectionCollectingTraversalController
{
PxBounds3 box;
PxArray<PxI32>& candidateTriangleIndices;
public:
IntersectionCollectingTraversalController(PxArray<PxI32>& candidateTriangleIndices_) :
box(PxBounds3::empty()), candidateTriangleIndices(candidateTriangleIndices_)
{ }
IntersectionCollectingTraversalController(const PxBounds3& box_, PxArray<PxI32>& candidateTriangleIndices_) :
box(box_), candidateTriangleIndices(candidateTriangleIndices_)
{ }
void reset(const PxBounds3& box_)
{
box = box_;
candidateTriangleIndices.clear();
}
Gu::TraversalControl::Enum analyze(const Gu::BVHNode& node, PxI32)
{
if (node.isLeaf())
{
candidateTriangleIndices.pushBack(node.getPrimitiveIndex());
return Gu::TraversalControl::eDontGoDeeper;
}
if (node.mBV.intersects(box))
return Gu::TraversalControl::eGoDeeper;
return Gu::TraversalControl::eDontGoDeeper;
}
private:
PX_NOCOPY(IntersectionCollectingTraversalController)
};
}
}
#endif
| 4,002 | C | 35.390909 | 154 | 0.750875 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtBVH.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_BVH_H
#define EXT_BVH_H
#include "foundation/PxBounds3.h"
#include "foundation/PxArray.h"
#include "GuAABBTreeNode.h"
namespace physx
{
namespace Ext
{
struct BVHDesc
{
PxArray<Gu::BVHNode> tree;
void query(const PxBounds3& bounds, PxArray<PxI32>& items);
};
class BVHBuilder
{
public:
static void build(BVHDesc& bvh, const PxBounds3* items, PxI32 numItems);
};
}
}
#endif
| 1,979 | C | 35.666666 | 75 | 0.752906 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtRemesher.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 "ExtRemesher.h"
#include "ExtBVH.h"
#include "ExtMarchingCubesTable.h"
#include "foundation/PxSort.h"
#include "GuIntersectionTriangleBox.h"
#include "GuBox.h"
namespace physx
{
namespace Ext
{
// -------------------------------------------------------------------------------------
void Remesher::clear()
{
cells.clear();
vertices.clear();
normals.clear();
triIds.clear();
triNeighbors.clear();
}
#define HASH_SIZE 170111
// -------------------------------------------------------------------------------------
PX_FORCE_INLINE static PxU32 hash(PxI32 xi, PxI32 yi, PxI32 zi)
{
PxU32 h = (xi * 92837111) ^ (yi * 689287499) ^ (zi * 283923481);
return h % HASH_SIZE;
}
// -------------------------------------------------------------------------------------
void Remesher::addCell(PxI32 xi, PxI32 yi, PxI32 zi)
{
Cell c;
c.init(xi, yi, zi);
PxU32 h = hash(xi, yi, zi);
c.next = firstCell[h];
firstCell[h] = PxI32(cells.size());
cells.pushBack(c);
}
// -------------------------------------------------------------------------------------
PxI32 Remesher::getCellNr(PxI32 xi, PxI32 yi, PxI32 zi) const
{
PxU32 h = hash(xi, yi, zi);
PxI32 nr = firstCell[h];
while (nr >= 0)
{
const Cell& c = cells[nr];
if (c.xi == xi && c.yi == yi && c.zi == zi)
return nr;
nr = c.next;
}
return -1;
}
// -------------------------------------------------------------------------------------
PX_FORCE_INLINE bool Remesher::cellExists(PxI32 xi, PxI32 yi, PxI32 zi) const
{
return getCellNr(xi, yi, zi) >= 0;
}
// -------------------------------------------------------------------------------------
void Remesher::remesh(const PxArray<PxVec3>& inputVerts, const PxArray<PxU32>& inputTriIds,
PxU32 resolution, PxArray<PxU32> *vertexMap)
{
remesh(inputVerts.begin(), inputVerts.size(), inputTriIds.begin(), inputTriIds.size(), resolution, vertexMap);
}
void Remesher::remesh(const PxVec3* inputVerts, PxU32 nbVertices, const PxU32* inputTriIds, PxU32 nbTriangleIndices, PxU32 resolution, PxArray<PxU32> *vertexMap)
{
clear();
PxBounds3 meshBounds;
meshBounds.setEmpty();
for (PxU32 i = 0; i < nbVertices; i++)
meshBounds.include(inputVerts[i]);
PxVec3 dims = meshBounds.getDimensions();
float spacing = PxMax(dims.x, PxMax(dims.y, dims.z)) / resolution;
meshBounds.fattenFast(3.0f * spacing);
PxU32 numTris = nbTriangleIndices / 3;
PxBounds3 triBounds, cellBounds;
Gu::BoxPadded box;
box.rot = PxMat33(PxIdentity);
firstCell.clear();
firstCell.resize(HASH_SIZE, -1);
// create sparse overlapping cells
for (PxU32 i = 0; i < numTris; i++)
{
const PxVec3& p0 = inputVerts[inputTriIds[3 * i]];
const PxVec3& p1 = inputVerts[inputTriIds[3 * i + 1]];
const PxVec3& p2 = inputVerts[inputTriIds[3 * i + 2]];
triBounds.setEmpty();
triBounds.include(p0);
triBounds.include(p1);
triBounds.include(p2);
PxI32 x0 = PxI32(PxFloor((triBounds.minimum.x - meshBounds.minimum.x) / spacing));
PxI32 y0 = PxI32(PxFloor((triBounds.minimum.y - meshBounds.minimum.y) / spacing));
PxI32 z0 = PxI32(PxFloor((triBounds.minimum.z - meshBounds.minimum.z) / spacing));
PxI32 x1 = PxI32(PxFloor((triBounds.maximum.x - meshBounds.minimum.x) / spacing)) + 1;
PxI32 y1 = PxI32(PxFloor((triBounds.maximum.y - meshBounds.minimum.y) / spacing)) + 1;
PxI32 z1 = PxI32(PxFloor((triBounds.maximum.z - meshBounds.minimum.z) / spacing)) + 1;
for (PxI32 xi = x0; xi <= x1; xi++)
{
for (PxI32 yi = y0; yi <= y1; yi++)
{
for (PxI32 zi = z0; zi <= z1; zi++)
{
cellBounds.minimum.x = meshBounds.minimum.x + xi * spacing;
cellBounds.minimum.y = meshBounds.minimum.y + yi * spacing;
cellBounds.minimum.z = meshBounds.minimum.z + zi * spacing;
cellBounds.maximum = cellBounds.minimum + PxVec3(spacing, spacing, spacing);
cellBounds.fattenFast(1e-5f);
box.center = cellBounds.getCenter();
box.extents = cellBounds.getExtents();
if (!Gu::intersectTriangleBox(box, p0, p1, p2))
continue;
if (!cellExists(xi, yi, zi))
addCell(xi, yi, zi);
}
}
}
}
// using marching cubes to create boundaries
vertices.clear();
cellOfVertex.clear();
triIds.clear();
PxI32 edgeVertId[12];
PxVec3 cornerPos[8];
int cornerVoxelNr[8];
for (PxI32 i = 0; i < PxI32(cells.size()); i++)
{
Cell& c = cells[i];
// we need to handle a 2 x 2 x 2 block of cells to cover the boundary
for (PxI32 dx = 0; dx < 2; dx++)
{
for (PxI32 dy = 0; dy < 2; dy++)
{
for (PxI32 dz = 0; dz < 2; dz++)
{
PxI32 xi = c.xi + dx;
PxI32 yi = c.yi + dy;
PxI32 zi = c.zi + dz;
// are we responsible for this cell?
PxI32 maxCellNr = i;
for (PxI32 rx = xi - 1; rx <= xi; rx++)
for (PxI32 ry = yi - 1; ry <= yi; ry++)
for (PxI32 rz = zi - 1; rz <= zi; rz++)
maxCellNr = PxMax(maxCellNr, getCellNr(rx, ry, rz));
if (maxCellNr != i)
continue;
PxI32 code = 0;
for (PxI32 j = 0; j < 8; j++)
{
PxI32 mx = xi - 1 + marchingCubeCorners[j][0];
PxI32 my = yi - 1 + marchingCubeCorners[j][1];
PxI32 mz = zi - 1 + marchingCubeCorners[j][2];
cornerVoxelNr[j] = getCellNr(mx, my, mz);
if (cornerVoxelNr[j] >= 0)
code |= (1 << j);
cornerPos[j].x = meshBounds.minimum.x + (mx + 0.5f) * spacing;
cornerPos[j].y = meshBounds.minimum.y + (my + 0.5f) * spacing;
cornerPos[j].z = meshBounds.minimum.z + (mz + 0.5f) * spacing;
}
PxI32 first = firstMarchingCubesId[code];
PxI32 num = (firstMarchingCubesId[code + 1] - first);
// create vertices and tris
for (PxI32 j = 0; j < 12; j++)
edgeVertId[j] = -1;
for (PxI32 j = num - 1; j >= 0; j--)
{
PxI32 edgeId = marchingCubesIds[first + j];
if (edgeVertId[edgeId] < 0)
{
PxI32 id0 = marchingCubeEdges[edgeId][0];
PxI32 id1 = marchingCubeEdges[edgeId][1];
PxVec3& p0 = cornerPos[id0];
PxVec3& p1 = cornerPos[id1];
edgeVertId[edgeId] = vertices.size();
vertices.pushBack((p0 + p1) * 0.5f);
cellOfVertex.pushBack(PxMax(cornerVoxelNr[id0], cornerVoxelNr[id1]));
}
triIds.pushBack(edgeVertId[edgeId]);
}
}
}
}
}
removeDuplicateVertices();
pruneInternalSurfaces();
project(inputVerts, inputTriIds, nbTriangleIndices, 2.0f * spacing, 0.1f * spacing);
if (vertexMap)
createVertexMap(inputVerts, nbVertices, meshBounds.minimum, spacing, *vertexMap);
computeNormals();
}
// -------------------------------------------------------------------------------------
void Remesher::removeDuplicateVertices()
{
PxF32 eps = 1e-5f;
struct Ref
{
PxF32 d;
PxI32 id;
bool operator < (const Ref& r) const
{
return d < r.d;
}
};
PxI32 numVerts = PxI32(vertices.size());
PxArray<Ref> refs(numVerts);
for (PxI32 i = 0; i < numVerts; i++)
{
PxVec3& p = vertices[i];
refs[i].d = p.x + 0.3f * p.y + 0.1f * p.z;
refs[i].id = i;
}
PxSort(refs.begin(), refs.size());
PxArray<PxI32> idMap(vertices.size(), -1);
PxArray<PxVec3> oldVerts = vertices;
PxArray<PxI32> oldCellOfVertex = cellOfVertex;
vertices.clear();
cellOfVertex.clear();
PxI32 nr = 0;
while (nr < numVerts)
{
Ref& r = refs[nr];
nr++;
if (idMap[r.id] >= 0)
continue;
idMap[r.id] = vertices.size();
vertices.pushBack(oldVerts[r.id]);
cellOfVertex.pushBack(oldCellOfVertex[r.id]);
PxI32 i = nr;
while (i < numVerts && fabsf(refs[i].d - r.d) < eps)
{
PxI32 id = refs[i].id;
if ((oldVerts[r.id] - oldVerts[id]).magnitudeSquared() < eps * eps)
idMap[id] = idMap[r.id];
i++;
}
}
for (PxI32 i = 0; i < PxI32(triIds.size()); i++)
triIds[i] = idMap[triIds[i]];
}
// -------------------------------------------------------------------------------------
void Remesher::findTriNeighbors()
{
PxI32 numTris = PxI32(triIds.size()) / 3;
triNeighbors.clear();
triNeighbors.resize(3 * numTris, -1);
struct Edge
{
void init(PxI32 _id0, PxI32 _id1, PxI32 _triNr, PxI32 _edgeNr)
{
this->id0 = PxMin(_id0, _id1);
this->id1 = PxMax(_id0, _id1);
this->triNr = _triNr;
this->edgeNr = _edgeNr;
}
bool operator < (const Edge& e) const
{
if (id0 < e.id0) return true;
if (id0 > e.id0) return false;
return id1 < e.id1;
}
bool operator == (const Edge& e) const
{
return id0 == e.id0 && id1 == e.id1;
}
PxI32 id0, id1, triNr, edgeNr;
};
PxArray<Edge> edges(triIds.size());
for (PxI32 i = 0; i < numTris; i++)
{
for (PxI32 j = 0; j < 3; j++) {
PxI32 id0 = triIds[3 * i + j];
PxI32 id1 = triIds[3 * i + (j + 1) % 3];
edges[3 * i + j].init(id0, id1, i, j);
}
}
PxSort(edges.begin(), edges.size());
PxI32 nr = 0;
while (nr < PxI32(edges.size()))
{
Edge& e0 = edges[nr];
nr++;
while (nr < PxI32(edges.size()) && edges[nr] == e0) {
Edge& e1 = edges[nr];
triNeighbors[3 * e0.triNr + e0.edgeNr] = e1.triNr;
triNeighbors[3 * e1.triNr + e1.edgeNr] = e0.triNr;
nr++;
}
}
}
// -------------------------------------------------------------------------------------
void Remesher::pruneInternalSurfaces()
{
// flood islands, if the enclosed volume is negative remove it
findTriNeighbors();
PxI32 numTris = PxI32(triIds.size()) / 3;
PxArray<PxI32> oldTriIds = triIds;
triIds.clear();
PxArray<bool> visited(numTris, false);
PxArray<PxI32> stack;
for (PxI32 i = 0; i < numTris; i++)
{
if (visited[i])
continue;
stack.clear();
stack.pushBack(i);
PxI32 islandStart = PxI32(triIds.size());
float vol = 0.0f;
while (!stack.empty())
{
PxI32 triNr = stack.back();
stack.popBack();
if (visited[triNr])
continue;
visited[triNr] = true;
for (PxI32 j = 0; j < 3; j++)
triIds.pushBack(oldTriIds[3 * triNr + j]);
const PxVec3& p0 = vertices[oldTriIds[3 * triNr]];
const PxVec3& p1 = vertices[oldTriIds[3 * triNr + 1]];
const PxVec3& p2 = vertices[oldTriIds[3 * triNr + 2]];
vol += p0.cross(p1).dot(p2);
for (PxI32 j = 0; j < 3; j++)
{
PxI32 n = triNeighbors[3 * triNr + j];
if (n >= 0 && !visited[n])
stack.pushBack(n);
}
}
if (vol <= 0.0f)
triIds.resize(islandStart);
}
// remove unreferenced vertices
PxArray<PxI32> idMap(vertices.size(), -1);
PxArray<PxVec3> oldVerts = vertices;
PxArray<PxI32> oldCellOfVertex = cellOfVertex;
vertices.clear();
cellOfVertex.clear();
for (int i = 0; i < PxI32(triIds.size()); i++)
{
PxI32 id = triIds[i];
if (idMap[id] < 0)
{
idMap[id] = vertices.size();
vertices.pushBack(oldVerts[id]);
cellOfVertex.pushBack(oldCellOfVertex[id]);
}
triIds[i] = idMap[id];
}
}
// -----------------------------------------------------------------------------------
static void getClosestPointOnTriangle(const PxVec3& pos, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2,
PxVec3& closest, PxVec3& bary)
{
PxVec3 e0 = p1 - p0;
PxVec3 e1 = p2 - p0;
PxVec3 tmp = p0 - pos;
float a = e0.dot(e0);
float b = e0.dot(e1);
float c = e1.dot(e1);
float d = e0.dot(tmp);
float e = e1.dot(tmp);
PxVec3 coords, clampedCoords;
coords.x = b * e - c * d; // s * det
coords.y = b * d - a * e; // t * det
coords.z = a * c - b * b; // det
clampedCoords = PxVec3(PxZero);
if (coords.x <= 0.0f)
{
if (c != 0.0f)
clampedCoords.y = -e / c;
}
else if (coords.y <= 0.0f)
{
if (a != 0.0f)
clampedCoords.x = -d / a;
}
else if (coords.x + coords.y > coords.z)
{
float denominator = a + c - b - b;
float numerator = c + e - b - d;
if (denominator != 0.0f)
{
clampedCoords.x = numerator / denominator;
clampedCoords.y = 1.0f - clampedCoords.x;
}
}
else
{ // all inside
if (coords.z != 0.0f) {
clampedCoords.x = coords.x / coords.z;
clampedCoords.y = coords.y / coords.z;
}
}
bary.y = PxMin(PxMax(clampedCoords.x, 0.0f), 1.0f);
bary.z = PxMin(PxMax(clampedCoords.y, 0.0f), 1.0f);
bary.x = 1.0f - bary.y - bary.z;
closest = p0 * bary.x + p1 * bary.y + p2 * bary.z;
}
// -------------------------------------------------------------------------------------
void Remesher::project(const PxVec3* inputVerts, const PxU32* inputTriIds, PxU32 nbTriangleIndices,
float searchDist, float surfaceDist)
{
// build a bvh for the input mesh
PxI32 numInputTris = PxI32(nbTriangleIndices) / 3;
if (numInputTris == 0)
return;
bvhBounds.resize(numInputTris);
bvhTris.clear();
for (PxI32 i = 0; i < numInputTris; i++) {
PxBounds3& b = bvhBounds[i];
b.setEmpty();
b.include(inputVerts[inputTriIds[3 * i]]);
b.include(inputVerts[inputTriIds[3 * i + 1]]);
b.include(inputVerts[inputTriIds[3 * i + 2]]);
}
BVHDesc bvh;
BVHBuilder::build(bvh, &bvhBounds[0], bvhBounds.size());
// project vertices to closest point on surface
PxBounds3 pb;
for (PxU32 i = 0; i < vertices.size(); i++)
{
PxVec3& p = vertices[i];
pb.setEmpty();
pb.include(p);
pb.fattenFast(searchDist);
bvh.query(pb, bvhTris);
float minDist2 = PX_MAX_F32;
PxVec3 closest(PxZero);
for (PxU32 j = 0; j < bvhTris.size(); j++)
{
PxI32 triNr = bvhTris[j];
const PxVec3& p0 = inputVerts[inputTriIds[3 * triNr]];
const PxVec3& p1 = inputVerts[inputTriIds[3 * triNr + 1]];
const PxVec3& p2 = inputVerts[inputTriIds[3 * triNr + 2]];
PxVec3 c, bary;
getClosestPointOnTriangle(p, p0, p1, p2, c, bary);
float dist2 = (c - p).magnitudeSquared();
if (dist2 < minDist2) {
minDist2 = dist2;
closest = c;
}
}
if (minDist2 < PX_MAX_F32) {
PxVec3 n = p - closest;
n.normalize();
p = closest + n * surfaceDist;
}
}
}
static const int cellNeighbors[6][3] = { { -1,0,0 }, {1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} };
// -------------------------------------------------------------------------------------
void Remesher::createVertexMap(const PxVec3* inputVerts, PxU32 nbVertices, const PxVec3 &gridOrigin, PxF32 &gridSpacing,
PxArray<PxU32> &vertexMap)
{
PxArray<PxI32> vertexOfCell(cells.size(), -1);
PxArray<PxI32 > front[2];
PxI32 frontNr = 0;
// compute inverse links
for (PxI32 i = 0; i < PxI32(vertices.size()); i++)
{
PxI32 cellNr = cellOfVertex[i];
if (cellNr >= 0)
{
if (vertexOfCell[cellNr] < 0) {
vertexOfCell[cellNr] = i;
front[frontNr].pushBack(cellNr);
}
}
}
// propagate cell->vertex links through the voxel mesh
while (!front[frontNr].empty())
{
front[1 - frontNr].clear();
for (PxI32 i = 0; i < PxI32(front[frontNr].size()); i++)
{
int cellNr = front[frontNr][i];
Cell& c = cells[cellNr];
for (PxI32 j = 0; j < 6; j++)
{
PxI32 n = getCellNr(c.xi + cellNeighbors[j][0],
c.yi + cellNeighbors[j][1],
c.zi + cellNeighbors[j][2]);
if (n >= 0 && vertexOfCell[n] < 0) {
vertexOfCell[n] = vertexOfCell[cellNr];
front[1 - frontNr].pushBack(n);
}
}
}
frontNr = 1 - frontNr;
}
// create the map
vertexMap.clear();
vertexMap.resize(nbVertices, 0);
for (PxU32 i = 0; i < nbVertices; i++)
{
const PxVec3& p = inputVerts[i];
PxI32 xi = PxI32(PxFloor((p.x - gridOrigin.x) / gridSpacing));
PxI32 yi = PxI32(PxFloor((p.y - gridOrigin.y) / gridSpacing));
PxI32 zi = PxI32(PxFloor((p.z - gridOrigin.z) / gridSpacing));
PxI32 cellNr = getCellNr(xi, yi, zi);
vertexMap[i] = cellNr >= 0 ? vertexOfCell[cellNr] : 0;
}
}
// -------------------------------------------------------------------------------------
void Remesher::computeNormals()
{
normals.clear();
normals.resize(vertices.size(), PxVec3(PxZero));
for (PxI32 i = 0; i < PxI32(triIds.size()); i += 3)
{
PxI32* ids = &triIds[i];
PxVec3& p0 = vertices[ids[0]];
PxVec3& p1 = vertices[ids[1]];
PxVec3& p2 = vertices[ids[2]];
PxVec3 n = (p1 - p0).cross(p2 - p0);
normals[ids[0]] += n;
normals[ids[1]] += n;
normals[ids[2]] += n;
}
for (PxI32 i = 0; i < PxI32(normals.size()); i++)
normals[i].normalize();
}
// -------------------------------------------------------------------------------------
void Remesher::readBack(PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputTriIds)
{
outputVertices = vertices;
outputTriIds.resize(triIds.size());
for (PxU32 i = 0; i < triIds.size(); i++)
outputTriIds[i] = PxU32(triIds[i]);
}
}
}
| 18,791 | C++ | 27.472727 | 163 | 0.552232 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayBoundaryInserter.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 EXT_DELAUNAY_BOUNDARY_INSERTER_H
#define EXT_DELAUNAY_BOUNDARY_INSERTER_H
#include "foundation/PxHashSet.h"
#include "foundation/PxVec3.h"
#include "foundation/PxMat33.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxArray.h"
#include "common/PxCoreUtilityTypes.h"
#include "extensions/PxTriangleMeshAnalysisResult.h"
#include "extensions/PxTetrahedronMeshAnalysisResult.h"
#include "ExtDelaunayTetrahedralizer.h"
namespace physx
{
namespace Ext
{
//Generates a tetmesh that matches the specified triangle mesh. All triangle mesh points are present in the tetmesh, additional points on edges and faces might be present.
void generateTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTriangles, const bool has16bitIndices, PxArray<PxVec3>& tetPoints, PxArray<PxU32>& finalTets);
//Generates a tetmesh that that matches the surface of the input tetmesh approximately but creats very regular shaped tetrahedra.
void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxU32 numVoxelsX, PxU32 numVoxelsY, PxU32 numVoxelsZ,
PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices = NULL, PxU32 numTetsPerVoxel = 5);
//Generates a tetmesh that that matches the surface of the input tetmesh approximately but creats very regular shaped tetrahedra.
void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxReal voxelEdgeLength,
PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices = NULL, PxU32 numTetsPerVoxel = 5);
//Generates a tetmesh that that matches the surface of the input tetmesh approximately but creats very regular shaped tetrahedra.
void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxU32 numVoxelsAlongLongestBoundingBoxAxis,
PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices = NULL, PxU32 numTetsPerVoxel = 5);
//Extracts the surface triangles from the specified tetrahedra
void extractTetmeshSurface(const PxArray<PxI32>& tets, PxArray<PxI32>& triangles);
//Computes the lumped mass per vertex for the specified tetmesh
void pointMasses(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxF32 density, PxArray<PxF32>& mass);
//Computes a rest pose matrix for every tetrahedron in the specified tetmesh
void restPoses(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxArray<PxMat33>& restPoses);
//Computes a fiber direction for every tetrahedron in the specified tetmesh. Currently just returns dummy values.
void tetFibers(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxArray<PxVec3>& tetFibers);
//Analyzes the triangle mesh to get a report about deficiencies. Some deficiencies can be handled by the tetmesher, others cannot.
PxTriangleMeshAnalysisResults validateTriangleMesh(const PxBoundedData& points, const PxBoundedData& triangles, const bool has16BitIndices, const PxReal minVolumeThreshold = 1e-6f, const PxReal minTriangleAngleRadians = 10.0f*3.1415926535898f / 180.0f);
//Analyzes the tetrahedron mesh to get a report about deficiencies. Some deficiencies can be handled by the softbody cooker, others cannot.
PxTetrahedronMeshAnalysisResults validateTetrahedronMesh(const PxBoundedData& points, const PxBoundedData& tetrahedra, const bool has16BitIndices, const PxReal minTetVolumeThreshold = 1e-8f);
PxU32 removeDisconnectedIslands(PxI32* finalTets, PxU32 numTets);
}
}
#endif
| 5,211 | C | 61.047618 | 254 | 0.801574 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtUtilities.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/PxAssert.h"
#include "ExtUtilities.h"
#include "GuAABBTreeBuildStats.h"
#include "foundation/PxFPU.h"
namespace physx
{
namespace Ext
{
using namespace Gu;
static PxVec3 toFloat(const PxVec3d& p)
{
return PxVec3(PxReal(p.x), PxReal(p.y), PxReal(p.z));
}
void buildTree(const PxU32* triangles, const PxU32 numTriangles, const PxVec3d* points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement)
{
//Computes a bounding box for every triangle in triangles
AABBTreeBounds boxes;
boxes.init(numTriangles);
for (PxU32 i = 0; i < numTriangles; ++i)
{
const PxU32* tri = &triangles[3 * i];
PxBounds3 box = PxBounds3::empty();
box.include(toFloat(points[tri[0]]));
box.include(toFloat(points[tri[1]]));
box.include(toFloat(points[tri[2]]));
box.fattenFast(enlargement);
boxes.getBounds()[i] = box;
}
Gu::buildAABBTree(numTriangles, boxes, tree);
}
}
}
| 2,472 | C++ | 38.253968 | 135 | 0.743123 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtOctreeTetrahedralizer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_OCTREE_TETRAHEDRALIZER_H
#define EXT_OCTREE_TETRAHEDRALIZER_H
#include "ExtMultiList.h"
#include "ExtVec3.h"
#include "foundation/PxVec3.h"
#include "ExtInsideTester.h"
namespace physx
{
namespace Ext
{
class InsideTester;
// ------------------------------------------------------------------------------
class OctreeTetrahedralizer
{
public:
OctreeTetrahedralizer();
void clear();
void createTetMesh(const PxArray<PxVec3> &verts, const PxArray<PxU32> &triIds,
bool includeOctreeNodes = true, PxI32 maxVertsPerCell = 20, PxI32 maxTreeDepth = 5);
void readBack(PxArray<PxVec3> &tetVertices, PxArray<PxU32> &tetIndices);
private:
// input mesh
PxArray<PxVec3> surfaceVerts;
PxArray<PxI32> surfaceTriIds;
// octree
PxI32 maxVertsPerCell;
PxI32 maxTreeDepth;
struct Cell
{
void init()
{
firstChild = -1;
orig = PxVec3d(0.0, 0.0, 0.0);
size = 0.0;
numVerts = 0;
closestTetNr = -1;
depth = 0;
}
PxI32 getChildNr(const PxVec3d& p);
PX_FORCE_INLINE PxI32 getChildNr(const PxVec3& p)
{
return getChildNr(PxVec3d(PxF64(p.x), PxF64(p.y), PxF64(p.z)));
}
PxI32 firstChild;
PxI32 firstCellVert;
PxI32 firstCellTet;
PxVec3d orig;
double size;
PxI32 numVerts;
PxI32 closestTetNr;
PxI32 depth;
};
PxArray<Cell> cells;
MultiList<PxI32> vertsOfCell;
// tet mesh
PxArray<PxVec3d> tetVerts;
PxArray<PxI32> tetIds;
PxArray<PxI32> tetNeighbors;
PxArray<PxI32> tetMarks;
PxI32 currentTetMark;
PxArray<PxI32> stack;
PxArray<PxI32> violatingTets;
PxI32 firstABBVert;
struct Edge
{
PxI32 id0, id1;
PxI32 faceNr, tetNr;
void init(PxI32 _id0, PxI32 _id1, PxI32 _tetNr, PxI32 _faceNr)
{
this->id0 = _id0 < _id1 ? _id0 : _id1;
this->id1 = _id0 > _id1 ? _id0 : _id1;
this->tetNr = _tetNr;
this->faceNr = _faceNr;
}
PX_FORCE_INLINE bool operator < (Edge e) const
{
if (id0 < e.id0) return true;
if (id0 > e.id0) return false;
return id1 < e.id1;
}
PX_FORCE_INLINE bool operator == (Edge e)
{
return id0 == e.id0 && id1 == e.id1;
}
};
PxArray<Edge> edges;
void clearTets();
void createTree();
void treeInsertVert(PxI32 cellNr, PxI32 vertNr);
void createTetVerts(bool includeOctreeNodes);
bool findSurroundingTet(const PxVec3d& p, PxI32 startTetNr, PxI32& tetNr);
bool findSurroundingTet(const PxVec3d& p, PxI32& tetNr);
void treeInsertTet(PxI32 tetNr);
void treeRemoveTet(PxI32 tetNr);
PxI32 firstFreeTet;
PxI32 getNewTetNr();
void removeTetNr(PxI32 tetNr);
PxVec3d getTetCenter(PxI32 tetNr) const;
bool meshInsertTetVert(PxI32 vertNr);
InsideTester insideTester;
void pruneTets();
mutable float prevClip;
mutable float prevScale;
mutable PxArray<PxVec3> renderVerts;
mutable PxArray<PxVec3> renderNormals;
mutable PxArray<PxI32> renderTriIds;
};
}
}
#endif
| 4,717 | C | 26.752941 | 88 | 0.684757 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtVoxelTetrahedralizer.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 "ExtVoxelTetrahedralizer.h"
#include "CmRandom.h"
#include "ExtTetUnionFind.h"
namespace physx
{
namespace Ext
{
// -------------------------------------------------------------------------------------
static PxI32 cubeNeighbors[6][3] = { { -1,0,0 }, {1,0,0}, {0,-1,0}, {0,1,0}, {0,0,-1}, {0,0,1} };
static const PxI32 cubeCorners[8][3] = { {0,0,0}, {1,0,0},{1,1,0},{0,1,0}, {0,0,1}, {1,0,1},{1,1,1},{0,1,1} };
static const PxI32 cubeFaces[6][4] = { {0,3,7,4},{1,2,6,5},{0,1,5,4},{3,2,6,7},{0,1,2,3},{4,5,6,7} };
static const PxI32 oppNeighbor[6] = { 1,0,3,2,5,4 };
static const PxI32 tetEdges[12][2] = { {0,1},{1,2},{2,0},{0,3},{1,3},{2,3}, {1,0},{2,1},{0,2},{3,0},{3,1},{3,2} };
static PxI32 cubeSixTets[6][4] = {
{ 0, 4, 5, 7 },{ 1, 5, 6, 7 },{ 1, 0, 5, 7 },{ 1, 2, 3, 6 },{ 3, 1, 6, 7 },{ 0, 1, 3, 7 } };
static PxI32 cubeFiveTets[2][5][4] = {
{ { 0, 1, 2, 5 },{ 0, 2, 3, 7 },{ 0, 5, 2, 7 },{ 0, 5, 7, 4 },{ 2, 7, 5, 6 } },
{ { 1, 2, 3, 6 },{ 1, 3, 0, 4 },{ 1, 6, 3, 4 },{ 1, 6, 4, 5 },{ 3, 4, 6, 7 } },
};
static PxI32 cubeSixSubdivTets[12][4] = {
{0,4,5,8}, {0,5,1,8}, {3,2,6,8}, {3,6,7,8},
{0,3,7,8}, {0,7,4,8}, {1,5,6,8}, {1,6,2,8},
{0,1,3,8}, {1,2,3,8}, {5,4,7,8}, {5,7,6,8}
};
static PxI32 cubeFiveSubdivTets[2][12][4] = {
{
{0,1,2,8}, {0,2,3,8}, {4,7,5,8}, {5,7,6,8},
{0,7,4,8}, {0,3,7,8}, {1,5,2,8}, {2,5,6,8},
{0,5,1,8}, {0,4,5,8}, {3,2,7,8}, {2,6,7,8}
},
{
{0,1,3,8}, {1,2,3,8}, {4,7,6,8}, {4,6,5,8},
{0,3,4,8}, {3,7,4,8}, {1,5,6,8}, {1,6,2,8},
{0,4,1,8}, {1,4,5,8}, {3,2,6,8}, {3,6,7,8}
}
};
static const PxI32 volIdOrder[4][3] = { {1, 3, 2}, {0, 2, 3}, {0, 3, 1}, {0, 1, 2} };
// -------------------------------------------------------------------------------------
static bool boxTriangleIntersection(
PxVec3 p0, PxVec3 p1, PxVec3 p2, PxVec3 center, PxVec3 extents);
static void getClosestPointOnTriangle(
PxVec3 p1, PxVec3 p2, PxVec3 p3, PxVec3 p, PxVec3& closest, PxVec3& bary);
// -------------------------------------------------------------------------------------
VoxelTetrahedralizer::VoxelTetrahedralizer()
{
clear();
}
// -------------------------------------------------------------------------------------
void VoxelTetrahedralizer::clear()
{
surfaceVerts.clear();
surfaceTriIds.clear();
surfaceBounds.setEmpty();
tetVerts.clear();
origTetVerts.clear();
isSurfaceVert.clear();
targetVertPos.clear();
tetIds.clear();
voxels.clear();
gridOrigin = PxVec3(PxZero);
gridSpacing = 0.0f;
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::readBack(PxArray<PxVec3>& _tetVertices, PxArray<PxU32>& _tetIndices)
{
_tetVertices = tetVerts;
_tetIndices.resize(tetIds.size());
for (PxU32 i = 0; i < tetIds.size(); i++)
_tetIndices[i] = PxU32(tetIds[i]);
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::createTetMesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds,
PxI32 resolution, PxI32 numRelaxationIters, PxF32 relMinTetVolume)
{
surfaceVerts = verts;
surfaceTriIds.resize(triIds.size());
for (PxU32 i = 0; i < triIds.size(); i++)
surfaceTriIds[i] = triIds[i];
surfaceBounds.setEmpty();
for (PxU32 i = 0; i < surfaceVerts.size(); i++)
surfaceBounds.include(surfaceVerts[i]);
buildBVH();
voxelize(resolution);
bool subdivBorder = true;
int numTetsPerVoxel = 5; // or 6
createTets(subdivBorder, numTetsPerVoxel);
findTargetPositions(0.2f * gridSpacing);
relax(numRelaxationIters, relMinTetVolume);
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::buildBVH()
{
PxI32 numTris = PxI32(surfaceTriIds.size()) / 3;
if (numTris == 0)
return;
PxArray<PxBounds3> bvhBounds(numTris);
for (PxI32 i = 0; i < numTris; i++) {
PxBounds3& b = bvhBounds[i];
b.setEmpty();
b.include(surfaceVerts[surfaceTriIds[3 * i]]);
b.include(surfaceVerts[surfaceTriIds[3 * i + 1]]);
b.include(surfaceVerts[surfaceTriIds[3 * i + 2]]);
}
BVHBuilder::build(bvh, &bvhBounds[0], bvhBounds.size());
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::voxelize(PxU32 resolution)
{
tetIds.clear();
tetVerts.clear();
PxBounds3 meshBounds;
meshBounds.setEmpty();
for (PxU32 i = 0; i < surfaceVerts.size(); i++)
meshBounds.include(surfaceVerts[i]);
gridSpacing = meshBounds.getDimensions().magnitude() / resolution;
meshBounds.fattenSafe(gridSpacing);
gridOrigin = meshBounds.minimum;
voxels.clear();
PxI32 numX = PxI32((meshBounds.maximum.x - meshBounds.minimum.x) / gridSpacing) + 1;
PxI32 numY = PxI32((meshBounds.maximum.y - meshBounds.minimum.y) / gridSpacing) + 1;
PxI32 numZ = PxI32((meshBounds.maximum.z - meshBounds.minimum.z) / gridSpacing) + 1;
PxI32 numCells = numX * numY * numZ;
PxArray<PxI32> voxelOfCell(numCells, -1);
PxBounds3 voxelBounds, faceBounds;
// create intersected voxels
for (PxI32 i = 0; i < numCells; i++) {
PxI32 zi = i % numZ;
PxI32 yi = (i / numZ) % numY;
PxI32 xi = (i / numZ / numY);
voxelBounds.minimum = meshBounds.minimum + PxVec3(PxF32(xi), PxF32(yi), PxF32(zi)) * gridSpacing;
voxelBounds.maximum = voxelBounds.minimum + PxVec3(gridSpacing);
bvh.query(voxelBounds, queryTris);
for (PxU32 j = 0; j < queryTris.size(); j++) {
PxI32 triNr = queryTris[j];
const PxVec3& p0 = surfaceVerts[surfaceTriIds[3 * triNr]];
const PxVec3& p1 = surfaceVerts[surfaceTriIds[3 * triNr + 1]];
const PxVec3& p2 = surfaceVerts[surfaceTriIds[3 * triNr + 2]];
if (boxTriangleIntersection(p0, p1, p2, voxelBounds.getCenter(), voxelBounds.getExtents())) {
// volume
if (voxelOfCell[i] < 0) {
voxelOfCell[i] = voxels.size();
voxels.resize(voxels.size() + 1);
voxels.back().init(xi, yi, zi);
}
}
}
}
// flood outside
PxArray<PxI32> stack;
stack.pushBack(0);
while (!stack.empty()) {
PxI32 nr = stack.back();
stack.popBack();
if (voxelOfCell[nr] == -1) {
voxelOfCell[nr] = -2; // outside
PxI32 z0 = nr % numZ;
PxI32 y0 = (nr / numZ) % numY;
PxI32 x0 = (nr / numZ / numY);
for (PxI32 i = 0; i < 6; i++) {
PxI32 xi = x0 + cubeNeighbors[i][0];
PxI32 yi = y0 + cubeNeighbors[i][1];
PxI32 zi = z0 + cubeNeighbors[i][2];
if (xi >= 0 && xi < numX && yi >= 0 && yi < numY && zi >= 0 && zi < numZ) {
PxI32 adj = (xi * numY + yi) * numZ + zi;
if (voxelOfCell[adj] == -1)
stack.pushBack(adj);
}
}
}
}
// create voxels for the inside
for (PxI32 i = 0; i < numCells; i++) {
if (voxelOfCell[i] == -1) {
voxelOfCell[i] = voxels.size();
voxels.resize(voxels.size() + 1);
PxI32 zi = i % numZ;
PxI32 yi = (i / numZ) % numY;
PxI32 xi = (i / numZ / numY);
voxels.back().init(xi, yi, zi);
voxels.back().inner = true;
}
}
// find neighbors
for (PxU32 i = 0; i < voxels.size(); i++) {
Voxel& v = voxels[i];
voxelBounds.minimum = meshBounds.minimum + PxVec3(PxF32(v.xi), PxF32(v.yi), PxF32(v.zi)) * gridSpacing;
voxelBounds.maximum = voxelBounds.minimum + PxVec3(gridSpacing);
for (PxI32 j = 0; j < 6; j++) {
PxI32 xi = v.xi + cubeNeighbors[j][0];
PxI32 yi = v.yi + cubeNeighbors[j][1];
PxI32 zi = v.zi + cubeNeighbors[j][2];
if (xi < 0 || xi >= numX || yi < 0 || yi >= numY || zi < 0 || zi >= numZ)
continue;
PxI32 neighbor = voxelOfCell[(xi * numY + yi) * numZ + zi];
if (neighbor < 0)
continue;
if (v.inner || voxels[neighbor].inner) {
v.neighbors[j] = neighbor;
continue;
}
faceBounds = voxelBounds;
PxF32 eps = 1e-4f;
switch (j) {
case 0: faceBounds.maximum.x = faceBounds.minimum.x + eps; break;
case 1: faceBounds.minimum.x = faceBounds.maximum.x - eps; break;
case 2: faceBounds.maximum.y = faceBounds.minimum.y + eps; break;
case 3: faceBounds.minimum.y = faceBounds.maximum.y - eps; break;
case 4: faceBounds.maximum.z = faceBounds.minimum.z + eps; break;
case 5: faceBounds.minimum.z = faceBounds.maximum.z - eps; break;
}
bvh.query(faceBounds, queryTris);
bool intersected = false;
for (PxU32 k = 0; k < queryTris.size(); k++) {
PxI32 triNr = queryTris[k];
const PxVec3& p0 = surfaceVerts[surfaceTriIds[3 * triNr]];
const PxVec3& p1 = surfaceVerts[surfaceTriIds[3 * triNr + 1]];
const PxVec3& p2 = surfaceVerts[surfaceTriIds[3 * triNr + 2]];
if (boxTriangleIntersection(p0, p1, p2, faceBounds.getCenter(), faceBounds.getExtents())) {
intersected = true;
break;
}
}
if (intersected)
v.neighbors[j] = neighbor;
}
}
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::createUniqueTetVertices()
{
// start with each voxel having its own vertices
PxArray<PxVec3> verts;
for (PxU32 i = 0; i < voxels.size(); i++) {
Voxel& v = voxels[i];
for (PxI32 j = 0; j < 8; j++) {
v.ids[j] = verts.size();
verts.pushBack(gridOrigin + PxVec3(
PxF32(v.xi + cubeCorners[j][0]),
PxF32(v.yi + cubeCorners[j][1]),
PxF32(v.zi + cubeCorners[j][2])) * gridSpacing);
}
}
// unify vertices
UnionFind* u = new UnionFind();
u->init(verts.size());
for (PxU32 i = 0; i < voxels.size(); i++) {
Voxel& v0 = voxels[i];
for (PxI32 j = 0; j < 6; j++) {
PxI32 n = v0.neighbors[j];
if (n < 0)
continue;
Voxel& v1 = voxels[n];
for (PxI32 k = 0; k < 4; k++) {
PxI32 id0 = v0.ids[cubeFaces[j][k]];
PxI32 id1 = v1.ids[cubeFaces[oppNeighbor[j]][k]];
u->makeSet(id0, id1);
}
}
}
u->computeSetNrs();
tetVerts.clear();
for (PxU32 i = 0; i < voxels.size(); i++) {
Voxel& v = voxels[i];
for (PxI32 j = 0; j < 8; j++) {
PxI32 setNr = u->getSetNr(v.ids[j]);
if (PxI32(tetVerts.size()) <= setNr)
tetVerts.resize(setNr + 1, PxVec3(PxZero));
tetVerts[setNr] = verts[v.ids[j]];
v.ids[j] = setNr;
}
}
origTetVerts = tetVerts;
delete u;
}
// -------------------------------------------------------------------------------------
void VoxelTetrahedralizer::findTargetPositions(PxF32 surfaceDist)
{
targetVertPos = tetVerts;
for (PxU32 i = 0; i < voxels.size(); i++) {
Voxel& v = voxels[i];
PxBounds3 voxelBounds;
voxelBounds.minimum = gridOrigin + PxVec3(PxF32(v.xi), PxF32(v.yi), PxF32(v.zi)) * gridSpacing;
voxelBounds.maximum = voxelBounds.minimum + PxVec3(gridSpacing);
voxelBounds.fattenFast(0.1f * gridSpacing);
bvh.query(voxelBounds, queryTris);
for (PxI32 j = 0; j < 8; j++) {
PxI32 id = v.ids[j];
if (!isSurfaceVert[id])
continue;
PxVec3& p = tetVerts[id];
PxF32 minDist2 = PX_MAX_F32;
PxVec3 closest(PxZero);
for (PxU32 k = 0; k < queryTris.size(); k++) {
PxI32 triNr = queryTris[k];
const PxVec3& p0 = surfaceVerts[surfaceTriIds[3 * triNr]];
const PxVec3& p1 = surfaceVerts[surfaceTriIds[3 * triNr + 1]];
const PxVec3& p2 = surfaceVerts[surfaceTriIds[3 * triNr + 2]];
PxVec3 c, bary;
getClosestPointOnTriangle(p0, p1, p2, p, c, bary);
PxF32 dist2 = (c - p).magnitudeSquared();
if (dist2 < minDist2) {
minDist2 = dist2;
closest = c;
}
}
if (minDist2 < PX_MAX_F32) {
PxVec3 n = p - closest;
n.normalize();
targetVertPos[id] = closest + n * surfaceDist;
}
}
}
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::createTets(bool subdivBorder, PxU32 numTetsPerVoxel)
{
if (numTetsPerVoxel < 5 || numTetsPerVoxel > 6)
return;
createUniqueTetVertices();
PxArray<Voxel> prevVoxels;
PxArray<PxI32> numVertVoxels(tetVerts.size(), 0);
tetIds.clear();
for (PxU32 i = 0; i < voxels.size(); i++) {
Voxel& v = voxels[i];
for (PxI32 j = 0; j < 8; j++)
numVertVoxels[v.ids[j]]++;
PxI32 parity = (v.xi + v.yi + v.zi) % 2;
if (v.inner || !subdivBorder) {
if (numTetsPerVoxel == 6) {
for (PxI32 j = 0; j < 6; j++) {
tetIds.pushBack(v.ids[cubeSixTets[j][0]]);
tetIds.pushBack(v.ids[cubeSixTets[j][1]]);
tetIds.pushBack(v.ids[cubeSixTets[j][2]]);
tetIds.pushBack(v.ids[cubeSixTets[j][3]]);
}
}
else if (numTetsPerVoxel == 5) {
for (PxI32 j = 0; j < 5; j++) {
tetIds.pushBack(v.ids[cubeFiveTets[parity][j][0]]);
tetIds.pushBack(v.ids[cubeFiveTets[parity][j][1]]);
tetIds.pushBack(v.ids[cubeFiveTets[parity][j][2]]);
tetIds.pushBack(v.ids[cubeFiveTets[parity][j][3]]);
}
}
}
else {
PxVec3 p(PxZero);
for (PxI32 j = 0; j < 8; j++)
p += tetVerts[v.ids[j]];
p /= 8.0;
PxI32 newId = tetVerts.size();
tetVerts.pushBack(p);
origTetVerts.pushBack(p);
numVertVoxels.pushBack(8);
for (PxI32 j = 0; j < 12; j++) {
const int* localIds;
if (numTetsPerVoxel == 6)
localIds = cubeSixSubdivTets[j];
else
localIds = cubeFiveSubdivTets[parity][j];
for (PxI32 k = 0; k < 4; k++) {
PxI32 id = localIds[k] < 8 ? v.ids[localIds[k]] : newId;
tetIds.pushBack(id);
}
}
}
}
isSurfaceVert.resize(tetVerts.size(), false);
for (PxU32 i = 0; i < tetVerts.size(); i++)
isSurfaceVert[i] = numVertVoxels[i] < 8;
// randomize tets
PxU32 numTets = tetIds.size() / 4;
//for (PxU32 i = 0; i < numTets - 1; i++) {
// PxI32 ri = i + rand() % (numTets - i);
// for (PxI32 j = 0; j < 4; j++) {
// PxI32 id = tetIds[4 * i + j]; tetIds[4 * i + j] = tetIds[4 * ri + j]; tetIds[4 * ri + j] = id;
// }
//}
// edges
MultiList<int> adjVerts;
edgeIds.clear();
adjVerts.clear();
adjVerts.reserve(tetVerts.size());
for (PxU32 i = 0; i < numTets; i++) {
for (PxI32 j = 0; j < 6; j++) {
PxI32 id0 = tetIds[4 * i + tetEdges[j][0]];
PxI32 id1 = tetIds[4 * i + tetEdges[j][1]];
if (!adjVerts.exists(id0, id1)) {
edgeIds.pushBack(id0);
edgeIds.pushBack(id1);
adjVerts.addUnique(id0, id1);
adjVerts.addUnique(id1, id0);
}
}
}
}
// -----------------------------------------------------------------------------------
void VoxelTetrahedralizer::conserveVolume(PxF32 relMinVolume)
{
PxVec3 grads[4];
PxU32 numTets = tetIds.size() / 4;
for (PxU32 i = 0; i < numTets; i++) {
PxI32* ids = &tetIds[4 * i];
PxF32 w = 0.0f;
for (PxI32 j = 0; j < 4; j++) {
PxI32 id0 = ids[volIdOrder[j][0]];
PxI32 id1 = ids[volIdOrder[j][1]];
PxI32 id2 = ids[volIdOrder[j][2]];
grads[j] = (tetVerts[id1] - tetVerts[id0]).cross(tetVerts[id2] - tetVerts[id0]);
w += grads[j].magnitudeSquared();
}
if (w == 0.0f)
continue;
PxVec3& p0 = tetVerts[ids[0]];
PxF32 V = (tetVerts[ids[1]] - p0).cross(tetVerts[ids[2]] - p0).dot(tetVerts[ids[3]] - p0);
PxVec3& origP0 = origTetVerts[ids[0]];
PxF32 origV = (origTetVerts[ids[1]] - origP0).cross(origTetVerts[ids[2]] - origP0).dot(origTetVerts[ids[3]] - origP0);
PxF32 minV = relMinVolume * origV;
if (V < minV) {
PxF32 C = V - minV;
PxF32 lambda = -C / w;
for (PxI32 j = 0; j < 4; j++) {
tetVerts[ids[j]] += grads[j] * lambda;
}
}
}
}
// -------------------------------------------------------------------------------------
void VoxelTetrahedralizer::relax(PxI32 numIters, PxF32 relMinVolume)
{
const PxF32 targetScale = 0.3f;
const PxF32 edgeScale = 0.3f;
for (PxI32 iter = 0; iter < numIters; iter++) {
PxU32 numVerts = tetVerts.size();
for (PxU32 i = 0; i < numVerts; i++) {
if (isSurfaceVert[i]) {
PxVec3 offset = (targetVertPos[i] - tetVerts[i]) * targetScale;
tetVerts[i] += offset;
}
}
for (PxU32 i = 0; i < edgeIds.size(); i += 2) {
PxI32 id0 = edgeIds[i];
PxI32 id1 = edgeIds[i + 1];
PxF32 w0 = isSurfaceVert[id0] ? 0.0f : 1.0f;
PxF32 w1 = isSurfaceVert[id1] ? 0.0f : 1.0f;
PxF32 w = w0 + w1;
if (w == 0.0f)
continue;
PxVec3& p0 = tetVerts[id0];
PxVec3& p1 = tetVerts[id1];
PxVec3 e = (p1 - p0) * edgeScale;
if (w == 1.0f)
e *= 0.5f;
p0 += w0 / w * e;
p1 -= w1 / w * e;
}
conserveVolume(relMinVolume);
}
PxI32 volIters = 2;
for (PxI32 volIter = 0; volIter < volIters; volIter++)
conserveVolume(relMinVolume);
}
// -----------------------------------------------------------------------------------
static PxF32 max3(PxF32 f0, PxF32 f1, PxF32 f2) {
return PxMax(f0, PxMax(f1, f2));
}
static PxF32 min3(PxF32 f0, PxF32 f1, PxF32 f2) {
return PxMin(f0, PxMin(f1, f2));
}
static PxF32 minMax(PxF32 f0, PxF32 f1, PxF32 f2) {
return PxMax(-max3(f0, f1, f2), min3(f0, f1, f2));
}
// -----------------------------------------------------------------------------------
static bool boxTriangleIntersection(
PxVec3 p0, PxVec3 p1, PxVec3 p2, PxVec3 center, PxVec3 extents)
{
PxVec3 v0 = p0 - center, v1 = p1 - center, v2 = p2 - center;
PxVec3 f0 = p1 - p0, f1 = p2 - p1, f2 = p0 - p2;
PxF32 r;
PxVec3 n = f0.cross(f1);
PxF32 d = n.dot(v0);
r = extents.x * fabsf(n.x) + extents.y * fabsf(n.y) + extents.z * fabsf(n.z);
if (d > r || d < -r)
return false;
if (max3(v0.x, v1.x, v2.x) < -extents.x || min3(v0.x, v1.x, v2.x) > extents.x)
return false;
if (max3(v0.y, v1.y, v2.y) < -extents.y || min3(v0.y, v1.y, v2.y) > extents.y)
return false;
if (max3(v0.z, v1.z, v2.z) < -extents.z || min3(v0.z, v1.z, v2.z) > extents.z)
return false;
PxVec3 a00(0.0f, -f0.z, f0.y);
r = extents.y * fabsf(f0.z) + extents.z * fabsf(f0.y);
if (minMax(v0.dot(a00), v1.dot(a00), v2.dot(a00)) > r)
return false;
PxVec3 a01(0.0f, -f1.z, f1.y);
r = extents.y * fabsf(f1.z) + extents.z * fabsf(f1.y);
if (minMax(v0.dot(a01), v1.dot(a01), v2.dot(a01)) > r)
return false;
PxVec3 a02(0.0f, -f2.z, f2.y);
r = extents.y * fabsf(f2.z) + extents.z * fabsf(f2.y);
if (minMax(v0.dot(a02), v1.dot(a02), v2.dot(a02)) > r)
return false;
PxVec3 a10(f0.z, 0.0f, -f0.x);
r = extents.x * fabsf(f0.z) + extents.z * fabsf(f0.x);
if (minMax(v0.dot(a10), v1.dot(a10), v2.dot(a10)) > r)
return false;
PxVec3 a11(f1.z, 0.0f, -f1.x);
r = extents.x * fabsf(f1.z) + extents.z * fabsf(f1.x);
if (minMax(v0.dot(a11), v1.dot(a11), v2.dot(a11)) > r)
return false;
PxVec3 a12(f2.z, 0.0f, -f2.x);
r = extents.x * fabsf(f2.z) + extents.z * fabsf(f2.x);
if (minMax(v0.dot(a12), v1.dot(a12), v2.dot(a12)) > r)
return false;
PxVec3 a20(-f0.y, f0.x, 0.0f);
r = extents.x * fabsf(f0.y) + extents.y * fabsf(f0.x);
if (minMax(v0.dot(a20), v1.dot(a20), v2.dot(a20)) > r)
return false;
PxVec3 a21(-f1.y, f1.x, 0.0f);
r = extents.x * fabsf(f1.y) + extents.y * fabsf(f1.x);
if (minMax(v0.dot(a21), v1.dot(a21), v2.dot(a21)) > r)
return false;
PxVec3 a22(-f2.y, f2.x, 0.0f);
r = extents.x * fabsf(f2.y) + extents.y * fabsf(f2.x);
if (minMax(v0.dot(a22), v1.dot(a22), v2.dot(a22)) > r)
return false;
return true;
}
// -----------------------------------------------------------------------------------
static void getClosestPointOnTriangle(
PxVec3 p1, PxVec3 p2, PxVec3 p3, PxVec3 p, PxVec3& closest, PxVec3& bary)
{
PxVec3 e0 = p2 - p1;
PxVec3 e1 = p3 - p1;
PxVec3 tmp = p1 - p;
PxF32 a = e0.dot(e0);
PxF32 b = e0.dot(e1);
PxF32 c = e1.dot(e1);
PxF32 d = e0.dot(tmp);
PxF32 e = e1.dot(tmp);
PxVec3 coords, clampedCoords;
coords.x = b * e - c * d; // s * det
coords.y = b * d - a * e; // t * det
coords.z = a * c - b * b; // det
clampedCoords = PxVec3(0.0f, 0.0f, 0.0f);
if (coords.x <= 0.0f) {
if (c != 0.0f)
clampedCoords.y = -e / c;
}
else if (coords.y <= 0.0f) {
if (a != 0.0f)
clampedCoords.x = -d / a;
}
else if (coords.x + coords.y > coords.z) {
PxF32 denominator = a + c - b - b;
PxF32 numerator = c + e - b - d;
if (denominator != 0.0f) {
clampedCoords.x = numerator / denominator;
clampedCoords.y = 1.0f - clampedCoords.x;
}
}
else { // all inside
if (coords.z != 0.0f) {
clampedCoords.x = coords.x / coords.z;
clampedCoords.y = coords.y / coords.z;
}
}
clampedCoords.x = PxMax(clampedCoords.x, 0.0f);
clampedCoords.y = PxMax(clampedCoords.y, 0.0f);
clampedCoords.x = PxMin(clampedCoords.x, 1.0f);
clampedCoords.y = PxMin(clampedCoords.y, 1.0f);
closest = p1 + e0 * clampedCoords.x + e1 * clampedCoords.y;
bary.x = 1.0f - clampedCoords.x - clampedCoords.y;
bary.y = clampedCoords.x;
bary.z = clampedCoords.y;
}
}
}
| 22,879 | C++ | 29.184697 | 122 | 0.544954 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtInsideTester.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 "ExtInsideTester.h"
#include "foundation/PxBounds3.h"
namespace physx
{
namespace Ext
{
// ------------------------------------------------------------------------
void InsideTester::init(const PxVec3 *vertices, PxI32 numVertices, const PxI32 *triIndices, PxI32 numTris)
{
PxArray<PxI32> newIds(numVertices, -1);
mVertices.clear();
mIndices.clear();
for (PxI32 i = 0; i < 3 * numTris; i++)
{
PxI32 id = triIndices[i];
if (newIds[id] < 0)
{
newIds[id] = PxI32(mVertices.size());
mVertices.pushBack(vertices[id]);
}
mIndices.pushBack(newIds[id]);
}
mGrids[0].init(0, mVertices, mIndices);
mGrids[1].init(1, mVertices, mIndices);
mGrids[2].init(2, mVertices, mIndices);
}
// ------------------------------------------------------------------------
bool InsideTester::isInside(const PxVec3 &pos)
{
PxI32 vote = 0;
vote += mGrids[0].numInside(pos, mVertices, mIndices);
vote += mGrids[1].numInside(pos, mVertices, mIndices);
vote += mGrids[2].numInside(pos, mVertices, mIndices);
return (vote > 3);
}
// ------------------------------------------------------------------------
void InsideTester::Grid2d::init(PxI32 _dim0, const PxArray<PxVec3> &vertices, const PxArray<PxI32> &indices)
{
first.clear();
tris.clear();
next.clear();
num1 = num2 = 0;
this->dim0 = _dim0;
PxI32 dim1 = (_dim0 + 1) % 3;
PxI32 dim2 = (_dim0 + 2) % 3;
PxI32 numTris = PxI32(indices.size()) / 3;
if (numTris == 0)
return;
PxBounds3 bounds, triBounds;
bounds.setEmpty();
PxReal avgSize = 0.0f;
for (PxI32 i = 0; i < numTris; i++)
{
triBounds.setEmpty();
triBounds.include(vertices[indices[3 * i]]);
triBounds.include(vertices[indices[3 * i + 1]]);
triBounds.include(vertices[indices[3 * i + 2]]);
triBounds.minimum[dim0] = 0.0f;
triBounds.maximum[dim0] = 0.0f;
avgSize += triBounds.getDimensions().magnitude();
bounds.include(triBounds);
}
if (bounds.isEmpty())
return;
avgSize /= PxReal(numTris);
orig = bounds.minimum;
spacing = avgSize;
num1 = PxI32((bounds.maximum[dim1] - orig[dim1]) / spacing) + 2;
num2 = PxI32((bounds.maximum[dim2] - orig[dim2]) / spacing) + 2;
first.clear();
first.resize(num1 * num2, -1);
for (PxI32 i = 0; i < numTris; i++)
{
triBounds.setEmpty();
triBounds.include(vertices[indices[3 * i]] - orig);
triBounds.include(vertices[indices[3 * i + 1]] - orig);
triBounds.include(vertices[indices[3 * i + 2]] - orig);
PxI32 min1 = PxI32(triBounds.minimum[dim1] / spacing);
PxI32 min2 = PxI32(triBounds.minimum[dim2] / spacing);
PxI32 max1 = PxI32(triBounds.maximum[dim1] / spacing);
PxI32 max2 = PxI32(triBounds.maximum[dim2] / spacing);
for (PxI32 i1 = min1; i1 <= max1; i1++)
{
for (PxI32 i2 = min2; i2 <= max2; i2++)
{
PxI32 nr = i1 * num2 + i2;
next.pushBack(first[nr]);
first[nr] = PxI32(tris.size());
tris.pushBack(i);
}
}
}
}
// ------------------------------------------------------------------------
PxI32 InsideTester::Grid2d::numInside(const PxVec3 &pos, const PxArray<PxVec3> &vertices, const PxArray<PxI32> &indices)
{
if (first.empty())
return 0;
PxI32 dim1 = (dim0 + 1) % 3;
PxI32 dim2 = (dim0 + 2) % 3;
PxReal r = 1e-5f;
PxVec3 p = pos;
p[dim1] = pos[dim1] + rnd.rand(0.0f, r);
p[dim2] = pos[dim2] + rnd.rand(0.0f, r);
PxI32 i1 = PxI32((p[dim1] - orig[dim1]) / spacing);
PxI32 i2 = PxI32((p[dim2] - orig[dim2]) / spacing);
if (i1 < 0 || i1 >= num1 || i2 < 0 || i2 >= num2)
return false;
PxI32 count1 = 0;
PxI32 count2 = 0;
PxI32 nr = first[i1 * num2 + i2];
while (nr >= 0)
{
PxI32 triNr = tris[nr];
nr = next[nr];
const PxVec3 &p0 = vertices[indices[3 * triNr]];
const PxVec3 &p1 = vertices[indices[3 * triNr + 1]];
const PxVec3 &p2 = vertices[indices[3 * triNr + 2]];
bool side0 = (p1 - p0).cross(p - p0)[dim0] > 0.0f;
bool side1 = (p2 - p1).cross(p - p1)[dim0] > 0.0f;
bool side2 = (p0 - p2).cross(p - p2)[dim0] > 0.0f;
if (side0 != side1 || side1 != side2)
continue;
// ray triangle intersection
PxVec3 n = (p1 - p0).cross(p2 - p0);
if (n[dim0] == 0.0f)
continue;
PxReal t = (p0 - p).dot(n) / n[dim0];
if (t > 0.0f)
count1++;
else if (t < 0.0f)
count2++;
}
PxI32 num = 0;
if ((count1 % 2) == 1)
num++;
if ((count2 % 2) == 1)
num++;
return num;
}
}
}
| 6,128 | C++ | 30.111675 | 122 | 0.601012 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/omnipvd/ExtOmniPvdRegistrationData.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 "ExtOmniPvdRegistrationData.h"
#if PX_SUPPORT_OMNI_PVD
namespace physx
{
namespace Ext
{
void OmniPvdPxExtensionsRegistrationData::registerData(OmniPvdWriter& writer)
{
// auto-generate class/attribute registration code from object definition file
#define OMNI_PVD_WRITER_VAR writer
#include "omnipvd/CmOmniPvdAutoGenRegisterData.h"
#include "OmniPvdPxExtensionsTypes.h"
#include "omnipvd/CmOmniPvdAutoGenClearDefines.h"
#undef OMNI_PVD_WRITER_VAR
}
}
}
#endif
| 2,176 | C++ | 39.314814 | 79 | 0.775276 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/omnipvd/OmniPvdPxExtensionsSampler.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA 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_EXTENSION_SAMPLER_H
#define OMNI_PVD_EXTENSION_SAMPLER_H
#if PX_SUPPORT_OMNI_PVD
#include "foundation/PxUserAllocated.h"
#include "ExtOmniPvdRegistrationData.h"
namespace physx
{
class PxOmniPvd;
}
class OmniPvdPxExtensionsSampler : public physx::PxUserAllocated
{
public:
OmniPvdPxExtensionsSampler();
~OmniPvdPxExtensionsSampler();
void setOmniPvdInstance(physx::PxOmniPvd* omniPvdInstance);
physx::PxOmniPvd* getOmniPvdInstance();
void registerClasses();
const physx::Ext::OmniPvdPxExtensionsRegistrationData& getRegistrationData() const { return mRegistrationData; }
// OmniPvdPxExtensionsSampler singleton
static bool createInstance();
static OmniPvdPxExtensionsSampler* getInstance();
static void destroyInstance();
private:
physx::PxOmniPvd* mOmniPvdInstance;
physx::Ext::OmniPvdPxExtensionsRegistrationData mRegistrationData;
};
namespace physx
{
namespace Ext
{
const OmniPvdPxExtensionsRegistrationData* OmniPvdGetPxExtensionsRegistrationData();
PxOmniPvd* OmniPvdGetInstance();
}
}
#endif
#endif
| 2,750 | C | 33.3875 | 113 | 0.782182 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/omnipvd/ExtOmniPvdSetData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_OMNI_PVD_SET_DATA_H
#define EXT_OMNI_PVD_SET_DATA_H
//
// This header has to be included to use macros like OMNI_PVD_SET() (set attribute values,
// object instance registration etc.)
//
#define OMNI_PVD_CONTEXT_HANDLE 1
#if PX_SUPPORT_OMNI_PVD
#include "OmniPvdPxExtensionsSampler.h"
#include "omnipvd/PxOmniPvd.h"
//
// Define the macros needed in CmOmniPvdAutoGenSetData.h
//
#undef OMNI_PVD_GET_WRITER
#define OMNI_PVD_GET_WRITER(writer) \
physx::PxOmniPvd::ScopedExclusiveWriter writeLock(physx::Ext::OmniPvdGetInstance()); \
OmniPvdWriter* writer = writeLock.getWriter();
#undef OMNI_PVD_GET_REGISTRATION_DATA
#define OMNI_PVD_GET_REGISTRATION_DATA(registrationData) \
const OmniPvdPxExtensionsRegistrationData* registrationData = physx::Ext::OmniPvdGetPxExtensionsRegistrationData();
#endif // PX_SUPPORT_OMNI_PVD
#include "omnipvd/CmOmniPvdAutoGenSetData.h"
// note: included in all cases since it will provide empty definitions of the helper macros such
// that not all of them have to be guarded by PX_SUPPORT_OMNI_PVD
#endif // EXT_OMNI_PVD_SET_DATA_H
| 2,796 | C | 39.536231 | 115 | 0.765737 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/omnipvd/OmniPvdPxExtensionsSampler.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 "OmniPvdPxExtensionsSampler.h"
#include "omnipvd/PxOmniPvd.h"
using namespace physx;
void OmniPvdPxExtensionsSampler::registerClasses()
{
PxOmniPvd::ScopedExclusiveWriter scope(mOmniPvdInstance);
OmniPvdWriter* writer = scope.getWriter();
if (writer)
{
mRegistrationData.registerData(*mOmniPvdInstance->getWriter());
}
}
OmniPvdPxExtensionsSampler::OmniPvdPxExtensionsSampler()
{
mOmniPvdInstance = NULL;
}
OmniPvdPxExtensionsSampler::~OmniPvdPxExtensionsSampler()
{
}
void OmniPvdPxExtensionsSampler::setOmniPvdInstance(physx::PxOmniPvd* omniPvdInstance)
{
mOmniPvdInstance = omniPvdInstance;
}
physx::PxOmniPvd* OmniPvdPxExtensionsSampler::getOmniPvdInstance() {
return mOmniPvdInstance;
}
///////////////////////////////////////////////////////////////////////////////
static OmniPvdPxExtensionsSampler* gOmniPvdPxExtensionsSampler = NULL;
bool OmniPvdPxExtensionsSampler::createInstance()
{
gOmniPvdPxExtensionsSampler = PX_NEW(OmniPvdPxExtensionsSampler)();
return gOmniPvdPxExtensionsSampler != NULL;
}
OmniPvdPxExtensionsSampler* OmniPvdPxExtensionsSampler::getInstance()
{
return gOmniPvdPxExtensionsSampler;
}
void OmniPvdPxExtensionsSampler::destroyInstance()
{
PX_DELETE(gOmniPvdPxExtensionsSampler);
}
namespace physx
{
namespace Ext
{
const OmniPvdPxExtensionsRegistrationData* OmniPvdGetPxExtensionsRegistrationData()
{
OmniPvdPxExtensionsSampler* sampler = OmniPvdPxExtensionsSampler::getInstance();
if (sampler)
{
return &sampler->getRegistrationData();
}
else
{
return NULL;
}
}
PxOmniPvd* OmniPvdGetInstance()
{
OmniPvdPxExtensionsSampler* sampler = OmniPvdPxExtensionsSampler::getInstance();
if (sampler)
{
return sampler->getOmniPvdInstance();
}
else
{
return NULL;
}
}
}
}
#endif
| 3,490 | C++ | 27.153226 | 86 | 0.762751 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/omnipvd/ExtOmniPvdRegistrationData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef EXT_OMNI_PVD_REGISTRATION_DATA_H
#define EXT_OMNI_PVD_REGISTRATION_DATA_H
#if PX_SUPPORT_OMNI_PVD
#include "../pvdruntime/include/OmniPvdWriter.h"
#include "extensions/PxD6Joint.h" // for PxD6Motion
#include "extensions/PxDistanceJoint.h" // for PxDistanceJointFlags
#include "extensions/PxPrismaticJoint.h" // for PxPrismaticJointFlags
#include "extensions/PxRevoluteJoint.h" // for PxRevoluteJointFlags
#include "extensions/PxSphericalJoint.h" // for PxSphericalJointFlags
#include "extensions/PxCustomGeometryExt.h" // for PxCustomGeometryExtBaseConvexCallbacks etc.
namespace physx
{
class PxContactJoint;
class PxFixedJoint;
class PxGearJoint;
class PxRackAndPinionJoint;
namespace Ext
{
struct OmniPvdPxExtensionsRegistrationData
{
void registerData(OmniPvdWriter&);
// auto-generate members and setter methods from object definition file
#include "omnipvd/CmOmniPvdAutoGenCreateRegistrationStruct.h"
#include "OmniPvdPxExtensionsTypes.h"
#include "omnipvd/CmOmniPvdAutoGenClearDefines.h"
};
}
}
#endif // PX_SUPPORT_OMNI_PVD
#endif // EXT_OMNI_PVD_REGISTRATION_DATA_H
| 2,806 | C | 36.932432 | 95 | 0.779401 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/omnipvd/OmniPvdPxExtensionsTypes.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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!
////////////////////////////////////////////////////////////////////////////////
// Enums
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_ENUM_BEGIN (PxConstraintFlag)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eBROKEN)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eCOLLISION_ENABLED)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eVISUALIZATION)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eDRIVE_LIMITS_ARE_FORCES)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eIMPROVED_SLERP)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eDISABLE_PREPROCESSING)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eENABLE_EXTENDED_LIMITS)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eGPU_COMPATIBLE)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eALWAYS_UPDATE)
OMNI_PVD_ENUM_VALUE (PxConstraintFlag, eDISABLE_CONSTRAINT)
OMNI_PVD_ENUM_END (PxConstraintFlag)
OMNI_PVD_ENUM_BEGIN (PxRevoluteJointFlag)
OMNI_PVD_ENUM_VALUE (PxRevoluteJointFlag, eLIMIT_ENABLED)
OMNI_PVD_ENUM_VALUE (PxRevoluteJointFlag, eDRIVE_ENABLED)
OMNI_PVD_ENUM_VALUE (PxRevoluteJointFlag, eDRIVE_FREESPIN)
OMNI_PVD_ENUM_END (PxRevoluteJointFlag)
OMNI_PVD_ENUM_BEGIN (PxPrismaticJointFlag)
OMNI_PVD_ENUM_VALUE (PxPrismaticJointFlag, eLIMIT_ENABLED)
OMNI_PVD_ENUM_END (PxPrismaticJointFlag)
OMNI_PVD_ENUM_BEGIN (PxDistanceJointFlag)
OMNI_PVD_ENUM_VALUE (PxDistanceJointFlag, eMAX_DISTANCE_ENABLED)
OMNI_PVD_ENUM_VALUE (PxDistanceJointFlag, eMIN_DISTANCE_ENABLED)
OMNI_PVD_ENUM_VALUE (PxDistanceJointFlag, eSPRING_ENABLED)
OMNI_PVD_ENUM_END (PxDistanceJointFlag)
OMNI_PVD_ENUM_BEGIN (PxSphericalJointFlag)
OMNI_PVD_ENUM_VALUE (PxSphericalJointFlag, eLIMIT_ENABLED)
OMNI_PVD_ENUM_END (PxSphericalJointFlag)
OMNI_PVD_ENUM_BEGIN (PxD6JointDriveFlag)
OMNI_PVD_ENUM_VALUE (PxD6JointDriveFlag, eACCELERATION)
OMNI_PVD_ENUM_END (PxD6JointDriveFlag)
OMNI_PVD_ENUM_BEGIN (PxJointConcreteType)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eSPHERICAL)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eREVOLUTE)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, ePRISMATIC)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eFIXED)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eDISTANCE)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eD6)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eCONTACT)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eGEAR)
OMNI_PVD_ENUM_VALUE (PxJointConcreteType, eRACK_AND_PINION)
OMNI_PVD_ENUM_END (PxJointConcreteType)
OMNI_PVD_ENUM_BEGIN (PxD6Motion)
OMNI_PVD_ENUM_VALUE (PxD6Motion, eLOCKED)
OMNI_PVD_ENUM_VALUE (PxD6Motion, eLIMITED)
OMNI_PVD_ENUM_VALUE (PxD6Motion, eFREE)
OMNI_PVD_ENUM_END (PxD6Motion)
////////////////////////////////////////////////////////////////////////////////
// Classes
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// PxJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_BEGIN (PxJoint)
OMNI_PVD_ATTRIBUTE_FLAG (PxJoint, type, PxJointConcreteType::Enum, PxJointConcreteType)
OMNI_PVD_ATTRIBUTE (PxJoint, actor0, PxRigidActor* const, OmniPvdDataType::eOBJECT_HANDLE)
OMNI_PVD_ATTRIBUTE (PxJoint, actor1, PxRigidActor* const, OmniPvdDataType::eOBJECT_HANDLE)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxJoint, actor0LocalPose, PxTransform, OmniPvdDataType::eFLOAT32, 7)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxJoint, actor1LocalPose, PxTransform, OmniPvdDataType::eFLOAT32, 7)
OMNI_PVD_ATTRIBUTE (PxJoint, breakForce, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxJoint, breakTorque, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_FLAG (PxJoint, constraintFlags, PxConstraintFlags, PxConstraintFlag)
OMNI_PVD_ATTRIBUTE (PxJoint, invMassScale0, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxJoint, invInertiaScale0, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxJoint, invMassScale1, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxJoint, invInertiaScale1, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_STRING (PxJoint, name)
OMNI_PVD_ATTRIBUTE_STRING (PxJoint, concreteTypeName)
OMNI_PVD_CLASS_END (PxJoint)
////////////////////////////////////////////////////////////////////////////////
// PxFixedJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxFixedJoint, PxJoint)
OMNI_PVD_CLASS_END (PxFixedJoint)
////////////////////////////////////////////////////////////////////////////////
// PxPrismaticJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxPrismaticJoint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, position, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, velocity, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, limitLower, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, limitUpper, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, limitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, limitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, limitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxPrismaticJoint, limitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_FLAG (PxPrismaticJoint, jointFlags, PxPrismaticJointFlags, PxPrismaticJointFlag)
OMNI_PVD_CLASS_END (PxPrismaticJoint)
////////////////////////////////////////////////////////////////////////////////
// PxRevoluteJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxRevoluteJoint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, angle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, velocity, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, limitLower, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, limitUpper, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, limitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, limitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, limitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, limitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, driveVelocity, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, driveForceLimit, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxRevoluteJoint, driveGearRatio, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_FLAG (PxRevoluteJoint, jointFlags, PxRevoluteJointFlags, PxRevoluteJointFlag)
OMNI_PVD_CLASS_END (PxRevoluteJoint)
////////////////////////////////////////////////////////////////////////////////
// PxSphericalJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxSphericalJoint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, swingYAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, swingZAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, limitYAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, limitZAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, limitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, limitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, limitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxSphericalJoint, limitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_FLAG (PxSphericalJoint, jointFlags, PxSphericalJointFlags, PxSphericalJointFlag)
OMNI_PVD_CLASS_END (PxSphericalJoint)
////////////////////////////////////////////////////////////////////////////////
// PxDistanceJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxDistanceJoint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxDistanceJoint, distance, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxDistanceJoint, minDistance, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxDistanceJoint, maxDistance, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxDistanceJoint, tolerance, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxDistanceJoint, stiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxDistanceJoint, damping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_FLAG (PxDistanceJoint, jointFlags, PxDistanceJointFlags, PxDistanceJointFlag)
OMNI_PVD_CLASS_END (PxDistanceJoint)
////////////////////////////////////////////////////////////////////////////////
// PxContactJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxContactJoint, PxJoint)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxContactJoint, point, PxVec3, OmniPvdDataType::eFLOAT32, 3)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxContactJoint, normal, PxVec3, OmniPvdDataType::eFLOAT32, 3)
OMNI_PVD_ATTRIBUTE (PxContactJoint, penetration, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxContactJoint, restitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxContactJoint, bounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_CLASS_END (PxContactJoint)
////////////////////////////////////////////////////////////////////////////////
// PxGearJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxGearJoint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxGearJoint, ratio, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxGearJoint, hinges, PxBase* const, OmniPvdDataType::eOBJECT_HANDLE)
OMNI_PVD_CLASS_END (PxGearJoint)
////////////////////////////////////////////////////////////////////////////////
// PxRackAndPinionJoint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxRackAndPinionJoint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxRackAndPinionJoint, ratio, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxRackAndPinionJoint, joints, PxBase* const, OmniPvdDataType::eOBJECT_HANDLE)
OMNI_PVD_CLASS_END (PxRackAndPinionJoint)
////////////////////////////////////////////////////////////////////////////////
// PxD6Joint
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxD6Joint, PxJoint)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingYAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingZAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, motions, PxD6Motion::Enum, OmniPvdDataType::eUINT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, distanceLimitValue, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, distanceLimitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, distanceLimitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, distanceLimitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, distanceLimitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, linearLimitLower, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, linearLimitUpper, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, linearLimitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, linearLimitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, linearLimitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, linearLimitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistLimitLower, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistLimitUpper, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistLimitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistLimitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistLimitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, twistLimitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingLimitYAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingLimitZAngle, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingLimitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingLimitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingLimitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, swingLimitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitYAngleMin, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitYAngleMax, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitZAngleMin, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitZAngleMax, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitRestitution, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitBounceThreshold, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxD6Joint, pyramidSwingLimitDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, driveForceLimit, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, driveFlags, PxD6JointDriveFlags, OmniPvdDataType::eUINT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, driveStiffness, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_VARIABLE_SIZE (PxD6Joint, driveDamping, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxD6Joint, drivePosition, PxTransform, OmniPvdDataType::eFLOAT32, 7)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxD6Joint, driveLinVelocity, PxVec3, OmniPvdDataType::eFLOAT32, 3)
OMNI_PVD_ATTRIBUTE_ARRAY_FIXED_SIZE (PxD6Joint, driveAngVelocity, PxVec3, OmniPvdDataType::eFLOAT32, 3)
OMNI_PVD_CLASS_END (PxD6Joint)
////////////////////////////////////////////////////////////////////////////////
// PxCustomGeometryExt::BaseConvexCallbacks
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_BEGIN (PxCustomGeometryExtBaseConvexCallbacks)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtBaseConvexCallbacks, margin, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_CLASS_END (PxCustomGeometryExtBaseConvexCallbacks)
////////////////////////////////////////////////////////////////////////////////
// PxCustomGeometryExt::CylinderCallbacks
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxCustomGeometryExtCylinderCallbacks, PxCustomGeometryExtBaseConvexCallbacks)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtCylinderCallbacks, height, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtCylinderCallbacks, radius, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtCylinderCallbacks, axis, PxI32, OmniPvdDataType::eINT32)
OMNI_PVD_CLASS_END (PxCustomGeometryExtCylinderCallbacks)
////////////////////////////////////////////////////////////////////////////////
// PxCustomGeometryExt::ConeCallbacks
////////////////////////////////////////////////////////////////////////////////
OMNI_PVD_CLASS_DERIVED_BEGIN (PxCustomGeometryExtConeCallbacks, PxCustomGeometryExtBaseConvexCallbacks)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtConeCallbacks, height, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtConeCallbacks, radius, PxReal, OmniPvdDataType::eFLOAT32)
OMNI_PVD_ATTRIBUTE (PxCustomGeometryExtConeCallbacks, axis, PxI32, OmniPvdDataType::eINT32)
OMNI_PVD_CLASS_END (PxCustomGeometryExtConeCallbacks)
| 19,108 | C | 66.522968 | 117 | 0.686205 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/SnSerializationRegistry.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_SERIALIZATION_REGISTRY_H
#define SN_SERIALIZATION_REGISTRY_H
#include "extensions/PxSerialization.h"
#include "extensions/PxRepXSerializer.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxArray.h"
namespace physx
{
namespace Cm { class Collection; }
namespace Sn {
class SerializationRegistry : public PxSerializationRegistry, public PxUserAllocated
{
public:
SerializationRegistry(PxPhysics& physics);
virtual ~SerializationRegistry();
virtual void release(){ PX_DELETE_THIS; }
PxPhysics& getPhysics() const { return mPhysics; }
//binary
void registerSerializer(PxType type, PxSerializer& serializer);
PxSerializer* unregisterSerializer(PxType type);
void registerBinaryMetaDataCallback(PxBinaryMetaDataCallback callback);
void getBinaryMetaData(PxOutputStream& stream) const;
const PxSerializer* getSerializer(PxType type) const;
const char* getSerializerName(PxU32 index) const;
PxType getSerializerType(PxU32 index) const;
PxU32 getNbSerializers() const { return mSerializers.size(); }
//repx
void registerRepXSerializer(PxType type, PxRepXSerializer& serializer);
PxRepXSerializer* getRepXSerializer(const char* typeName) const;
PxRepXSerializer* unregisterRepXSerializer(PxType type);
protected:
SerializationRegistry &operator=(const SerializationRegistry &);
private:
typedef PxCoalescedHashMap<PxType, PxSerializer*> SerializerMap;
typedef PxHashMap<PxType, PxRepXSerializer*> RepXSerializerMap;
PxPhysics& mPhysics;
SerializerMap mSerializers;
RepXSerializerMap mRepXSerializers;
PxArray<PxBinaryMetaDataCallback> mMetaDataCallbacks;
};
void sortCollection(Cm::Collection& collection, SerializationRegistry& sr, bool isRepx);
} // Sn
} // physx
#endif
| 3,669 | C | 38.891304 | 91 | 0.743254 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/SnSerialUtils.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 "extensions/PxSerialization.h"
#include "foundation/PxPhysicsVersion.h"
#include "SnSerialUtils.h"
#include "foundation/PxString.h"
#include "foundation/PxBasicTemplates.h"
using namespace physx;
namespace
{
#define SN_NUM_BINARY_PLATFORMS 9
const PxU32 sBinaryPlatformTags[SN_NUM_BINARY_PLATFORMS] =
{
PX_MAKE_FOURCC('W','_','3','2'),
PX_MAKE_FOURCC('W','_','6','4'),
PX_MAKE_FOURCC('L','_','3','2'),
PX_MAKE_FOURCC('L','_','6','4'),
PX_MAKE_FOURCC('M','_','3','2'),
PX_MAKE_FOURCC('M','_','6','4'),
PX_MAKE_FOURCC('N','X','3','2'),
PX_MAKE_FOURCC('N','X','6','4'),
PX_MAKE_FOURCC('L','A','6','4')
};
const char* sBinaryPlatformNames[SN_NUM_BINARY_PLATFORMS] =
{
"win32",
"win64",
"linux32",
"linux64",
"mac32",
"mac64",
"switch32",
"switch64",
"linuxaarch64"
};
}
namespace physx { namespace Sn {
PxU32 getBinaryPlatformTag()
{
#if PX_WINDOWS && PX_X86
return sBinaryPlatformTags[0];
#elif PX_WINDOWS && PX_X64
return sBinaryPlatformTags[1];
#elif PX_LINUX && PX_X86
return sBinaryPlatformTags[2];
#elif PX_LINUX && PX_X64
return sBinaryPlatformTags[3];
#elif PX_OSX && PX_X86
return sBinaryPlatformTags[4];
#elif PX_OSX && PX_X64
return sBinaryPlatformTags[5];
#elif PX_SWITCH && !PX_A64
return sBinaryPlatformTags[6];
#elif PX_SWITCH && PX_A64
return sBinaryPlatformTags[7];
#elif PX_LINUX && PX_A64
return sBinaryPlatformTags[8];
#else
#error Unknown binary platform
#endif
}
bool isBinaryPlatformTagValid(physx::PxU32 platformTag)
{
PxU32 platformIndex = 0;
while (platformIndex < SN_NUM_BINARY_PLATFORMS && platformTag != sBinaryPlatformTags[platformIndex]) platformIndex++;
return platformIndex < SN_NUM_BINARY_PLATFORMS;
}
const char* getBinaryPlatformName(physx::PxU32 platformTag)
{
PxU32 platformIndex = 0;
while (platformIndex < SN_NUM_BINARY_PLATFORMS && platformTag != sBinaryPlatformTags[platformIndex]) platformIndex++;
return (platformIndex == SN_NUM_BINARY_PLATFORMS) ? "unknown" : sBinaryPlatformNames[platformIndex];
}
const char* getBinaryVersionGuid()
{
PX_COMPILE_TIME_ASSERT(sizeof(PX_BINARY_SERIAL_VERSION) == SN_BINARY_VERSION_GUID_NUM_CHARS + 1);
return PX_BINARY_SERIAL_VERSION;
}
bool checkCompatibility(const char* binaryVersionGuidCandidate)
{
for(PxU32 i=0; i<SN_BINARY_VERSION_GUID_NUM_CHARS; i++)
{
if (binaryVersionGuidCandidate[i] != PX_BINARY_SERIAL_VERSION[i])
{
return false;
}
}
return true;
}
} // Sn
} // physx
| 4,124 | C++ | 30.25 | 118 | 0.730844 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/SnSerializationRegistry.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/PxSerializer.h"
#include "foundation/PxString.h"
#include "PxPhysics.h"
#include "PxPhysicsSerialization.h"
#include "PxArticulationLink.h"
#include "SnSerializationRegistry.h"
#include "ExtSerialization.h"
#include "CmCollection.h"
using namespace physx;
namespace
{
class CollectionSorter : public PxProcessPxBaseCallback
{
typedef PxPair<PxBase*, PxSerialObjectId> Object;
class Element
{
public:
Object object;
PxArray<PxU32> children;
bool isFinished;
Element(PxBase* obj = NULL) : object(obj, PX_SERIAL_OBJECT_ID_INVALID), isFinished(false) {}
};
public:
CollectionSorter(Cm::Collection& collection, Sn::SerializationRegistry& sr, bool isRepx) : mCollection(collection), mSr(sr), mIsRepx(isRepx) {}
virtual ~CollectionSorter(){}
void process(PxBase& base)
{
addChild(&base);
//ArticulationLink is not a repx serializer, so should require Articulation here
if( mIsRepx && PxConcreteType::eARTICULATION_LINK == base.getConcreteType() )
{
PxArticulationLink* link = static_cast<PxArticulationLink*>(&base);
PxBase* a = reinterpret_cast<PxBase*>(&link->getArticulation());
if(mCurElement->object.first != a ) //don't require itself
addChild(a);
}
}
void sort()
{
Element element;
PxU32 i;
PxU32 nbObject = mCollection.internalGetNbObjects();
const Cm::Collection::ObjectToIdMap::Entry* objectdatas = mCollection.internalGetObjects();
for( i = 0; i < nbObject; ++i )
{
element.object.first = objectdatas[i].first;
element.object.second = objectdatas[i].second;
mObjToIdMap.insert(objectdatas[i].first, mElements.size());
mElements.pushBack(element);
}
for( i = 0; i < nbObject; ++i )
{
mCurElement = &mElements[i];
const PxSerializer* serializer = mSr.getSerializer(mCurElement->object.first->getConcreteType());
PX_ASSERT(serializer);
serializer->requiresObjects(*mCurElement->object.first, *this);
}
for( i = 0; i < nbObject; ++i )
{
if( mElements[i].isFinished )
continue;
AddElement(mElements[i]);
}
mCollection.mObjects.clear();
for(PxArray<Object>::Iterator o = mSorted.begin(); o != mSorted.end(); ++o )
{
mCollection.internalAdd(o->first, o->second);
}
}
void AddElement(Element& e)
{
if( !e.isFinished )
{
for( PxArray<PxU32>::Iterator child = e.children.begin(); child != e.children.end(); ++child )
{
AddElement(mElements[*child]);
}
mSorted.pushBack(e.object);
e.isFinished = true;
}
}
private:
PX_INLINE void addChild(PxBase* base)
{
PX_ASSERT(mCurElement);
const PxHashMap<PxBase*, PxU32>::Entry* entry = mObjToIdMap.find(base);
if(entry)
mCurElement->children.pushBack(entry->second);
}
CollectionSorter& operator=(const CollectionSorter&);
PxHashMap<PxBase*, PxU32> mObjToIdMap;
PxArray<Element> mElements;
Cm::Collection& mCollection;
Sn::SerializationRegistry& mSr;
PxArray<Object> mSorted;
Element* mCurElement;
bool mIsRepx;
};
}
namespace physx { namespace Sn {
SerializationRegistry::SerializationRegistry(PxPhysics& physics)
: mPhysics(physics)
{
PxRegisterPhysicsSerializers(*this);
Ext::RegisterExtensionsSerializers(*this);
registerBinaryMetaDataCallback(PxGetPhysicsBinaryMetaData);
registerBinaryMetaDataCallback(Ext::GetExtensionsBinaryMetaData);
}
SerializationRegistry::~SerializationRegistry()
{
PxUnregisterPhysicsSerializers(*this);
Ext::UnregisterExtensionsSerializers(*this);
if(mSerializers.size() > 0)
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::release(): some registered PxSerializer instances were not unregistered");
}
if(mRepXSerializers.size() > 0)
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::release(): some registered PxRepXSerializer instances were not unregistered");
}
}
void SerializationRegistry::registerSerializer(PxType type, PxSerializer& serializer)
{
if(mSerializers.find(type))
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::registerSerializer: Type %d has already been registered", type);
}
mSerializers.insert(type, &serializer);
}
PxSerializer* SerializationRegistry::unregisterSerializer(PxType type)
{
const SerializerMap::Entry* e = mSerializers.find(type);
PxSerializer* s = e ? e->second : NULL;
if(!mSerializers.erase(type))
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::unregisterSerializer: failed to find PxSerializer instance for type %d", type);
}
return s;
}
const PxSerializer* SerializationRegistry::getSerializer(PxType type) const
{
const SerializerMap::Entry* e = mSerializers.find(type);
#if PX_CHECKED
if (!e)
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::getSerializer: failed to find PxSerializer instance for type %d", type);
}
#endif
return e ? e->second : NULL;
}
PxType SerializationRegistry::getSerializerType(PxU32 index) const
{
PX_ASSERT(index < mSerializers.size());
return mSerializers.getEntries()[index].first;
}
const char* SerializationRegistry::getSerializerName(PxU32 index) const
{
PX_ASSERT(index < mSerializers.size());
return mSerializers.getEntries()[index].second->getConcreteTypeName();
}
void SerializationRegistry::registerBinaryMetaDataCallback(PxBinaryMetaDataCallback callback)
{
mMetaDataCallbacks.pushBack(callback);
}
void SerializationRegistry::getBinaryMetaData(PxOutputStream& stream) const
{
for(PxU32 i = 0; i < mMetaDataCallbacks.size(); i++)
{
mMetaDataCallbacks[i](stream);
}
}
void SerializationRegistry::registerRepXSerializer(PxType type, PxRepXSerializer& serializer)
{
if(mRepXSerializers.find(type))
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::registerRepXSerializer: Type %d has already been registered", type);
}
mRepXSerializers.insert(type, &serializer);
}
PxRepXSerializer* SerializationRegistry::getRepXSerializer(const char* typeName) const
{
SerializationRegistry* sr = const_cast<SerializationRegistry*>(this);
for( RepXSerializerMap::Iterator iter = sr->mRepXSerializers.getIterator(); !iter.done(); ++iter)
{
if ( physx::Pxstricmp( iter->second->getTypeName(), typeName ) == 0 )
return iter->second;
}
return NULL;
}
PxRepXSerializer* SerializationRegistry::unregisterRepXSerializer(PxType type)
{
const RepXSerializerMap::Entry* e = mRepXSerializers.find(type);
PxRepXSerializer* s = e ? e->second : NULL;
if(!mRepXSerializers.erase(type))
{
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL,
"PxSerializationRegistry::unregisterRepXSerializer: failed to find PxRepXSerializer instance for type %d", type);
}
return s;
}
void sortCollection(Cm::Collection& collection, SerializationRegistry& sr, bool isRepx)
{
CollectionSorter sorter(collection, sr, isRepx);
sorter.sort();
}
} // Sn
PxSerializationRegistry* PxSerialization::createSerializationRegistry(PxPhysics& physics)
{
return PX_NEW(Sn::SerializationRegistry)(physics);
}
} // physx
| 9,026 | C++ | 30.452962 | 145 | 0.730556 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/SnSerialization.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/PxMetaData.h"
#include "common/PxSerializer.h"
#include "extensions/PxConstraintExt.h"
#include "foundation/PxPhysicsVersion.h"
#include "PxPhysicsAPI.h"
#include "SnConvX.h"
#include "SnSerializationRegistry.h"
#include "SnSerialUtils.h"
#include "ExtSerialization.h"
#include "CmCollection.h"
using namespace physx;
using namespace Sn;
namespace
{
struct RequiresCallback : public PxProcessPxBaseCallback
{
RequiresCallback(physx::PxCollection& c) : collection(c) {}
void process(PxBase& base)
{
if(!collection.contains(base))
collection.add(base);
}
PxCollection& collection;
PX_NOCOPY(RequiresCallback)
};
struct CompleteCallback : public PxProcessPxBaseCallback
{
CompleteCallback(physx::PxCollection& r, physx::PxCollection& c, const physx::PxCollection* e) :
required(r), complete(c), external(e) {}
void process(PxBase& base)
{
if(complete.contains(base) || (external && external->contains(base)))
return;
if(!required.contains(base))
required.add(base);
}
PxCollection& required;
PxCollection& complete;
const PxCollection* external;
PX_NOCOPY(CompleteCallback)
};
void getRequiresCollection(PxCollection& required, PxCollection& collection, PxCollection& complete, const PxCollection* external, PxSerializationRegistry& sr, bool followJoints)
{
CompleteCallback callback(required, complete, external);
for (PxU32 i = 0; i < collection.getNbObjects(); ++i)
{
PxBase& s = collection.getObject(i);
const PxSerializer* serializer = sr.getSerializer(s.getConcreteType());
PX_ASSERT(serializer);
serializer->requiresObjects(s, callback);
if(followJoints)
{
PxRigidActor* actor = s.is<PxRigidActor>();
if(actor)
{
PxArray<PxConstraint*> objects(actor->getNbConstraints());
actor->getConstraints(objects.begin(), objects.size());
for(PxU32 j=0;j<objects.size();j++)
{
PxU32 typeId;
PxJoint* joint = reinterpret_cast<PxJoint*>(objects[j]->getExternalReference(typeId));
if(typeId == PxConstraintExtIDs::eJOINT)
{
const PxSerializer* sj = sr.getSerializer(joint->getConcreteType());
PX_ASSERT(sj);
sj->requiresObjects(*joint, callback);
if(!required.contains(*joint))
required.add(*joint);
}
}
}
}
}
}
}
bool PxSerialization::isSerializable(PxCollection& collection, PxSerializationRegistry& sr, const PxCollection* externalReferences)
{
PxCollection* subordinateCollection = PxCreateCollection();
PX_ASSERT(subordinateCollection);
for(PxU32 i = 0; i < collection.getNbObjects(); ++i)
{
PxBase& s = collection.getObject(i);
const PxSerializer* serializer = sr.getSerializer(s.getConcreteType());
PX_ASSERT(serializer);
if(serializer->isSubordinate())
subordinateCollection->add(s);
if(externalReferences)
{
PxSerialObjectId id = collection.getId(s);
if(id != PX_SERIAL_OBJECT_ID_INVALID)
{
PxBase* object = externalReferences->find(id);
if(object && (object != &s))
{
subordinateCollection->release();
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::isSerializable: Reference id %" PX_PRIu64 " used both in current collection and in externalReferences. "
"Please use unique identifiers.", id);
return false;
}
}
}
}
PxCollection* requiresCollection = PxCreateCollection();
PX_ASSERT(requiresCollection);
RequiresCallback requiresCallback0(*requiresCollection);
for (PxU32 i = 0; i < collection.getNbObjects(); ++i)
{
PxBase& s = collection.getObject(i);
const PxSerializer* serializer = sr.getSerializer(s.getConcreteType());
PX_ASSERT(serializer);
serializer->requiresObjects(s, requiresCallback0);
Cm::Collection* cmRequiresCollection = static_cast<Cm::Collection*>(requiresCollection);
for(PxU32 j = 0; j < cmRequiresCollection->getNbObjects(); ++j)
{
PxBase& s0 = cmRequiresCollection->getObject(j);
if(subordinateCollection->contains(s0))
{
subordinateCollection->remove(s0);
continue;
}
bool requiredIsInCollection = collection.contains(s0);
if(!requiredIsInCollection)
{
if(externalReferences)
{
if(!externalReferences->contains(s0))
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::isSerializable: Object of type %s references a missing object of type %s. "
"The missing object needs to be added to either the current collection or the externalReferences collection.",
s.getConcreteTypeName(), s0.getConcreteTypeName());
}
else if(externalReferences->getId(s0) == PX_SERIAL_OBJECT_ID_INVALID)
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::isSerializable: Object of type %s in externalReferences collection requires an id.",
s0.getConcreteTypeName());
}
else
continue;
}
else
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::isSerializable: Object of type %s references a missing serial object of type %s. "
"Please completed the collection or specify an externalReferences collection containing the object.",
s.getConcreteTypeName(), s0.getConcreteTypeName());
}
subordinateCollection->release();
requiresCollection->release();
return false;
}
}
cmRequiresCollection->mObjects.clear();
}
requiresCollection->release();
PxU32 numOrphans = subordinateCollection->getNbObjects();
for(PxU32 j = 0; j < numOrphans; ++j)
{
PxBase& subordinate = subordinateCollection->getObject(j);
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::isSerializable: An object of type %s is subordinate but not required "
"by other objects in the collection (orphan). Please remove the object from the collection or add its owner.",
subordinate.getConcreteTypeName());
}
subordinateCollection->release();
if(numOrphans>0)
return false;
if(externalReferences)
{
PxCollection* oppositeRequiresCollection = PxCreateCollection();
PX_ASSERT(oppositeRequiresCollection);
RequiresCallback requiresCallback(*oppositeRequiresCollection);
for (PxU32 i = 0; i < externalReferences->getNbObjects(); ++i)
{
PxBase& s = externalReferences->getObject(i);
const PxSerializer* serializer = sr.getSerializer(s.getConcreteType());
PX_ASSERT(serializer);
serializer->requiresObjects(s, requiresCallback);
Cm::Collection* cmCollection = static_cast<Cm::Collection*>(oppositeRequiresCollection);
for(PxU32 j = 0; j < cmCollection->getNbObjects(); ++j)
{
PxBase& s0 = cmCollection->getObject(j);
if(collection.contains(s0))
{
oppositeRequiresCollection->release();
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxSerialization::isSerializable: Object of type %s in externalReferences references an object "
"of type %s in collection (circular dependency).",
s.getConcreteTypeName(), s0.getConcreteTypeName());
return false;
}
}
cmCollection->mObjects.clear();
}
oppositeRequiresCollection->release();
}
return true;
}
void PxSerialization::complete(PxCollection& collection, PxSerializationRegistry& sr, const PxCollection* exceptFor, bool followJoints)
{
PxCollection* curCollection = PxCreateCollection();
PX_ASSERT(curCollection);
curCollection->add(collection);
PxCollection* requiresCollection = PxCreateCollection();
PX_ASSERT(requiresCollection);
do
{
getRequiresCollection(*requiresCollection, *curCollection, collection, exceptFor, sr, followJoints);
collection.add(*requiresCollection);
PxCollection* swap = curCollection;
curCollection = requiresCollection;
requiresCollection = swap;
(static_cast<Cm::Collection*>(requiresCollection))->mObjects.clear();
}while(curCollection->getNbObjects() > 0);
requiresCollection->release();
curCollection->release();
}
void PxSerialization::createSerialObjectIds(PxCollection& collection, const PxSerialObjectId base)
{
PxSerialObjectId localBase = base;
PxU32 nbObjects = collection.getNbObjects();
for (PxU32 i = 0; i < nbObjects; ++i)
{
while(collection.find(localBase))
{
localBase++;
}
PxBase& s = collection.getObject(i);
if(PX_SERIAL_OBJECT_ID_INVALID == collection.getId(s))
{
collection.addId(s, localBase);
localBase++;
}
}
}
namespace physx { namespace Sn
{
static PxU32 addToStringTable(physx::PxArray<char>& stringTable, const char* str)
{
if(!str)
return 0xffffffff;
PxI32 length = PxI32(stringTable.size());
const char* table = stringTable.begin();
const char* start = table;
while(length)
{
if(Pxstrcmp(table, str)==0)
return PxU32(table - start);
const char* saved = table;
while(*table++);
length -= PxU32(table - saved);
PX_ASSERT(length>=0);
}
const PxU32 offset = stringTable.size();
while(*str)
stringTable.pushBack(*str++);
stringTable.pushBack(0);
return offset;
}
} }
void PxSerialization::dumpBinaryMetaData(PxOutputStream& outputStream, PxSerializationRegistry& sr)
{
class MetaDataStream : public PxOutputStream
{
public:
bool addNewType(const char* typeName)
{
for(PxU32 i=0;i<types.size();i++)
{
if(Pxstrcmp(types[i], typeName)==0)
return false;
}
types.pushBack(typeName);
return true;
}
virtual PxU32 write(const void* src, PxU32 count)
{
PX_ASSERT(count==sizeof(PxMetaDataEntry));
const PxMetaDataEntry* entry = reinterpret_cast<const PxMetaDataEntry*>(src);
if(( entry->flags & PxMetaDataFlag::eTYPEDEF) || ((entry->flags & PxMetaDataFlag::eCLASS) && (!entry->name)) )
newType = addNewType(entry->type);
if(newType)
metaData.pushBack(*entry);
return count;
}
PxArray<PxMetaDataEntry> metaData;
PxArray<const char*> types;
bool newType;
}s;
SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr);
sn.getBinaryMetaData(s);
PxArray<char> stringTable;
PxU32 nb = s.metaData.size();
PxMetaDataEntry* entries = s.metaData.begin();
for(PxU32 i=0;i<nb;i++)
{
entries[i].type = reinterpret_cast<const char*>(size_t(addToStringTable(stringTable, entries[i].type)));
entries[i].name = reinterpret_cast<const char*>(size_t(addToStringTable(stringTable, entries[i].name)));
}
PxU32 platformTag = getBinaryPlatformTag();
const PxU32 gaussMapLimit = 32;
const PxU32 header = PX_MAKE_FOURCC('M','E','T','A');
const PxU32 version = PX_PHYSICS_VERSION;
const PxU32 ptrSize = sizeof(void*);
outputStream.write(&header, 4);
outputStream.write(&version, 4);
outputStream.write(PX_BINARY_SERIAL_VERSION, SN_BINARY_VERSION_GUID_NUM_CHARS);
outputStream.write(&ptrSize, 4);
outputStream.write(&platformTag, 4);
outputStream.write(&gaussMapLimit, 4);
outputStream.write(&nb, 4);
outputStream.write(entries, nb*sizeof(PxMetaDataEntry));
//concreteTypes to name
PxU32 num = sn.getNbSerializers();
outputStream.write(&num, 4);
for(PxU32 i=0; i<num; i++)
{
PxU16 type = sn.getSerializerType(i);
PxU32 nameOffset = addToStringTable(stringTable, sn.getSerializerName(i));
outputStream.write(&type, 2);
outputStream.write(&nameOffset, 4);
}
PxU32 length = stringTable.size();
const char* table = stringTable.begin();
outputStream.write(&length, 4);
outputStream.write(table, length);
}
PxBinaryConverter* PxSerialization::createBinaryConverter()
{
return PX_NEW(ConvX)();
}
| 13,344 | C++ | 30.849642 | 179 | 0.713504 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/SnSerialUtils.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_SERIAL_UTILS_H
#define SN_SERIAL_UTILS_H
#define SN_BINARY_VERSION_GUID_NUM_CHARS 32
namespace physx
{
namespace Sn
{
PxU32 getBinaryPlatformTag();
bool isBinaryPlatformTagValid(PxU32 platformTag);
const char* getBinaryPlatformName(PxU32 platformTag);
const char* getBinaryVersionGuid();
bool checkCompatibility(const char* binaryVersionGuidCandidate);
}
}
#endif
| 2,083 | C | 41.530611 | 74 | 0.771483 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Output.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/PxIO.h"
#include "foundation/PxErrorCallback.h"
#include "SnConvX.h"
#if PX_VC
#pragma warning(disable:4389) // signed/unsigned mismatch
#endif
using namespace physx;
void Sn::ConvX::setNullPtr(bool flag)
{
mNullPtr = flag;
}
void Sn::ConvX::setNoOutput(bool flag)
{
mNoOutput = flag;
}
bool Sn::ConvX::initOutput(PxOutputStream& targetStream)
{
mOutStream = &targetStream;
mOutputSize = 0;
mNullPtr = false;
mNoOutput = false;
const MetaData* srcMetaData = getBinaryMetaData(META_DATA_SRC);
PX_ASSERT(srcMetaData);
const MetaData* dstMetaData = getBinaryMetaData(META_DATA_DST);
PX_ASSERT(dstMetaData);
mSrcPtrSize = srcMetaData->getPtrSize();
mDstPtrSize = dstMetaData->getPtrSize();
PX_ASSERT(!srcMetaData->getFlip());
mMustFlip = dstMetaData->getFlip();
return true;
}
void Sn::ConvX::closeOutput()
{
mOutStream = NULL;
}
int Sn::ConvX::getCurrentOutputSize()
{
return mOutputSize;
}
void Sn::ConvX::output(short value)
{
if(mNoOutput)
return;
if(mMustFlip)
flip(value);
PX_ASSERT(mOutStream);
const size_t size = mOutStream->write(&value, 2);
PX_ASSERT(size==2);
mOutputSize += int(size);
}
void Sn::ConvX::output(int value)
{
if(mNoOutput)
return;
if(mMustFlip)
flip(value);
PX_ASSERT(mOutStream);
const size_t size = mOutStream->write(&value, 4);
PX_ASSERT(size==4);
mOutputSize += int(size);
}
//ntohll is a macro on apple yosemite
static PxU64 ntohll_internal(const PxU64 value)
{
union
{
PxU64 ull;
PxU8 c[8];
} x;
x.ull = value;
PxU8 c = 0;
c = x.c[0]; x.c[0] = x.c[7]; x.c[7] = c;
c = x.c[1]; x.c[1] = x.c[6]; x.c[6] = c;
c = x.c[2]; x.c[2] = x.c[5]; x.c[5] = c;
c = x.c[3]; x.c[3] = x.c[4]; x.c[4] = c;
return x.ull;
}
void Sn::ConvX::output(PxU64 value)
{
if(mNoOutput)
return;
if(mMustFlip)
// flip(value);
value = ntohll_internal(value);
PX_ASSERT(mOutStream);
const size_t size = mOutStream->write(&value, 8);
PX_ASSERT(size==8);
mOutputSize += int(size);
}
void Sn::ConvX::output(const char* buffer, int nbBytes)
{
if(mNoOutput)
return;
if(!nbBytes)
return;
PX_ASSERT(mOutStream);
const PxU32 size = mOutStream->write(buffer, PxU32(nbBytes));
PX_ASSERT(size== PxU32(nbBytes));
mOutputSize += int(size);
}
void Sn::ConvX::convert8(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize==1*entry.mCount);
PX_ASSERT(mOutStream);
PX_ASSERT(entry.mSize==dstEntry.mSize);
const PxU32 size = mOutStream->write(src, PxU32(entry.mSize));
PX_ASSERT(size== PxU32(entry.mSize));
mOutputSize += int(size);
}
// This is called to convert auto-generated "padding bytes" (or so we think).
// We use a special converter to check the input bytes and issue warnings when it doesn't look like padding
void Sn::ConvX::convertPad8(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
(void)src;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize);
PX_ASSERT(entry.mSize==1*entry.mCount);
PX_ASSERT(mOutStream);
PX_ASSERT(entry.mSize==dstEntry.mSize);
// PT: we don't output the source data on purpose, to catch missing meta-data
// sschirm: changed that to 0xcd, so we can mark the output as "having marked pads"
const unsigned char b = 0xcd;
for(int i=0;i<entry.mSize;i++)
{
const size_t size = mOutStream->write(&b, 1);
(void)size;
}
mOutputSize += entry.mSize;
}
void Sn::ConvX::convert16(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize==int(sizeof(short)*entry.mCount));
PX_ASSERT(mOutStream);
PX_ASSERT(entry.mSize==dstEntry.mSize);
const short* data = reinterpret_cast<const short*>(src);
for(int i=0;i<entry.mCount;i++)
{
short value = *data++;
if(mMustFlip)
flip(value);
const size_t size = mOutStream->write(&value, sizeof(short));
PX_ASSERT(size==sizeof(short));
mOutputSize += int(size);
}
}
void Sn::ConvX::convert32(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize==int(sizeof(int)*entry.mCount));
PX_ASSERT(mOutStream);
PX_ASSERT(entry.mSize==dstEntry.mSize);
const int* data = reinterpret_cast<const int*>(src);
for(int i=0;i<entry.mCount;i++)
{
int value = *data++;
if(mMustFlip)
flip(value);
const size_t size = mOutStream->write(&value, sizeof(int));
PX_ASSERT(size==sizeof(int));
mOutputSize += int(size);
}
}
void Sn::ConvX::convert64(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize==int(sizeof(PxU64)*entry.mCount));
PX_ASSERT(mOutStream);
PX_ASSERT(entry.mSize==dstEntry.mSize);
const PxU64* data = reinterpret_cast<const PxU64*>(src);
for(int i=0;i<entry.mCount;i++)
{
PxU64 value = *data++;
if(mMustFlip)
value = ntohll_internal(value);
const size_t size = mOutStream->write(&value, sizeof(PxU64));
PX_ASSERT(size==sizeof(PxU64));
mOutputSize += int(size);
}
}
void Sn::ConvX::convertFloat(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize==int(sizeof(float)*entry.mCount));
PX_ASSERT(mOutStream);
PX_ASSERT(entry.mSize==dstEntry.mSize);
const float* data = reinterpret_cast<const float*>(src);
for(int i=0;i<entry.mCount;i++)
{
float value = *data++;
if(mMustFlip)
flip(value);
const size_t size = mOutStream->write(&value, sizeof(float));
PX_ASSERT(size==sizeof(float));
mOutputSize += int(size);
}
}
void Sn::ConvX::convertPtr(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(entry.mSize==mSrcPtrSize*entry.mCount);
PX_ASSERT(mOutStream);
char buffer[16];
for(int i=0;i<entry.mCount;i++)
{
PxU64 testValue=0;
// Src pointer can be 4 or 8 bytes so we can't use "void*" here
if(mSrcPtrSize==4)
{
PX_ASSERT(sizeof(PxU32)==4);
const PxU32* data = reinterpret_cast<const PxU32*>(src);
PxU32 value = *data++;
src = reinterpret_cast<const char*>(data);
if(mPointerActiveRemap)
{
PxU32 ref;
if(mPointerActiveRemap->getObjectRef(value, ref))
{
value = ref;
}
else if(value)
{
// all pointers not in the pointer remap table get set as 0x12345678, this also applies to PhysX name properties (mName)
value=0x12345678;
}
}
else
{
//we should only get here during convertReferenceTables to build up the pointer map
PxU32 ref;
if (mPointerRemap.getObjectRef(value, ref))
{
value = ref;
}
else if(value)
{
const PxU32 remappedRef = 0x80000000 | (mPointerRemapCounter++ +1);
mPointerRemap.setObjectRef(value, remappedRef);
value = remappedRef;
}
}
if(mMustFlip)
flip(value);
if(mNullPtr)
value = 0;
*reinterpret_cast<PxU32*>(buffer) = value;
}
else
{
PX_ASSERT(mSrcPtrSize==8);
PX_ASSERT(sizeof(PxU64)==8);
const PxU64* data = reinterpret_cast<const PxU64*>(src);
PxU64 value = *data++;
src = reinterpret_cast<const char*>(data);
if(mPointerActiveRemap)
{
PxU32 ref;
if(mPointerActiveRemap->getObjectRef(value, ref))
{
value = ref;
}
else if(value)
{
// all pointers not in the pointer remap table get set as 0x12345678, this also applies to PhysX name properties (mName)
value=0x12345678;
}
}
else
{
//we should only get here during convertReferenceTables to build up the pointer map
PxU32 ref;
if (mPointerRemap.getObjectRef(value, ref))
{
value = ref;
}
else if(value)
{
const PxU32 remappedRef = 0x80000000 | (mPointerRemapCounter++ +1);
mPointerRemap.setObjectRef(value, remappedRef);
value = remappedRef;
}
}
if(mNullPtr)
value = 0;
testValue = value;
*reinterpret_cast<PxU64*>(buffer) = value;
}
if(mSrcPtrSize==mDstPtrSize)
{
const size_t size = mOutStream->write(buffer, PxU32(mSrcPtrSize));
PX_ASSERT(size==PxU32(mSrcPtrSize));
mOutputSize += int(size);
}
else
{
if(mDstPtrSize>mSrcPtrSize)
{
// 32bit to 64bit
PX_ASSERT(mDstPtrSize==8);
PX_ASSERT(mSrcPtrSize==4);
// We need to output the lower 32bits first for PC. Might be different on a 64bit console....
// Output src ptr for the lower 32bits
const size_t size = mOutStream->write(buffer, PxU32(mSrcPtrSize));
PX_ASSERT(size==PxU32(mSrcPtrSize));
mOutputSize += int(size);
// Output zeros for the higher 32bits
const int zero = 0;
const size_t size0 = mOutStream->write(&zero, 4);
PX_ASSERT(size0==4);
mOutputSize += int(size0);
}
else
{
// 64bit to 32bit
PX_ASSERT(mSrcPtrSize==8);
PX_ASSERT(mDstPtrSize==4);
// Not sure how we can safely convert 64bit ptrs to 32bit... just drop the high 32 bits?!?
PxU32 ptr32 = *reinterpret_cast<PxU32*>(buffer);
(void)ptr32;
PxU32 ptr32b = PxU32(testValue);
(void)ptr32b;
if(mMustFlip)
flip(ptr32b);
// Output src ptr for the lower 32bits
const size_t size = mOutStream->write(&ptr32b, 4);
PX_ASSERT(size==4);
mOutputSize += int(size);
}
}
}
}
void Sn::ConvX::convertHandle16(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry)
{
(void)dstEntry;
if(mNoOutput)
return;
PX_ASSERT(strcmp(entry.mType, "PxU16") == 0);
PX_ASSERT(entry.mSize==dstEntry.mSize);
PX_ASSERT(mOutStream);
const PxU16* handles = reinterpret_cast<const PxU16*>(src);
for(int i=0;i<entry.mCount;i++)
{
PxU16 value = handles[i];
if (mHandle16ActiveRemap)
{
PxU16 ref;
bool isMapped = mHandle16ActiveRemap->getObjectRef(value, ref);
PX_UNUSED(isMapped);
PX_ASSERT(isMapped);
value = ref;
}
else
{
//we should only get here during convertReferenceTables to build up the pointer map
PxU16 ref;
if (mHandle16Remap.getObjectRef(value, ref))
{
value = ref;
}
else
{
const PxU16 remappedRef = mHandle16RemapCounter++;
mHandle16Remap.setObjectRef(value, remappedRef);
value = remappedRef;
}
}
if(mMustFlip)
flip(value);
const size_t size = mOutStream->write(&value, sizeof(PxU16));
PX_UNUSED(size);
PX_ASSERT(size==sizeof(PxU16));
mOutputSize += sizeof(PxU16);
}
}
| 12,053 | C++ | 23.5 | 125 | 0.684394 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnBinaryDeserialization.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/PxSerializer.h"
#include "foundation/PxHash.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxString.h"
#include "extensions/PxSerialization.h"
#include "PxPhysics.h"
#include "PxPhysicsSerialization.h"
#include "SnFile.h"
#include "SnSerializationContext.h"
#include "SnConvX_Align.h"
#include "serialization/SnSerializationRegistry.h"
#include "serialization/SnSerialUtils.h"
#include "CmCollection.h"
using namespace physx;
using namespace Sn;
namespace
{
PX_INLINE PxU8* alignPtr(PxU8* ptr, PxU32 alignment = PX_SERIAL_ALIGN)
{
if(!alignment)
return ptr;
const PxU32 padding = getPadding(size_t(ptr), alignment);
PX_ASSERT(!getPadding(size_t(ptr + padding), alignment));
return ptr + padding;
}
PX_FORCE_INLINE PxU32 read32(PxU8*& address)
{
const PxU32 value = *reinterpret_cast<PxU32*>(address);
address += sizeof(PxU32);
return value;
}
bool readHeader(PxU8*& address)
{
const PxU32 header = read32(address);
PX_UNUSED(header);
const PxU32 version = read32(address);
PX_UNUSED(version);
char binaryVersionGuid[SN_BINARY_VERSION_GUID_NUM_CHARS + 1];
PxMemCopy(binaryVersionGuid, address, SN_BINARY_VERSION_GUID_NUM_CHARS);
binaryVersionGuid[SN_BINARY_VERSION_GUID_NUM_CHARS] = 0;
address += SN_BINARY_VERSION_GUID_NUM_CHARS;
PX_UNUSED(binaryVersionGuid);
const PxU32 platformTag = read32(address);
PX_UNUSED(platformTag);
const PxU32 markedPadding = read32(address);
PX_UNUSED(markedPadding);
if (header != PX_MAKE_FOURCC('S','E','B','D'))
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"Buffer contains data with wrong header indicating invalid binary data.");
return false;
}
if (!checkCompatibility(binaryVersionGuid))
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"Buffer contains binary data version 0x%s and is incompatible with this PhysX sdk (0x%s).\n",
binaryVersionGuid, getBinaryVersionGuid());
return false;
}
if (platformTag != getBinaryPlatformTag())
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"Buffer contains data with platform mismatch:\nExpected: %s \nActual: %s\n",
getBinaryPlatformName(getBinaryPlatformTag()),
getBinaryPlatformName(platformTag));
return false;
}
return true;
}
bool checkImportReferences(const ImportReference* importReferences, PxU32 nbImportReferences, const Cm::Collection* externalRefs)
{
if (!externalRefs)
{
if (nbImportReferences > 0)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxSerialization::createCollectionFromBinary: External references needed but no externalRefs collection specified.");
return false;
}
}
else
{
for (PxU32 i=0; i<nbImportReferences;i++)
{
PxSerialObjectId id = importReferences[i].id;
PxType type = importReferences[i].type;
PxBase* referencedObject = externalRefs->find(id);
if (!referencedObject)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxSerialization::createCollectionFromBinary: External reference %" PX_PRIu64 " expected in externalRefs collection but not found.", id);
return false;
}
if (referencedObject->getConcreteType() != type)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxSerialization::createCollectionFromBinary: External reference %d type mismatch. Expected %d but found %d in externalRefs collection.", type, referencedObject->getConcreteType());
return false;
}
}
}
return true;
}
}
PxCollection* PxSerialization::createCollectionFromBinary(void* memBlock, PxSerializationRegistry& sr, const PxCollection* pxExternalRefs)
{
if(size_t(memBlock) & (PX_SERIAL_FILE_ALIGN-1))
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Buffer must be 128-bytes aligned.");
return NULL;
}
PxU8* address = reinterpret_cast<PxU8*>(memBlock);
const Cm::Collection* externalRefs = static_cast<const Cm::Collection*>(pxExternalRefs);
if (!readHeader(address))
{
return NULL;
}
ManifestEntry* manifestTable;
PxU32 nbManifestEntries;
PxU32 nbObjectsInCollection;
PxU32 objectDataEndOffset;
// read number of objects in collection
address = alignPtr(address);
nbObjectsInCollection = read32(address);
// read manifest (PxU32 offset, PxConcreteType type)
{
address = alignPtr(address);
nbManifestEntries = read32(address);
PX_ASSERT(*reinterpret_cast<PxU32*>(address) == 0); //first offset is always 0
manifestTable = (nbManifestEntries > 0) ? reinterpret_cast<ManifestEntry*>(address) : NULL;
address += nbManifestEntries*sizeof(ManifestEntry);
objectDataEndOffset = read32(address);
}
ImportReference* importReferences;
PxU32 nbImportReferences;
// read import references
{
address = alignPtr(address);
nbImportReferences = read32(address);
importReferences = (nbImportReferences > 0) ? reinterpret_cast<ImportReference*>(address) : NULL;
address += nbImportReferences*sizeof(ImportReference);
}
if (!checkImportReferences(importReferences, nbImportReferences, externalRefs))
{
return NULL;
}
ExportReference* exportReferences;
PxU32 nbExportReferences;
// read export references
{
address = alignPtr(address);
nbExportReferences = read32(address);
exportReferences = (nbExportReferences > 0) ? reinterpret_cast<ExportReference*>(address) : NULL;
address += nbExportReferences*sizeof(ExportReference);
}
// read internal references arrays
PxU32 nbInternalPtrReferences = 0;
PxU32 nbInternalHandle16References = 0;
InternalReferencePtr* internalPtrReferences = NULL;
InternalReferenceHandle16* internalHandle16References = NULL;
{
address = alignPtr(address);
nbInternalPtrReferences = read32(address);
internalPtrReferences = (nbInternalPtrReferences > 0) ? reinterpret_cast<InternalReferencePtr*>(address) : NULL;
address += nbInternalPtrReferences*sizeof(InternalReferencePtr);
nbInternalHandle16References = read32(address);
internalHandle16References = (nbInternalHandle16References > 0) ? reinterpret_cast<InternalReferenceHandle16*>(address) : NULL;
address += nbInternalHandle16References*sizeof(InternalReferenceHandle16);
}
// create internal references map
InternalPtrRefMap internalPtrReferencesMap(nbInternalPtrReferences*2);
{
//create hash (we should load the hashes directly from memory)
for (PxU32 i = 0; i < nbInternalPtrReferences; i++)
{
const InternalReferencePtr& ref = internalPtrReferences[i];
internalPtrReferencesMap.insertUnique(ref.reference, SerialObjectIndex(ref.objIndex));
}
}
InternalHandle16RefMap internalHandle16ReferencesMap(nbInternalHandle16References*2);
{
for (PxU32 i=0;i<nbInternalHandle16References;i++)
{
const InternalReferenceHandle16& ref = internalHandle16References[i];
internalHandle16ReferencesMap.insertUnique(ref.reference, SerialObjectIndex(ref.objIndex));
}
}
SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr);
Cm::Collection* collection = static_cast<Cm::Collection*>(PxCreateCollection());
PX_ASSERT(collection);
collection->mObjects.reserve(nbObjectsInCollection*2);
if(nbExportReferences > 0)
collection->mIds.reserve(nbExportReferences*2);
PxU8* addressObjectData = alignPtr(address);
PxU8* addressExtraData = alignPtr(addressObjectData + objectDataEndOffset);
DeserializationContext context(manifestTable, importReferences, addressObjectData, internalPtrReferencesMap, internalHandle16ReferencesMap, externalRefs, addressExtraData);
// iterate over memory containing PxBase objects, create the instances, resolve the addresses, import the external data, add to collection.
{
PxU32 nbObjects = nbObjectsInCollection;
while(nbObjects--)
{
address = alignPtr(address);
context.alignExtraData();
// read PxBase header with type and get corresponding serializer.
PxBase* header = reinterpret_cast<PxBase*>(address);
const PxType classType = header->getConcreteType();
const PxSerializer* serializer = sn.getSerializer(classType);
PX_ASSERT(serializer);
PxBase* instance = serializer->createObject(address, context);
if (!instance)
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL,
"Cannot create class instance for concrete type %d.", classType);
collection->release();
return NULL;
}
collection->internalAdd(instance);
}
}
PX_ASSERT(nbObjectsInCollection == collection->internalGetNbObjects());
// update new collection with export references
{
bool manifestTableAccessError = false;
PX_ASSERT(addressObjectData != NULL);
for (PxU32 i=0;i<nbExportReferences;i++)
{
bool isExternal;
PxU32 manifestIndex = exportReferences[i].objIndex.getIndex(isExternal);
PX_ASSERT(!isExternal);
if (manifestIndex < nbManifestEntries)
{
PxBase* obj = reinterpret_cast<PxBase*>(addressObjectData + manifestTable[manifestIndex].offset);
collection->mIds.insertUnique(exportReferences[i].id, obj);
collection->mObjects[obj] = exportReferences[i].id;
}
else
{
manifestTableAccessError = true;
}
}
if (manifestTableAccessError)
{
PxGetFoundation().error(physx::PxErrorCode::eINTERNAL_ERROR, PX_FL, "Manifest table access error");
collection->release();
return NULL;
}
}
PxAddCollectionToPhysics(*collection);
return collection;
}
| 11,124 | C++ | 33.874608 | 250 | 0.750809 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Align.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 "SnConvX.h"
#include "SnConvX_Align.h"
#include <assert.h>
using namespace physx;
void Sn::ConvX::alignTarget(int alignment)
{
const int outputSize = getCurrentOutputSize();
const PxU32 outPadding = getPadding(size_t(outputSize), PxU32(alignment));
if(outPadding)
{
assert(outPadding<CONVX_ZERO_BUFFER_SIZE);
output(mZeros, int(outPadding));
}
}
const char* Sn::ConvX::alignStream(const char* buffer, int alignment)
{
const PxU32 padding = getPadding(size_t(buffer), PxU32(alignment));
assert(!getPadding(size_t(buffer + padding), PxU32(alignment)));
const int outputSize = getCurrentOutputSize();
const PxU32 outPadding = getPadding(size_t(outputSize), PxU32(alignment));
if(outPadding==padding)
{
assert(outPadding<CONVX_ZERO_BUFFER_SIZE);
output(mZeros, int(outPadding));
}
else if(outPadding)
{
assert(outPadding<CONVX_ZERO_BUFFER_SIZE);
output(mZeros, int(outPadding));
}
return buffer + padding;
}
| 2,508 | C++ | 38.825396 | 75 | 0.756778 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnBinarySerialization.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/PxSerializer.h"
#include "foundation/PxPhysicsVersion.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxSort.h"
#include "extensions/PxBinaryConverter.h"
#include "SnSerializationContext.h"
#include "serialization/SnSerialUtils.h"
#include "serialization/SnSerializationRegistry.h"
using namespace physx;
using namespace Cm;
using namespace Sn;
//------------------------------------------------------------------------------------
//// Binary Serialized PxCollection, format documentation
//------------------------------------------------------------------------------------
//
//
//------------------------------------------------------------------------------------
//// overview:
//// header information
//// manifest table
//// import references
//// export references
//// internal references
//// object data
//// extra data
//------------------------------------------------------------------------------------
//
//
//------------------------------------------------------------------------------------
//// header information:
//// header tag plus various version and platform information
//------------------------------------------------------------------------------------
// header SEBD
// PX_PHYSICS_VERSION
// PX_BINARY_SERIAL_VERSION
// platform tag
// markedPadding (on for PX_CHECKED)
// nbObjectsInCollection
//
//
//------------------------------------------------------------------------------------
//// manifest table:
//// one entry per collected object
//// offsets relative to object data buffer
//------------------------------------------------------------------------------------
// alignment
// PxU32 size
// (PxU32 offset, PxType type)*size
// PxU32 endOffset
//
//
//------------------------------------------------------------------------------------
//// import references:
//// one entry per required reference to external collection
//------------------------------------------------------------------------------------
// alignment
// PxU32 size
// (PxSerialObjectId id, PxType type)*size
//
//
//------------------------------------------------------------------------------------
//// export references:
//// one entry per object in the collection with id
//// object indices point into the manifest table (objects in the same collection)
//------------------------------------------------------------------------------------
// alignment
// PxU32 size
// (PxSerialObjectId id, SerialObjectIndex objIndex)*size
//
//
//------------------------------------------------------------------------------------
//// internal references:
//// one entry per reference, kind pair
//// object indices point either into the manifest table or into the import references
//// depending on whether the entry references the same collection or the external one
//// one section for pointer type references and one for index type references.
//------------------------------------------------------------------------------------
// alignment
// PxU32 sizePtrs;
// (size_t reference, PxU32 kind, SerialObjectIndex objIndex)*sizePtrs
// PxU32 sizeHandle16;
// (PxU16 reference, PxU32 kind, SerialObjectIndex objIndex)*sizeHandle16
//
//
//------------------------------------------------------------------------------------
//// object data:
//// serialized PxBase derived class instances
//// each object size depends on specific class
//// offsets are stored in manifest table
//------------------------------------------------------------------------------------
// alignment
// (PxConcreteType type, -----)
// alignment
// (PxConcreteType type, --------)
// alignment
// (PxConcreteType type, --)
// .
// .
//
//
// -----------------------------------------------------------------------------------
//// extra data:
//// extra data memory block
//// serialized and deserialized by PxBase implementations
////----------------------------------------------------------------------------------
// extra data
//
//------------------------------------------------------------------------------------
namespace
{
class OutputStreamWriter
{
public:
PX_INLINE OutputStreamWriter(PxOutputStream& stream)
: mStream(stream)
, mCount(0)
{}
PX_INLINE PxU32 write(const void* src, PxU32 offset)
{
PxU32 count = mStream.write(src, offset);
mCount += count;
return count;
}
PX_INLINE PxU32 getStoredSize()
{
return mCount;
}
private:
OutputStreamWriter& operator=(const OutputStreamWriter&);
PxOutputStream& mStream;
PxU32 mCount;
};
class LegacySerialStream : public PxSerializationContext
{
public:
LegacySerialStream(OutputStreamWriter& writer,
const PxCollection& collection,
bool exportNames) : mWriter(writer), mCollection(collection), mExportNames(exportNames) {}
void writeData(const void* buffer, PxU32 size) { mWriter.write(buffer, size); }
PxU32 getTotalStoredSize() { return mWriter.getStoredSize(); }
void alignData(PxU32 alignment)
{
if(!alignment)
return;
PxI32 bytesToPad = PxI32(getPadding(getTotalStoredSize(), alignment));
static const PxI32 BUFSIZE = 64;
char buf[BUFSIZE];
PxMemSet(buf, 0, bytesToPad < BUFSIZE ? PxU32(bytesToPad) : PxU32(BUFSIZE));
while(bytesToPad > 0)
{
writeData(buf, bytesToPad < BUFSIZE ? PxU32(bytesToPad) : PxU32(BUFSIZE));
bytesToPad -= BUFSIZE;
}
PX_ASSERT(!getPadding(getTotalStoredSize(), alignment));
}
virtual void registerReference(PxBase&, PxU32, size_t)
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_OPERATION, PX_FL,
"Cannot register references during exportData, exportExtraData.");
}
virtual const PxCollection& getCollection() const
{
return mCollection;
}
virtual void writeName(const char* name)
{
PxU32 len = name && mExportNames ? PxU32(strlen(name)) + 1 : 0;
writeData(&len, sizeof(len));
if(len) writeData(name, len);
}
private:
LegacySerialStream& operator=(const LegacySerialStream&);
OutputStreamWriter& mWriter;
const PxCollection& mCollection;
bool mExportNames;
};
void writeHeader(PxSerializationContext& stream, bool hasDeserializedAssets)
{
PX_UNUSED(hasDeserializedAssets);
//serialized binary data.
const PxU32 header = PX_MAKE_FOURCC('S','E','B','D');
stream.writeData(&header, sizeof(PxU32));
PxU32 version = PX_PHYSICS_VERSION;
stream.writeData(&version, sizeof(PxU32));
stream.writeData(PX_BINARY_SERIAL_VERSION, SN_BINARY_VERSION_GUID_NUM_CHARS);
PxU32 platformTag = getBinaryPlatformTag();
stream.writeData(&platformTag, sizeof(PxU32));
PxU32 markedPadding = 0;
#if PX_CHECKED
if(!hasDeserializedAssets)
markedPadding = 1;
#endif
stream.writeData(&markedPadding, sizeof(PxU32));
}
template<typename InternalReferenceType>
struct InternalReferencePredicate
{
PX_FORCE_INLINE bool operator()(InternalReferenceType& a, InternalReferenceType& b) const { return a.objIndex < b.objIndex; }
};
}
bool PxSerialization::serializeCollectionToBinary(PxOutputStream& outputStream, PxCollection& pxCollection, PxSerializationRegistry& sr, const PxCollection* pxExternalRefs, bool exportNames)
{
if(!PxSerialization::isSerializable(pxCollection, sr, pxExternalRefs))
return false;
Collection& collection = static_cast<Collection&>(pxCollection);
const Collection* externalRefs = static_cast<const Collection*>(pxExternalRefs);
//temporary memory stream which allows fixing up data up stream
SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr);
// sort collection by "order" value (this will be the order in which they get serialized)
sortCollection(collection, sn, false);
//initialized the context with the sorted collection.
SerializationContext context(collection, externalRefs);
// gather reference information
bool hasDeserializedAssets = false;
{
const PxU32 nb = collection.internalGetNbObjects();
for(PxU32 i=0;i<nb;i++)
{
PxBase* s = collection.internalGetObject(i);
PX_ASSERT(s && s->getConcreteType());
#if PX_CHECKED
//can't guarantee marked padding for deserialized instances
if(!(s->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY))
hasDeserializedAssets = true;
#endif
const PxSerializer* serializer = sn.getSerializer(s->getConcreteType());
PX_ASSERT(serializer);
serializer->registerReferences(*s, context);
}
}
// now start the actual serialization into the output stream
OutputStreamWriter writer(outputStream);
LegacySerialStream stream(writer, collection, exportNames);
writeHeader(stream, hasDeserializedAssets);
// write size of collection
stream.alignData(PX_SERIAL_ALIGN);
PxU32 nbObjectsInCollection = collection.internalGetNbObjects();
stream.writeData(&nbObjectsInCollection, sizeof(PxU32));
// write the manifest table (PxU32 offset, PxConcreteType type)
{
PxArray<ManifestEntry> manifestTable(collection.internalGetNbObjects());
PxU32 headerOffset = 0;
for(PxU32 i=0;i<collection.internalGetNbObjects();i++)
{
PxBase* s = collection.internalGetObject(i);
PX_ASSERT(s && s->getConcreteType());
PxType concreteType = s->getConcreteType();
const PxSerializer* serializer = sn.getSerializer(concreteType);
PX_ASSERT(serializer);
manifestTable[i] = ManifestEntry(headerOffset, concreteType);
PxU32 classSize = PxU32(serializer->getClassSize());
headerOffset += getPadding(classSize, PX_SERIAL_ALIGN) + classSize;
}
stream.alignData(PX_SERIAL_ALIGN);
const PxU32 nb = manifestTable.size();
stream.writeData(&nb, sizeof(PxU32));
stream.writeData(manifestTable.begin(), manifestTable.size()*sizeof(ManifestEntry));
//store offset for end of object buffer (PxU32 offset)
stream.writeData(&headerOffset, sizeof(PxU32));
}
// write import references
{
const PxArray<ImportReference>& importReferences = context.getImportReferences();
stream.alignData(PX_SERIAL_ALIGN);
const PxU32 nb = importReferences.size();
stream.writeData(&nb, sizeof(PxU32));
stream.writeData(importReferences.begin(), importReferences.size()*sizeof(ImportReference));
}
// write export references
{
PxU32 nbIds = collection.getNbIds();
PxArray<ExportReference> exportReferences(nbIds);
//we can't get quickly from id to object index in collection.
//if we only need this here, its not worth to build a hash
nbIds = 0;
for (PxU32 i=0;i<collection.getNbObjects();i++)
{
PxBase& obj = collection.getObject(i);
PxSerialObjectId id = collection.getId(obj);
if (id != PX_SERIAL_OBJECT_ID_INVALID)
{
SerialObjectIndex objIndex(i, false); //i corresponds to manifest entry
exportReferences[nbIds++] = ExportReference(id, objIndex);
}
}
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(&nbIds, sizeof(PxU32));
stream.writeData(exportReferences.begin(), exportReferences.size()*sizeof(ExportReference));
}
// write internal references
{
InternalPtrRefMap& internalPtrReferencesMap = context.getInternalPtrReferencesMap();
PxArray<InternalReferencePtr> internalReferencesPtr(internalPtrReferencesMap.size());
PxU32 nbInternalPtrReferences = 0;
InternalHandle16RefMap& internalHandle16ReferencesMap = context.getInternalHandle16ReferencesMap();
PxArray<InternalReferenceHandle16> internalReferencesHandle16(internalHandle16ReferencesMap.size());
PxU32 nbInternalHandle16References = 0;
{
for(InternalPtrRefMap::Iterator iter = internalPtrReferencesMap.getIterator(); !iter.done(); ++iter)
internalReferencesPtr[nbInternalPtrReferences++] = InternalReferencePtr(iter->first, iter->second);
for(InternalHandle16RefMap::Iterator iter = internalHandle16ReferencesMap.getIterator(); !iter.done(); ++iter)
internalReferencesHandle16[nbInternalHandle16References++] = InternalReferenceHandle16(PxTo16(iter->first), iter->second);
//sort InternalReferences according to SerialObjectIndex for determinism
PxSort<InternalReferencePtr, InternalReferencePredicate<InternalReferencePtr> >(internalReferencesPtr.begin(), internalReferencesPtr.size(), InternalReferencePredicate<InternalReferencePtr>());
PxSort<InternalReferenceHandle16, InternalReferencePredicate<InternalReferenceHandle16> >(internalReferencesHandle16.begin(), internalReferencesHandle16.size(), InternalReferencePredicate<InternalReferenceHandle16>());
}
stream.alignData(PX_SERIAL_ALIGN);
stream.writeData(&nbInternalPtrReferences, sizeof(PxU32));
stream.writeData(internalReferencesPtr.begin(), internalReferencesPtr.size()*sizeof(InternalReferencePtr));
stream.writeData(&nbInternalHandle16References, sizeof(PxU32));
stream.writeData(internalReferencesHandle16.begin(), internalReferencesHandle16.size()*sizeof(InternalReferenceHandle16));
}
// write object data
{
stream.alignData(PX_SERIAL_ALIGN);
const PxU32 nb = collection.internalGetNbObjects();
for(PxU32 i=0;i<nb;i++)
{
PxBase* s = collection.internalGetObject(i);
PX_ASSERT(s && s->getConcreteType());
const PxSerializer* serializer = sn.getSerializer(s->getConcreteType());
PX_ASSERT(serializer);
stream.alignData(PX_SERIAL_ALIGN);
serializer->exportData(*s, stream);
}
}
// write extra data
{
const PxU32 nb = collection.internalGetNbObjects();
for(PxU32 i=0;i<nb;i++)
{
PxBase* s = collection.internalGetObject(i);
PX_ASSERT(s && s->getConcreteType());
const PxSerializer* serializer = sn.getSerializer(s->getConcreteType());
PX_ASSERT(serializer);
stream.alignData(PX_SERIAL_ALIGN);
serializer->exportExtraData(*s, stream);
}
}
return true;
}
bool PxSerialization::serializeCollectionToBinaryDeterministic(PxOutputStream& outputStream, PxCollection& pxCollection, PxSerializationRegistry& sr, const PxCollection* pxExternalRefs, bool exportNames)
{
PxDefaultMemoryOutputStream tmpOutputStream;
if (!serializeCollectionToBinary(tmpOutputStream, pxCollection, sr, pxExternalRefs, exportNames))
return false;
PxDefaultMemoryOutputStream metaDataOutput;
dumpBinaryMetaData(metaDataOutput, sr);
PxBinaryConverter* converter = createBinaryConverter();
PxDefaultMemoryInputData srcMetaData(metaDataOutput.getData(), metaDataOutput.getSize());
PxDefaultMemoryInputData dstMetaData(metaDataOutput.getData(), metaDataOutput.getSize());
if (!converter->setMetaData(srcMetaData, dstMetaData))
return false;
PxDefaultMemoryInputData srcBinaryData(tmpOutputStream.getData(), tmpOutputStream.getSize());
bool ret = converter->convert(srcBinaryData, srcBinaryData.getLength(), outputStream);
converter->release();
return ret;
}
| 16,242 | C++ | 35.748869 | 221 | 0.674301 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Common.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 SN_CONVX_COMMON_H
#define SN_CONVX_COMMON_H
#if PX_VC
#pragma warning(disable:4121) // alignment of a member was sensitive to packing
#endif
#include "common/PxPhysXCommonConfig.h"
#define inline_ PX_FORCE_INLINE
#define PsArray physx::PxArray
#endif
| 1,832 | C | 44.824999 | 79 | 0.766376 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Align.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 SN_CONVX_ALIGN_H
#define SN_CONVX_ALIGN_H
namespace physx { namespace Sn {
#define ALIGN_DEFAULT 16
#define ALIGN_FILE 128
PX_INLINE PxU32 getPadding(size_t value, PxU32 alignment)
{
const PxU32 mask = alignment-1;
const PxU32 overhead = PxU32(value) & mask;
return (alignment - overhead) & mask;
}
} }
#endif
| 1,897 | C | 42.136363 | 74 | 0.758039 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnSerializationContext.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 "SnSerializationContext.h"
using namespace physx;
using namespace Sn;
PxBase* DeserializationContext::resolveReference(PxU32 kind, size_t reference) const
{
SerialObjectIndex objIndex;
if (kind == PX_SERIAL_REF_KIND_PXBASE)
{
const InternalPtrRefMap::Entry* entry0 = mInternalPtrReferencesMap.find(reference);
PX_ASSERT(entry0);
objIndex = entry0->second;
}
else if (kind == PX_SERIAL_REF_KIND_MATERIAL_IDX)
{
const InternalHandle16RefMap::Entry* entry0 = mInternalHandle16ReferencesMap.find(PxU16(reference));
PX_ASSERT(entry0);
objIndex = entry0->second;
}
else
{
return NULL;
}
bool isExternal;
PxU32 index = objIndex.getIndex(isExternal);
PxBase* base = NULL;
if (isExternal)
{
const ImportReference& entry = mImportReferences[index];
base = mExternalRefs->find(entry.id);
}
else
{
const ManifestEntry& entry = mManifestTable[index];
base = reinterpret_cast<PxBase*>(mObjectDataAddress + entry.offset);
}
PX_ASSERT(base);
return base;
}
void SerializationContext::registerReference(PxBase& serializable, PxU32 kind, size_t reference)
{
#if PX_CHECKED
if ((kind & PX_SERIAL_REF_KIND_PTR_TYPE_BIT) == 0 && reference > 0xffff)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxSerializationContext::registerReference: only 16 bit handles supported.");
return;
}
#endif
bool isExternal = mExternalRefs && mExternalRefs->contains(serializable);
PxU32 index;
if (isExternal)
{
PxSerialObjectId id = mExternalRefs->getId(serializable);
PX_ASSERT(id != PX_SERIAL_OBJECT_ID_INVALID);
if (const PxHashMap<PxSerialObjectId, PxU32>::Entry* entry = mImportReferencesMap.find(id))
{
index = entry->second;
}
else
{
index = mImportReferences.size();
mImportReferencesMap.insert(id, index);
mImportReferences.pushBack(ImportReference(id, serializable.getConcreteType()));
}
}
else
{
PX_ASSERT(mCollection.contains(serializable));
index = mObjToCollectionIndexMap[&serializable];
}
if (kind & PX_SERIAL_REF_KIND_PXBASE)
{
mInternalPtrReferencesMap[reference] = SerialObjectIndex(index, isExternal);
}
else if (kind & PX_SERIAL_REF_KIND_MATERIAL_IDX)
{
mInternalHandle16ReferencesMap[PxU16(reference)] = SerialObjectIndex(index, isExternal);
}
}
| 3,994 | C++ | 34.043859 | 143 | 0.750626 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_MetaData.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/PxIO.h"
#include "foundation/PxMemory.h"
#include "foundation/PxString.h"
#include "SnConvX.h"
#include "common/PxSerialFramework.h"
#include "serialization/SnSerialUtils.h"
#include <assert.h>
using namespace physx;
using namespace physx::Sn;
//#define REMOVE_EXPLICIT_PADDING
static const char gVTablePtr[] = "v-table ptr";
static const char gAutoPadding[] = "auto-generated padding";
static const char gByte[] = "paddingByte";
///////////////////////////////////////////////////////////////////////////////
bool PxMetaDataEntry::isVTablePtr() const
{
return mType==gVTablePtr;
}
///////////////////////////////////////////////////////////////////////////////
bool MetaClass::getFieldByType(const char* type, PxMetaDataEntry& entry) const
{
assert(type);
PxU32 nbFields = mFields.size();
for(PxU32 i=0;i<nbFields;i++)
{
if(Pxstrcmp(mFields[i].mType, type)==0)
{
entry = mFields[i];
return true;
}
}
return false;
}
bool MetaClass::getFieldByName(const char* name, PxMetaDataEntry& entry) const
{
assert(name);
PxU32 nbFields = mFields.size();
for(PxU32 i=0;i<nbFields;i++)
{
if(Pxstrcmp(mFields[i].mName, name)==0)
{
entry = mFields[i];
return true;
}
}
return false;
}
void MetaClass::checkAndCompleteClass(const MetaData& owner, int& startOffset, int& nbBytes)
{
if(startOffset!=-1)
{
owner.mConvX.displayMessage(PxErrorCode::eDEBUG_INFO,
"\n Adding %d padding bytes at offset %d in class %s.\n", nbBytes, startOffset, mClassName);
// Leap of faith: add padding bytes there
PxMetaDataEntry padding;
padding.mType = gByte;
padding.mName = gAutoPadding;
padding.mOffset = startOffset;
padding.mSize = nbBytes;
padding.mCount = nbBytes;
padding.mFlags = PxMetaDataFlag::ePADDING;
mFields.pushBack(padding);
startOffset = -1;
}
}
bool MetaClass::check(const MetaData& owner)
{
owner.mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "Checking class: %s\n", mClassName);
if(mCallback)
return true; // Skip atomic types
if(mMaster)
return true; // Skip typedefs
bool* map = reinterpret_cast<bool*>(PX_ALLOC(sizeof(bool)*mSize, "bool"));
memset(map, 0, size_t(mSize));
const PxU32 nbFields = mFields.size();
for(PxU32 i=0;i<nbFields;i++)
{
const PxMetaDataEntry& field = mFields[i];
if(field.mFlags & PxMetaDataFlag::eEXTRA_DATA)
continue;
// if((field.mFlags & PxMetaDataFlag::eUNION) && !field.mSize)
// continue; // Union type
assert(field.mSize);
const int byteStart = field.mOffset;
const int byteEnd = field.mOffset + field.mSize;
assert(byteStart>=0 && byteStart<mSize);
assert(byteEnd>=0 && byteEnd<=mSize);
int startOffset = -1;
int nbBytes = 0;
for(int j=byteStart;j<byteEnd;j++)
{
if(map[j])
{
if(startOffset==-1)
{
startOffset = int(i);
nbBytes = 0;
}
nbBytes++;
// displayErrorMessage(" %s: found overlapping bytes!\n", mClassName);
}
else
{
if(startOffset!=-1)
{
owner.mConvX.displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: %s: %d overlapping bytes at offset %d!\n", mClassName, nbBytes, startOffset);
startOffset = -1;
PX_FREE(map);
return false;
}
}
map[j] = true;
}
if(startOffset!=-1)
{
owner.mConvX.displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: %s: %d overlapping bytes at offset %d!\n", mClassName, nbBytes, startOffset);
startOffset = -1;
PX_FREE(map);
return false;
}
}
{
int startOffset = -1;
int nbBytes = 0;
for(int i=0;i<mSize;i++)
{
if(!map[i])
{
if(startOffset==-1)
{
startOffset = i;
nbBytes = 0;
}
nbBytes++;
}
else
{
checkAndCompleteClass(owner, startOffset, nbBytes);
}
}
checkAndCompleteClass(owner, startOffset, nbBytes);
}
PX_FREE(map);
//
for(PxU32 i=0;i<nbFields;i++)
{
const PxMetaDataEntry& current = mFields[i];
if(current.mFlags & PxMetaDataFlag::ePTR)
continue;
MetaClass* fieldMetaClass = owner.mConvX.getMetaClass(current.mType, owner.getType());
if(!fieldMetaClass)
{
owner.mConvX.displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: Missing meta-data for: %s\n", current.mType);
return false;
}
else
{
if(current.mFlags & PxMetaDataFlag::eEXTRA_DATA)
{
owner.mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "Extra data: %s\n", current.mType);
}
else
{
assert(fieldMetaClass->mSize*current.mCount==current.mSize);
}
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
MetaData::MetaData(ConvX& convx) :
mConvX (convx),
mType (META_DATA_NONE),
mNbEntries (0),
mEntries (NULL),
mStringTable (NULL),
mVersion (0),
mSizeOfPtr (0),
mPlatformTag (0),
mGaussMapLimit (0),
mFlip (false)
{
}
MetaData::~MetaData()
{
PxU32 nbMetaClasses = mMetaClasses.size();
for(PxU32 i=0;i<nbMetaClasses;i++)
{
MetaClass* current = mMetaClasses[i];
PX_DELETE(current);
}
PX_FREE(mStringTable);
PX_DELETE_ARRAY(mEntries);
}
MetaClass* MetaData::getMetaClass(const char* name) const
{
PxU32 nbMetaClasses = mMetaClasses.size();
for(PxU32 i=0;i<nbMetaClasses;i++)
{
MetaClass* current = mMetaClasses[i];
if(Pxstrcmp(current->mClassName, name)==0)
{
while(current->mMaster)
current = current->mMaster;
return current;
}
}
return NULL;
}
MetaClass* MetaData::getMetaClass(PxConcreteType::Enum concreteType) const
{
for(PxU32 i=0; i< mConcreteTypeTable.size(); i++)
{
if(mConcreteTypeTable[i].first == concreteType)
{
const char* className = offsetToText(reinterpret_cast<const char*>(size_t(mConcreteTypeTable[i].second)));
return getMetaClass(className);
}
}
return NULL;
}
MetaClass* MetaData::addNewClass(const char* name, int size, MetaClass* master, ConvertCallback callback)
{
// PT: if you reach this assert, you used PX_DEF_BIN_METADATA_TYPEDEF twice on the same type
assert(!getMetaClass(name));
MetaClass* mc = PX_NEW(MetaClass);
mc->mCallback = callback;
mc->mMaster = master;
mc->mClassName = name;
mc->mSize = size;
mc->mDepth = 0;
mc->mProcessed = false;
// mc->mNbEntries = -1;
mMetaClasses.pushBack(mc);
return mc;
}
bool MetaData::load(PxInputStream& inputStream, MetaDataType type)
{
assert(type!=META_DATA_NONE);
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "Loading %s meta-data...\n", type==META_DATA_SRC ? "source" : "target");
mType = type;
mFlip = false;
{
int header;
inputStream.read(&header, 4);
if(header==PX_MAKE_FOURCC('M','E','T','A'))
{
mFlip = false;
}
else if(header==PX_MAKE_FOURCC('A','T','E','M'))
{
mFlip = true;
}
else
{
mConvX.displayMessage(PxErrorCode::eINVALID_PARAMETER, "PxBinaryConverter: invalid meta-data file!\n");
return false;
}
if (type == META_DATA_SRC && mFlip)
{
mConvX.displayMessage(PxErrorCode::eINVALID_PARAMETER,
"PxBinaryConverter: source meta data needs to match endianness with current system!");
return false;
}
inputStream.read(&mVersion, 4);
if(mFlip)
{
flip(mVersion);
}
inputStream.read(mBinaryVersionGuid, SN_BINARY_VERSION_GUID_NUM_CHARS);
mBinaryVersionGuid[SN_BINARY_VERSION_GUID_NUM_CHARS] = 0;
if (!checkCompatibility(mBinaryVersionGuid))
{
mConvX.displayMessage(PxErrorCode::eINVALID_PARAMETER,
"PxBinaryConverter: binary data version 0x%s is incompatible with this PhysX sdk (0x%s).\n",
mBinaryVersionGuid, getBinaryVersionGuid());
return false;
}
inputStream.read(&mSizeOfPtr, 4);
if(mFlip)
flip(mSizeOfPtr);
inputStream.read(&mPlatformTag, 4);
if(mFlip)
flip(mPlatformTag);
if (!Sn::isBinaryPlatformTagValid(PxU32(mPlatformTag)))
{
mConvX.displayMessage(PxErrorCode::eINVALID_PARAMETER, "PxBinaryConverter: Unknown meta data platform tag");
return false;
}
inputStream.read(&mGaussMapLimit, 4);
if(mFlip)
flip(mGaussMapLimit);
inputStream.read(&mNbEntries, 4);
if(mFlip)
flip(mNbEntries);
mEntries = PX_NEW(PxMetaDataEntry)[PxU32(mNbEntries)];
if(mSizeOfPtr==8)
{
for(int i=0;i<mNbEntries;i++)
{
MetaDataEntry64 tmp;
inputStream.read(&tmp, sizeof(MetaDataEntry64));
if (mFlip) // important to flip them first, else the cast below might destroy information
{
flip(tmp.mType);
flip(tmp.mName);
}
// We can safely cast to 32bits here since we transformed the pointers to offsets in the string table on export
mEntries[i].mType = reinterpret_cast<const char*>(size_t(tmp.mType));
mEntries[i].mName = reinterpret_cast<const char*>(size_t(tmp.mName));
mEntries[i].mOffset = tmp.mOffset;
mEntries[i].mSize = tmp.mSize;
mEntries[i].mCount = tmp.mCount;
mEntries[i].mOffsetSize = tmp.mOffsetSize;
mEntries[i].mFlags = tmp.mFlags;
mEntries[i].mAlignment = tmp.mAlignment;
}
}
else
{
assert(mSizeOfPtr==4);
// inputStream.read(mEntries, mNbEntries*sizeof(PxMetaDataEntry));
for(int i=0;i<mNbEntries;i++)
{
MetaDataEntry32 tmp;
inputStream.read(&tmp, sizeof(MetaDataEntry32));
if (mFlip)
{
flip(tmp.mType);
flip(tmp.mName);
}
mEntries[i].mType = reinterpret_cast<const char*>(size_t(tmp.mType));
mEntries[i].mName = reinterpret_cast<const char*>(size_t(tmp.mName));
mEntries[i].mOffset = tmp.mOffset;
mEntries[i].mSize = tmp.mSize;
mEntries[i].mCount = tmp.mCount;
mEntries[i].mOffsetSize = tmp.mOffsetSize;
mEntries[i].mFlags = tmp.mFlags;
mEntries[i].mAlignment = tmp.mAlignment;
}
}
if(mFlip)
{
for(int i=0;i<mNbEntries;i++)
{
// mEntries[i].mType and mEntries[i].mName have been flipped already because they need special treatment
// on 64bit to 32bit platform conversions
flip(mEntries[i].mOffset);
flip(mEntries[i].mSize);
flip(mEntries[i].mCount);
flip(mEntries[i].mOffsetSize);
flip(mEntries[i].mFlags);
flip(mEntries[i].mAlignment);
}
}
int nbConcreteType;
inputStream.read(&nbConcreteType, 4);
if(mFlip)
flip(nbConcreteType);
for(int i=0; i<nbConcreteType; i++)
{
PxU16 concreteType;
PxU32 nameOffset;
inputStream.read(&concreteType, 2);
inputStream.read(&nameOffset, 4);
if(mFlip)
{
flip(concreteType);
flip(nameOffset);
}
mConcreteTypeTable.pushBack( PxPair<PxConcreteType::Enum, PxU32>(PxConcreteType::Enum(concreteType), nameOffset) );
}
int tableSize;
inputStream.read(&tableSize, 4);
if(mFlip)
flip(tableSize);
mStringTable = reinterpret_cast<char*>(PX_ALLOC(sizeof(char)*tableSize, "MetaData StringTable"));
inputStream.read(mStringTable, PxU32(tableSize));
}
// Register atomic types
{
addNewClass("bool", 1, NULL, &ConvX::convert8);
addNewClass("char", 1, NULL, &ConvX::convert8);
addNewClass("short", 2, NULL, &ConvX::convert16);
addNewClass("int", 4, NULL, &ConvX::convert32);
addNewClass("PxU64", 8, NULL, &ConvX::convert64);
addNewClass("float", 4, NULL, &ConvX::convertFloat);
addNewClass("paddingByte", 1, NULL, &ConvX::convertPad8);
}
{
MetaClass* currentClass = NULL;
for(int i=0;i<mNbEntries;i++)
{
mEntries[i].mType = offsetToText(mEntries[i].mType);
mEntries[i].mName = offsetToText(mEntries[i].mName);
if(mEntries[i].mFlags & PxMetaDataFlag::eTYPEDEF)
{
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "Found typedef: %s => %s\n", mEntries[i].mName, mEntries[i].mType);
MetaClass* mc = getMetaClass(mEntries[i].mName);
if(mc)
addNewClass(mEntries[i].mType, mc->mSize, mc, mc->mCallback);
else
mConvX.displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: Invalid typedef - Missing metadata for: %s, please check the source metadata.\n"
, mEntries[i].mName);
}
else if(mEntries[i].mFlags & PxMetaDataFlag::eCLASS)
{
if(!mEntries[i].mName)
{
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "Found class: %s\n", mEntries[i].mType);
currentClass = addNewClass(mEntries[i].mType, mEntries[i].mSize);
if(mEntries[i].mFlags & PxMetaDataFlag::eVIRTUAL)
{
PxMetaDataEntry vtable;
vtable.mType = gVTablePtr;
vtable.mName = gVTablePtr;
vtable.mOffset = 0;
vtable.mSize = mSizeOfPtr;
vtable.mCount = 1;
vtable.mFlags = PxMetaDataFlag::ePTR;
currentClass->mFields.pushBack(vtable);
}
}
else
{
assert(currentClass);
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, " - inherits from: %s\n", mEntries[i].mName);
currentClass->mBaseClasses.pushBack(mEntries[i]);
}
}
else
{
const int isUnion = mEntries[i].mFlags & PxMetaDataFlag::eUNION;
if(isUnion && !mEntries[i].mSize)
{
mConvX.registerUnionType(mEntries[i].mType, mEntries[i].mName, mEntries[i].mOffset);
}
else
{
if(isUnion)
{
mConvX.registerUnion(mEntries[i].mType);
}
const int isPadding = mEntries[i].mFlags & PxMetaDataFlag::ePADDING;
assert(currentClass);
#ifdef REMOVE_EXPLICIT_PADDING
if(!isPadding)
#endif
currentClass->mFields.pushBack(mEntries[i]);
if(isPadding)
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO,
" - contains padding: %s - %s\n", mEntries[i].mType, mEntries[i].mName);
else if(mEntries[i].mFlags & PxMetaDataFlag::eEXTRA_DATA)
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO,
" - contains extra data: %s%s\n", mEntries[i].mType, mEntries[i].mFlags & PxMetaDataFlag::ePTR ? "*" : "");
else
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO,
" - contains field: %s%s\n", mEntries[i].mType, mEntries[i].mFlags & PxMetaDataFlag::ePTR ? "*" : "");
}
}
}
}
// Sort classes by depth
struct Local
{
static bool _computeDepth(const MetaData& md, MetaClass* current, int currentDepth, int& maxDepth)
{
if(currentDepth>maxDepth)
maxDepth = currentDepth;
PxU32 nbBases = current->mBaseClasses.size();
for(PxU32 i=0;i<nbBases;i++)
{
const PxMetaDataEntry& baseClassEntry = current->mBaseClasses[i];
MetaClass* baseClass = md.getMetaClass(baseClassEntry.mName);
if(!baseClass)
{
md.mConvX.displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: Can't find class %s metadata, please check the source metadata.\n", baseClassEntry.mName);
return false;
}
if (!_computeDepth(md, baseClass, currentDepth+1, maxDepth))
return false;
}
return true;
}
static int compareClasses(const void* c0, const void* c1)
{
MetaClass** mc0 = reinterpret_cast<MetaClass**>(const_cast<void*>(c0));
MetaClass** mc1 = reinterpret_cast<MetaClass**>(const_cast<void*>(c1));
// return (*mc0)->mSize - (*mc1)->mSize;
return (*mc0)->mDepth - (*mc1)->mDepth;
}
static int compareEntries(const void* c0, const void* c1)
{
PxMetaDataEntry* mc0 = reinterpret_cast<PxMetaDataEntry*>(const_cast<void*>(c0));
PxMetaDataEntry* mc1 = reinterpret_cast<PxMetaDataEntry*>(const_cast<void*>(c1));
//mOffset is used to access control information for extra data, and not for offsets of the data itself.
assert(!(mc0->mFlags & PxMetaDataFlag::eEXTRA_DATA));
assert(!(mc1->mFlags & PxMetaDataFlag::eEXTRA_DATA));
return mc0->mOffset - mc1->mOffset;
}
};
{
// Compute depths
const PxU32 nbMetaClasses = mMetaClasses.size();
for(PxU32 i=0;i<nbMetaClasses;i++)
{
MetaClass* current = mMetaClasses[i];
int maxDepth = 0;
if(!Local::_computeDepth(*this, current, 0, maxDepth))
return false;
current->mDepth = maxDepth;
}
// Sort by depth
MetaClass** metaClasses = &mMetaClasses[0];
qsort(metaClasses, size_t(nbMetaClasses), sizeof(MetaClass*), Local::compareClasses);
}
// Replicate fields from base classes
{
PxU32 nbMetaClasses = mMetaClasses.size();
for(PxU32 k=0;k<nbMetaClasses;k++)
{
MetaClass* current = mMetaClasses[k];
PxU32 nbBases = current->mBaseClasses.size();
// merge entries of base classes and current class in the right order
// this is needed for extra data ordering, which is not covered by the mOffset sort
// in the next stage below
PsArray<PxMetaDataEntry> mergedEntries;
for(PxU32 i=0;i<nbBases;i++)
{
const PxMetaDataEntry& baseClassEntry = current->mBaseClasses[i];
MetaClass* baseClass = getMetaClass(baseClassEntry.mName);
assert(baseClass);
assert(baseClass->mBaseClasses.size()==0 || baseClass->mProcessed);
PxU32 nbBaseFields = baseClass->mFields.size();
for(PxU32 j=0;j<nbBaseFields;j++)
{
PxMetaDataEntry f = baseClass->mFields[j];
// Don't merge primary v-tables to avoid redundant v-table entries.
// It means the base v-table won't be inherited & needs to be explicitly defined in the metadata. Seems reasonable.
// Could be done better though.
if(f.mType==gVTablePtr && !f.mOffset && !baseClassEntry.mOffset)
continue;
f.mOffset += baseClassEntry.mOffset;
mergedEntries.pushBack(f);
}
current->mProcessed = true;
}
//append current fields to base class fields
for (PxU32 i = 0; i < current->mFields.size(); i++)
{
mergedEntries.pushBack(current->mFields[i]);
}
current->mFields.clear();
current->mFields.assign(mergedEntries.begin(), mergedEntries.end());
}
}
// Check classes
{
PxU32 nbMetaClasses = mMetaClasses.size();
for(PxU32 i=0;i<nbMetaClasses;i++)
{
MetaClass* current = mMetaClasses[i];
if(!current->check(*this))
return false;
}
}
// Sort meta-data by offset
{
PxU32 nbMetaClasses = mMetaClasses.size();
for(PxU32 i=0;i<nbMetaClasses;i++)
{
MetaClass* current = mMetaClasses[i];
PxU32 nbFields = current->mFields.size();
if(nbFields<2)
continue;
PxMetaDataEntry* entries = ¤t->mFields[0];
PxMetaDataEntry* newEntries = PX_NEW(PxMetaDataEntry)[nbFields];
PxU32 nb = 0;
for(PxU32 j=0;j<nbFields;j++)
if(!(entries[j].mFlags & PxMetaDataFlag::eEXTRA_DATA))
newEntries[nb++] = entries[j];
PxU32 nbToSort = nb;
for(PxU32 j=0;j<nbFields;j++)
if(entries[j].mFlags & PxMetaDataFlag::eEXTRA_DATA)
newEntries[nb++] = entries[j];
assert(nb==nbFields);
PxMemCopy(entries, newEntries, nb*sizeof(PxMetaDataEntry));
PX_DELETE_ARRAY(newEntries);
qsort(entries, size_t(nbToSort), sizeof(PxMetaDataEntry), Local::compareEntries);
}
}
return true;
}
namespace
{
//tool functions for MetaData::compare
bool str_equal(const char* src, const char* dst)
{
if (src == dst)
return true;
if (src != NULL && dst != NULL)
return Pxstrcmp(src, dst) == 0;
return false;
}
const char* str_print(const char* str)
{
return str != NULL ? str : "(nullptr)";
}
}
#define COMPARE_METADATA_BOOL_MD(type, src, dst, field) if ((src).field != (dst).field) \
{ mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "%s::%s missmatch: src %s dst %s\n", #type, #field, (src).field?"true":"false", (dst).field?"true":"false"); isEquivalent = false; }
#define COMPARE_METADATA_INT_MD(type, src, dst, field) if ((src).field != (dst).field) \
{ mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "%s::%s missmatch: src %d dst %d\n", #type, #field, (src).field, (dst).field); isEquivalent = false; }
#define COMPARE_METADATA_STRING_MD(type, src, dst, field) \
if (!str_equal((src).field, (dst).field)) \
{ \
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "%s::%s missmatch: src %s dst %s\n", #type, #field, str_print((src).field), str_print((dst).field)); \
isEquivalent = false; \
}
bool MetaData::compare(const MetaData& dst) const
{
bool isEquivalent = true;
//mType
COMPARE_METADATA_BOOL_MD(MetaData, *this, dst, mFlip)
//mVersion
COMPARE_METADATA_STRING_MD(MetaData, *this, dst, mBinaryVersionGuid)
COMPARE_METADATA_INT_MD(MetaData, *this, dst, mSizeOfPtr)
COMPARE_METADATA_INT_MD(MetaData, *this, dst, mPlatformTag)
COMPARE_METADATA_INT_MD(MetaData, *this, dst, mGaussMapLimit)
COMPARE_METADATA_INT_MD(MetaData, *this, dst, mNbEntries)
//find classes missing in dst
for (PxU32 i = 0; i<mMetaClasses.size(); i++)
{
MetaClass* mcSrc = mMetaClasses[i];
MetaClass* mcDst = dst.getMetaClass(mcSrc->mClassName);
if (mcDst == NULL)
{
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "dst is missing meta class %s", mcSrc->mClassName);
}
}
//find classes missing in src
for (PxU32 i = 0; i<dst.mMetaClasses.size(); i++)
{
MetaClass* mcDst = dst.mMetaClasses[i];
MetaClass* mcSrc = getMetaClass(mcDst->mClassName);
if (mcSrc == NULL)
{
mConvX.displayMessage(PxErrorCode::eDEBUG_INFO, "src is missing meta class %s", mcDst->mClassName);
}
}
//compare classes present in src and dst
for (PxU32 i = 0; i<mMetaClasses.size(); i++)
{
const char* className = mMetaClasses[i]->mClassName;
MetaClass* mcSrc = getMetaClass(className);
MetaClass* mcDst = dst.getMetaClass(className);
if (mcSrc != NULL && mcDst != NULL)
{
COMPARE_METADATA_INT_MD(MetaClass, *mcSrc, *mcDst, mCallback)
COMPARE_METADATA_INT_MD(MetaClass, *mcSrc, *mcDst, mMaster) //should be 0 for both anyway
COMPARE_METADATA_STRING_MD(MetaClass, *mcSrc, *mcDst, mClassName)
COMPARE_METADATA_INT_MD(MetaClass, *mcSrc, *mcDst, mSize)
COMPARE_METADATA_INT_MD(MetaClass, *mcSrc, *mcDst, mDepth)
COMPARE_METADATA_INT_MD(MetaClass, *mcSrc, *mcDst, mBaseClasses.size())
if (mcSrc->mBaseClasses.size() == mcDst->mBaseClasses.size())
{
for (PxU32 b = 0; b < mcSrc->mBaseClasses.size(); b++)
{
COMPARE_METADATA_STRING_MD(PxMetaDataEntry, mcSrc->mBaseClasses[b], mcDst->mBaseClasses[b], mName);
}
}
COMPARE_METADATA_INT_MD(MetaClass, *mcSrc, *mcDst, mFields.size())
if (mcSrc->mFields.size() == mcDst->mFields.size())
{
for (PxU32 f = 0; f < mcSrc->mFields.size(); f++)
{
PxMetaDataEntry srcMde = mcSrc->mFields[f];
PxMetaDataEntry dstMde = mcDst->mFields[f];
COMPARE_METADATA_STRING_MD(PxMetaDataEntry, srcMde, dstMde, mType)
COMPARE_METADATA_STRING_MD(PxMetaDataEntry, srcMde, dstMde, mName)
COMPARE_METADATA_INT_MD(PxMetaDataEntry, srcMde, dstMde, mOffset)
COMPARE_METADATA_INT_MD(PxMetaDataEntry, srcMde, dstMde, mSize)
COMPARE_METADATA_INT_MD(PxMetaDataEntry, srcMde, dstMde, mCount)
COMPARE_METADATA_INT_MD(PxMetaDataEntry, srcMde, dstMde, mOffsetSize)
COMPARE_METADATA_INT_MD(PxMetaDataEntry, srcMde, dstMde, mFlags)
COMPARE_METADATA_INT_MD(PxMetaDataEntry, srcMde, dstMde, mAlignment)
}
}
}
}
return isEquivalent;
}
#undef COMPARE_METADATA_BOOL_MD
#undef COMPARE_METADATA_INT_MD
#undef COMPARE_METADATA_STRING_MD
///////////////////////////////////////////////////////////////////////////////
void ConvX::releaseMetaData()
{
PX_DELETE(mMetaData_Dst);
PX_DELETE(mMetaData_Src);
}
const MetaData* ConvX::loadMetaData(PxInputStream& inputStream, MetaDataType type)
{
if (type != META_DATA_SRC && type != META_DATA_DST)
{
displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: Wrong meta data type, please check the source metadata.\n");
return NULL;
}
PX_ASSERT(type == META_DATA_SRC || type == META_DATA_DST);
MetaData*& metaDataPtr = (type == META_DATA_SRC) ? mMetaData_Src : mMetaData_Dst;
metaDataPtr = PX_NEW(MetaData)(*this);
if(!(metaDataPtr)->load(inputStream, type))
PX_DELETE(metaDataPtr);
return metaDataPtr;
}
const MetaData* ConvX::getBinaryMetaData(MetaDataType type)
{
if(type==META_DATA_SRC)
return mMetaData_Src;
if(type==META_DATA_DST)
return mMetaData_Dst;
PX_ASSERT(0);
return NULL;
}
int ConvX::getNbMetaClasses(MetaDataType type)
{
if(type==META_DATA_SRC)
return mMetaData_Src->getNbMetaClasses();
if(type==META_DATA_DST)
return mMetaData_Dst->getNbMetaClasses();
PX_ASSERT(0);
return 0;
}
MetaClass* ConvX::getMetaClass(unsigned int i, MetaDataType type) const
{
if(type==META_DATA_SRC)
return mMetaData_Src->getMetaClass(i);
if(type==META_DATA_DST)
return mMetaData_Dst->getMetaClass(i);
PX_ASSERT(0);
return NULL;
}
MetaClass* ConvX::getMetaClass(const char* name, MetaDataType type) const
{
if(type==META_DATA_SRC)
return mMetaData_Src->getMetaClass(name);
if(type==META_DATA_DST)
return mMetaData_Dst->getMetaClass(name);
PX_ASSERT(0);
return NULL;
}
MetaClass* ConvX::getMetaClass(PxConcreteType::Enum concreteType, MetaDataType type)
{
MetaClass* metaClass = NULL;
if(type==META_DATA_SRC)
metaClass = mMetaData_Src->getMetaClass(concreteType);
if(type==META_DATA_DST)
metaClass = mMetaData_Dst->getMetaClass(concreteType);
if(!metaClass)
{
displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: Missing concreteType %d metadata! serialized a class without dumping metadata. Please check the metadata.",
concreteType);
return NULL;
}
return metaClass;
}
///////////////////////////////////////////////////////////////////////////////
// Peek & poke, yes sir.
PxU64 physx::Sn::peek(int size, const char* buffer, int flags)
{
const int maskMSB = flags & PxMetaDataFlag::eCOUNT_MASK_MSB;
const int skipIfOne = flags & PxMetaDataFlag::eCOUNT_SKIP_IF_ONE;
switch(size)
{
case 1:
{
unsigned char value = *(reinterpret_cast<const unsigned char*>(buffer));
if(maskMSB)
value &= 0x7f;
if(skipIfOne && value==1)
return 0;
return PxU64(value);
}
case 2:
{
unsigned short value = *(reinterpret_cast<const unsigned short*>(buffer));
if(maskMSB)
value &= 0x7fff;
if(skipIfOne && value==1)
return 0;
return PxU64(value);
}
case 4:
{
unsigned int value = *(reinterpret_cast<const unsigned int*>(buffer));
if(maskMSB)
value &= 0x7fffffff;
if(skipIfOne && value==1)
return 0;
return PxU64(value);
}
case 8:
{
PxU64 value = *(reinterpret_cast<const PxU64*>(buffer));
if(maskMSB)
value &= (PxU64(-1))>>1;
if(skipIfOne && value==1)
return 0;
return value;
}
};
PX_ASSERT(0);
return PxU64(-1);
}
| 27,508 | C++ | 27.83543 | 183 | 0.672132 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Output.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 SN_CONVX_OUTPUT_H
#define SN_CONVX_OUTPUT_H
#include "foundation/PxSimpleTypes.h"
namespace physx { namespace Sn {
struct PxMetaDataEntry;
class ConvX;
typedef void (Sn::ConvX::*ConvertCallback) (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
inline_ void flip(PxI16& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
PxI8 temp = b[0];
b[0] = b[1];
b[1] = temp;
}
inline_ void flip(PxU16& v)
{
flip(reinterpret_cast<PxI16&>(v));
}
inline_ void flip32(PxI8* b)
{
PxI8 temp = b[0];
b[0] = b[3];
b[3] = temp;
temp = b[1];
b[1] = b[2];
b[2] = temp;
}
inline_ void flip(PxI32& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
flip32(b);
}
inline_ void flip(PxU32& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
flip32(b);
}
inline_ void flip(PxI64& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
PxI8 temp = b[0];
b[0] = b[7];
b[7] = temp;
temp = b[1];
b[1] = b[6];
b[6] = temp;
temp = b[2];
b[2] = b[5];
b[5] = temp;
temp = b[3];
b[3] = b[4];
b[4] = temp;
}
inline_ void flip(PxF32& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
flip32(b);
}
inline_ void flip(void*& v)
{
PxI8* b = reinterpret_cast<PxI8*>(&v);
flip32(b);
}
inline_ void flip(const PxI8*& v)
{
PxI8* b = const_cast<PxI8*>(v);
flip32(b);
}
} }
#endif
| 2,914 | C | 25.026785 | 125 | 0.675704 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Convert.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/PxErrorCallback.h"
#include "extensions/PxDefaultStreams.h"
#include "SnConvX.h"
#include "serialization/SnSerialUtils.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxString.h"
#include "CmUtils.h"
#include <assert.h>
using namespace physx;
using namespace physx::Sn;
using namespace Cm;
void Sn::ConvX::resetConvexFlags()
{
mConvexFlags.clear();
}
void Sn::ConvX::_enumerateFields(const MetaClass* mc, ExtraDataEntry2* entries, int& nb, int baseOffset, MetaDataType type) const
{
PxU32 nbFields = mc->mFields.size();
int offsetCheck = baseOffset;
PX_UNUSED(offsetCheck);
for(PxU32 j=0;j<nbFields;j++)
{
const PxMetaDataEntry& entry = mc->mFields[j];
if(entry.mFlags & PxMetaDataFlag::eCLASS || entry.mFlags & PxMetaDataFlag::eEXTRA_DATA)
continue;
assert(offsetCheck == baseOffset + entry.mOffset);
int currentOffset = baseOffset + entry.mOffset;
//for(int c=0;c<entry.mCount;c++)
{
if(entry.mFlags & PxMetaDataFlag::eUNION)
{
entries[nb].entry = entry;
entries[nb].offset = currentOffset;
entries[nb].cb = 0;
nb++;
}
else if(entry.mFlags & PxMetaDataFlag::ePTR) // This also takes care of the vtable pointer
{
entries[nb].entry = entry;
entries[nb].offset = currentOffset;
entries[nb].cb = &Sn::ConvX::convertPtr;
nb++;
}
else if(entry.mFlags & PxMetaDataFlag::eHANDLE)
{
entries[nb].entry = entry;
entries[nb].offset = currentOffset;
entries[nb].cb = &Sn::ConvX::convertHandle16;
nb++;
}
else
{
MetaClass* fieldType = getMetaClass(entry.mType, type);
assert(fieldType);
if(fieldType->mCallback)
{
entries[nb].entry = entry;
entries[nb].offset = currentOffset;
entries[nb].cb = fieldType->mCallback;
nb++;
}
else
{
for(int c=0;c<entry.mCount;c++)
{
_enumerateFields(fieldType, entries, nb, currentOffset, type);
currentOffset += entry.mSize/entry.mCount;
}
}
}
}
offsetCheck += entry.mSize;
}
}
void Sn::ConvX::_enumerateExtraData(const char* address, const MetaClass* mc, ExtraDataEntry* entries,
int& nb, int offset, MetaDataType type) const
{
PxU32 nbFields = mc->mFields.size();
for(PxU32 j=0;j<nbFields;j++)
{
const PxMetaDataEntry& entry = mc->mFields[j];
if(entry.mFlags & PxMetaDataFlag::eCLASS /*|| entry.mFlags & PxMetaDataFlag::ePTR*/ || entry.mFlags & PxMetaDataFlag::eTYPEDEF)
continue;
const char* entryType = entry.mType;
//
// Insanely Twisted Shadow GeometryUnion
//
// Special code is needed as long as there are no meta data tags to describe our unions properly. The way it is done here is
// not future-proof at all. There should be a tag to describe where the union type can be found and the number of bytes
// this type id needs. Then a mapping needs to get added from each union type id to the proper meta class name.
//
if (entry.mFlags & PxMetaDataFlag::eUNION)
{
if (!mc->mClassName || Pxstrcmp(mc->mClassName, "GeometryUnion")!=0)
continue;
else
{
// ### hardcoded bit here, will only work when union type is the first int of the struct
const int* tmp = reinterpret_cast<const int*>(address + offset);
const int unionType = *tmp;
ConvX* tmpConv = const_cast<ConvX*>(this); // ... don't ask
const char* typeName = tmpConv->getTypeName(entry.mType, unionType);
assert(typeName);
bool isTriMesh = (Pxstrcmp(typeName, "PxTriangleMeshGeometryLL") == 0);
bool isHeightField = (Pxstrcmp(typeName, "PxHeightFieldGeometryLL") == 0);
if (!isTriMesh && !isHeightField)
{
continue;
}
else
{
entryType = typeName;
}
}
}
// MetaClass* extraDataType = getMetaClass(entry.mType, type);
// if(!extraDataType)
// continue;
if(entry.mFlags & PxMetaDataFlag::eEXTRA_DATA)
{
entries[nb].entry = entry;
entries[nb].offset = offset+entry.mOffset;
nb++;
}
else
{
if(entry.mFlags & PxMetaDataFlag::ePTR)
continue;
MetaClass* extraDataType = getMetaClass(entryType, type);
if(!extraDataType)
continue;
if(!extraDataType->mCallback)
_enumerateExtraData(address, extraDataType, entries, nb, offset+entry.mOffset, type);
}
}
}
PxU64 Sn::ConvX::read64(const void*& buffer)
{
const PxU64* buf64 = reinterpret_cast<const PxU64*>(buffer);
buffer = reinterpret_cast<const void*>(size_t(buffer) + sizeof(PxU64));
PxU64 value = *buf64;
output(value);
return value;
}
int Sn::ConvX::read32(const void*& buffer)
{
const int* buf32 = reinterpret_cast<const int*>(buffer);
buffer = reinterpret_cast<const void*>(size_t(buffer) + sizeof(int));
int value = *buf32;
output(value);
return value;
}
short Sn::ConvX::read16(const void*& buffer)
{
const short* buf16 = reinterpret_cast<const short*>(buffer);
buffer = reinterpret_cast<const void*>(size_t(buffer) + sizeof(short));
short value = *buf16;
output(value);
return value;
}
#if PX_CHECKED
extern const char* gVTable;
static bool compareEntries(const ExtraDataEntry2& e0, const ExtraDataEntry2& e1)
{
if(e0.entry.isVTablePtr() && e1.entry.isVTablePtr())
return true;
if((e0.entry.mFlags & PxMetaDataFlag::eUNION) && (e1.entry.mFlags & PxMetaDataFlag::eUNION))
{
if(e0.entry.mType && e1.entry.mType)
{
// We can't compare the ptrs since they index different string tables
if(Pxstrcmp(e0.entry.mType, e1.entry.mType)==0)
return true;
}
return false;
}
if(e0.entry.mName && e1.entry.mName)
{
// We can't compare the ptrs since they index different string tables
if(Pxstrcmp(e0.entry.mName, e1.entry.mName)==0)
return true;
}
return false;
}
#endif
// TODO: optimize this
bool Sn::ConvX::convertClass(const char* buffer, const MetaClass* mc, int offset)
{
// ---- big convex surgery ----
bool convexSurgery = false;
bool foundNbVerts = false;
bool removeBigData = false;
// force reference
(void)foundNbVerts;
displayMessage(PxErrorCode::eDEBUG_INFO, "%s\n", mc->mClassName);
displayMessage(PxErrorCode::eDEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++\n");
if(Pxstrcmp(mc->mClassName, "ConvexMesh")==0)
{
convexSurgery = true;
}
// ---- big convex surgery ----
int nbSrcEntries = 0;
PX_ALLOCA(srcEntries, ExtraDataEntry2, 256); // ### painful ctors here
int nbDstEntries = 0;
PX_ALLOCA(dstEntries, ExtraDataEntry2, 256); // ### painful ctors here
// Find corresponding meta-class for target platform
const MetaClass* target_mc = getMetaClass(mc->mClassName, META_DATA_DST);
assert(target_mc);
if(mc->mCallback)
{
srcEntries[0].cb = mc->mCallback;
srcEntries[0].offset = offset;
srcEntries[0].entry.mType = mc->mClassName;
srcEntries[0].entry.mName = mc->mClassName;
srcEntries[0].entry.mOffset = offset;
srcEntries[0].entry.mSize = mc->mSize;
srcEntries[0].entry.mCount = 1;
srcEntries[0].entry.mFlags = 0;
nbSrcEntries = 1;
assert(target_mc->mCallback);
dstEntries[0].cb = target_mc->mCallback;
dstEntries[0].offset = offset;
dstEntries[0].entry.mType = target_mc->mClassName;
dstEntries[0].entry.mName = target_mc->mClassName;
dstEntries[0].entry.mOffset = offset;
dstEntries[0].entry.mSize = target_mc->mSize;
dstEntries[0].entry.mCount = 1;
dstEntries[0].entry.mFlags = 0;
nbDstEntries = 1;
}
else
{
nbSrcEntries = 0;
_enumerateFields(mc, srcEntries, nbSrcEntries, 0, META_DATA_SRC);
assert(nbSrcEntries<256);
nbDstEntries = 0;
_enumerateFields(target_mc, dstEntries, nbDstEntries, 0, META_DATA_DST);
assert(nbDstEntries<256);
// nb = mc->mNbEntries;
// assert(nb>=0);
// memcpy(entries, mc->mEntries, nb*sizeof(ExtraDataEntry2));
}
int srcOffsetCheck = 0;
int dstOffsetCheck = 0;
PX_UNUSED(dstOffsetCheck);
int j = 0;
// Track cases where the vtable pointer location is different for different platforms.
// The variables indicate whether a platform has a vtable pointer entry that has not been converted yet
// and they will remember the index of the corrssponding entry. This works because there can only
// be one open vtable pointer entry at a time.
int srcOpenVTablePtrEntry = -1;
int dstOpenVTablePtrEntry = -1;
//if the src and dst platform place the vtable pointers at different locations some fiddling with the iteration count can be necessary.
int addVTablePtrShiftIteration = 0;
const int maxNb = nbSrcEntries > nbDstEntries ? nbSrcEntries : nbDstEntries;
for(int i=0; i < (maxNb + addVTablePtrShiftIteration); i++)
{
if (i < nbSrcEntries)
{
displayMessage(PxErrorCode::eDEBUG_INFO, "\t0x%p\t%02x\t%d\t%d\t%s", buffer + srcOffsetCheck,
static_cast<unsigned char>(buffer[srcOffsetCheck]), srcOffsetCheck, srcEntries[i].entry.mOffset, srcEntries[i].entry.mName);
for (int byteCount = 1; byteCount < srcEntries[i].entry.mSize; ++byteCount)
displayMessage(PxErrorCode::eDEBUG_INFO, "\t0x%p\t%02x\t%d\t%d\t.", buffer + srcOffsetCheck + byteCount,
static_cast<unsigned char>(buffer[srcOffsetCheck + byteCount]), srcOffsetCheck + byteCount, srcEntries[i].entry.mOffset + byteCount);
}
bool handlePadding = true;
bool skipLoop = false;
while(handlePadding)
{
const int pad0 = i<nbSrcEntries ? srcEntries[i].entry.mFlags & PxMetaDataFlag::ePADDING : 0;
const int pad1 = j<nbDstEntries ? dstEntries[j].entry.mFlags & PxMetaDataFlag::ePADDING : 0;
if(pad0 || pad1)
{
if(pad0)
{
#if PX_CHECKED
if (mMarkedPadding && (Pxstrcmp(srcEntries[i].entry.mType, "paddingByte")==0))
if(!checkPaddingBytes(buffer + srcOffsetCheck, srcEntries[i].entry.mSize))
{
if(i>0)
{
displayMessage(PxErrorCode::eDEBUG_WARNING,
"PxBinaryConverter warning: Bytes after %s::%s don't look like padding bytes. Likely mismatch between binary data and metadata.\n",
mc->mClassName, srcEntries[i-1].entry.mName );
}
else
displayMessage(PxErrorCode::eDEBUG_WARNING,
"PxBinaryConverter warning: Bytes after %s don't look like padding bytes. Likely mismatch between binary data and metadata.\n",
mc->mClassName);
}
#endif
if(pad1)
{
// Both have padding
// ### check sizes, output bytes
if(srcEntries[i].entry.mSize==dstEntries[j].entry.mSize)
{
// I guess we can just go on with the normal code here
handlePadding = false;
}
else
{
// Output padding
assert(srcEntries[i].cb);
assert(srcEntries[i].offset == srcOffsetCheck);
const int padSize = dstEntries[j].entry.mSize;
char* paddingBytes = reinterpret_cast<char*>(PX_ALLOC(sizeof(char)*padSize, "paddingByte"));
memset(paddingBytes, 0, size_t(padSize));
assert(dstEntries[j].cb);
(this->*dstEntries[j].cb)(paddingBytes, dstEntries[j].entry, dstEntries[j].entry);
assert(dstOffsetCheck==dstEntries[j].offset);
dstOffsetCheck += padSize;
PX_FREE(paddingBytes);
// srcEntries[i].cb(buffer+srcOffsetCheck, srcEntries[i].entry, dstEntries[j].entry);
// assert(dstOffsetCheck==dstEntries[j].offset);
// dstOffsetCheck += dstEntries[j].entry.mSize;
srcOffsetCheck += srcEntries[i].entry.mSize;
// Skip dest padding field
j++;
// continue; // ### BUG, doesn't go back to the "for"
skipLoop = true;
handlePadding = false;
}
}
else
{
// Src has padding, dst has not => skip conversion
// Don't increase j
skipLoop = true;
handlePadding = false;
srcOffsetCheck += srcEntries[i].entry.mSize;
}
}
else
{
if(pad1)
{
// Dst has padding, src has not
// Output padding
const int padSize = dstEntries[j].entry.mSize;
char* paddingBytes = reinterpret_cast<char*>(PX_ALLOC(sizeof(char)*padSize, "paddingByte"));
memset(paddingBytes, 0, size_t(padSize));
assert(dstEntries[j].cb);
(this->*dstEntries[j].cb)(paddingBytes, dstEntries[j].entry, dstEntries[j].entry);
assert(dstOffsetCheck==dstEntries[j].offset);
dstOffsetCheck += padSize;
PX_FREE(paddingBytes);
// Skip dest padding field, keep same src field
j++;
}
else
{
assert(0);
}
}
}
else handlePadding = false;
}
if(skipLoop)
continue;
int modSrcOffsetCheck = srcOffsetCheck;
const ExtraDataEntry2* srcEntryPtr = &srcEntries[i];
const ExtraDataEntry2* dstEntryPtr = &dstEntries[j];
bool isSrcVTablePtr = (i < nbSrcEntries) ? srcEntryPtr->entry.isVTablePtr() : false;
if (isSrcVTablePtr && (dstOpenVTablePtrEntry != -1))
{
// vtable ptr position mismatch:
// this check is necessary to align src and dst index again when the
// dst vtable pointer has been written already and the src vtable ptr
// element is reached.
//
// i
// src: | a | b | vt-ptr | c | ...
// dst: | vt-ptr | a | b | c | ...
// j
//
// it needs special treatment because the following case fails otherwise
// i
// src: | a | b | vt-ptr | c | vt-ptr | ...
// dst: | vt-ptr | a | b | vt-ptr | c | ...
// j
//
// This entry has been written already -> advance to next src entry
//
srcOffsetCheck += srcEntryPtr->entry.mSize;
i++;
isSrcVTablePtr = (i < nbSrcEntries) ? srcEntryPtr->entry.isVTablePtr() : false;
PX_ASSERT(dstOpenVTablePtrEntry < nbDstEntries);
PX_ASSERT(dstEntries[dstOpenVTablePtrEntry].entry.isVTablePtr());
dstOpenVTablePtrEntry = -1;
PX_ASSERT(addVTablePtrShiftIteration == 0);
}
bool isDstVTablePtr = (j < nbDstEntries) ? dstEntryPtr->entry.isVTablePtr() : false;
if (isDstVTablePtr && (srcOpenVTablePtrEntry != -1))
{
// i
// src: | vt-ptr | a | b | c | ...
// dst: | a | b | vt-ptr | c | ...
// j
i--; // next iteration the current element should get processed
isSrcVTablePtr = true;
PX_ASSERT(srcOpenVTablePtrEntry < nbSrcEntries);
srcEntryPtr = &srcEntries[srcOpenVTablePtrEntry];
PX_ASSERT(srcEntryPtr->entry.isVTablePtr());
modSrcOffsetCheck = srcEntryPtr->offset;
srcOffsetCheck -= srcEntryPtr->entry.mSize; // to make sure total change is 0 after this iteration
srcOpenVTablePtrEntry = -1;
PX_ASSERT(addVTablePtrShiftIteration == 1);
addVTablePtrShiftIteration = 0;
}
if(i==nbSrcEntries && j==nbDstEntries)
{
PX_ASSERT((srcOpenVTablePtrEntry == -1) && (dstOpenVTablePtrEntry == -1));
break;
}
if (isSrcVTablePtr || isDstVTablePtr)
{
if (!isSrcVTablePtr)
{
// i
// src: | a | b | vt-ptr | c | ...
// dst: | vt-ptr | a | b | c | ...
// j
PX_ASSERT(dstOpenVTablePtrEntry == -1); // the other case should be detected and treated earlier
PX_ASSERT(srcOpenVTablePtrEntry == -1);
PX_ASSERT(addVTablePtrShiftIteration == 0);
int k;
for(k=i+1; k < nbSrcEntries; k++)
{
if (srcEntries[k].entry.isVTablePtr())
break;
}
PX_ASSERT(k < nbSrcEntries);
srcEntryPtr = &srcEntries[k];
modSrcOffsetCheck = srcEntryPtr->offset;
srcOffsetCheck -= srcEntryPtr->entry.mSize; // to make sure total change is 0 after this iteration
dstOpenVTablePtrEntry = j;
i--; // to make sure the original entry gets processed in the next iteration
}
else if (!isDstVTablePtr)
{
// i ---> i
// src: | vt-ptr | a | b | c | ...
// dst: | a | b | vt-ptr | c | ...
// j
PX_ASSERT(srcOpenVTablePtrEntry == -1); // the other case should be detected and treated earlier
PX_ASSERT(dstOpenVTablePtrEntry == -1);
PX_ASSERT(addVTablePtrShiftIteration == 0);
srcOffsetCheck += srcEntryPtr->entry.mSize;
modSrcOffsetCheck = srcOffsetCheck;
srcOpenVTablePtrEntry = i;
i++;
srcEntryPtr = &srcEntries[i];
addVTablePtrShiftIteration = 1; // additional iteration might be needed to process vtable pointer at the end of a class
PX_ASSERT((i < nbSrcEntries) && ((srcEntryPtr->entry.mFlags & PxMetaDataFlag::ePADDING) == 0));
// if the second check fails, this whole section might have to be done before the padding bytes get processed. Not sure
// what other consequences that might have though.
}
}
#if PX_CHECKED
else
{
if(!compareEntries(*srcEntryPtr, *dstEntryPtr))
{
displayMessage(PxErrorCode::eINVALID_PARAMETER, "\rConvX::convertClass: %s, src meta data and dst meta data don't match!", mc->mClassName);
return false;
}
}
#endif
const ExtraDataEntry2& srcEntry = *srcEntryPtr;
const ExtraDataEntry2& dstEntry = *dstEntryPtr;
if(srcEntry.entry.mFlags & PxMetaDataFlag::eUNION)
{
// ### hardcoded bit here, will only work when union type is the first int of the struct
const int* tmp = reinterpret_cast<const int*>(buffer + modSrcOffsetCheck);
const int unionType = *tmp;
const char* typeName = getTypeName(srcEntry.entry.mType, unionType);
assert(typeName);
MetaClass* unionMC = getMetaClass(typeName, META_DATA_SRC);
assert(unionMC);
convertClass(buffer + modSrcOffsetCheck, unionMC, 0); // ### recurse
dstOffsetCheck += dstEntry.entry.mSize;
MetaClass* targetUnionMC = getMetaClass(typeName, META_DATA_DST);
assert(targetUnionMC);
const int delta = dstEntry.entry.mSize - targetUnionMC->mSize;
char* deltaBytes = reinterpret_cast<char*>(PX_ALLOC(sizeof(char)*delta, "deltaBytes"));
memset(deltaBytes, 0, size_t(delta));
output(deltaBytes, delta); // Skip unused bytes at the end of the union
PX_FREE(deltaBytes);
srcOffsetCheck += srcEntry.entry.mSize; // do not use modSrcOffsetCheck here!
}
else
{
assert(srcEntry.cb);
assert(srcEntry.offset == modSrcOffsetCheck);
// ---- big convex surgery ----
if(convexSurgery)
{
if(Pxstrcmp(srcEntry.entry.mName, "mNbHullVertices")==0)
{
assert(srcEntry.entry.mSize==1);
const PxU8 nbVerts = static_cast<PxU8>(*(buffer+modSrcOffsetCheck));
assert(!foundNbVerts);
foundNbVerts = true;
const PxU8 gaussMapLimit = static_cast<PxU8>(getBinaryMetaData(META_DATA_DST)->getGaussMapLimit());
if(nbVerts > gaussMapLimit)
{
// We need a gauss map and we have one => keep it
}
else
{
// We don't need a gauss map and we have one => remove it
removeBigData = true;
}
}
else
{
if(removeBigData)
{
const bool isBigConvexData = Pxstrcmp(srcEntry.entry.mType, "BigConvexData")==0 ||
Pxstrcmp(srcEntry.entry.mType, "BigConvexRawData")==0;
if(isBigConvexData)
{
assert(foundNbVerts);
setNullPtr(true);
}
}
}
}
// ---- big convex surgery ----
(this->*srcEntry.cb)(buffer+modSrcOffsetCheck, srcEntry.entry, dstEntry.entry);
assert(dstOffsetCheck==dstEntry.offset);
dstOffsetCheck += dstEntry.entry.mSize;
srcOffsetCheck += srcEntry.entry.mSize; // do not use modSrcOffsetCheck here!
// ---- big convex surgery ----
if(convexSurgery && removeBigData)
setNullPtr(false);
// ---- big convex surgery ----
}
j++;
}
displayMessage(PxErrorCode::eDEBUG_INFO, "---------------------------------------------\n");
while(j<nbDstEntries)
{
assert(dstEntries[j].entry.mFlags & PxMetaDataFlag::ePADDING);
if(dstEntries[j].entry.mFlags & PxMetaDataFlag::ePADDING)
{
dstOffsetCheck += dstEntries[j].entry.mSize;
}
j++;
}
assert(j==nbDstEntries);
assert(dstOffsetCheck==target_mc->mSize);
assert(srcOffsetCheck==mc->mSize);
// ---- big convex surgery ----
if(convexSurgery)
mConvexFlags.pushBack(removeBigData);
// ---- big convex surgery ----
return true;
}
// Handles data defined with PX_DEF_BIN_METADATA_EXTRA_ARRAY
const char* Sn::ConvX::convertExtraData_Array(const char* Address, const char* lastAddress, const char* objectAddress,
const ExtraDataEntry& ed)
{
(void)lastAddress;
MetaClass* mc = getMetaClass(ed.entry.mType, META_DATA_SRC);
assert(mc);
// PT: safe to cast to int here since we're reading a count.
const int count = int(peek(ed.entry.mSize, objectAddress + ed.offset, ed.entry.mFlags));
// if(ed.entry.mCount) // Reused as align value
if(ed.entry.mAlignment)
{
Address = alignStream(Address, ed.entry.mAlignment);
// Address = alignStream(Address, ed.entry.mCount);
assert(Address<=lastAddress);
}
for(int c=0;c<count;c++)
{
convertClass(Address, mc, 0);
Address += mc->mSize;
assert(Address<=lastAddress);
}
return Address;
}
const char* Sn::ConvX::convertExtraData_Ptr(const char* Address, const char* lastAddress, const PxMetaDataEntry& entry, int count,
int ptrSize_Src, int ptrSize_Dst)
{
(void)lastAddress;
PxMetaDataEntry tmpSrc = entry;
tmpSrc.mCount = count;
tmpSrc.mSize = count * ptrSize_Src;
PxMetaDataEntry tmpDst = entry;
tmpDst.mCount = count;
tmpDst.mSize = count * ptrSize_Dst;
displayMessage(PxErrorCode::eDEBUG_INFO, "extra data ptrs\n");
displayMessage(PxErrorCode::eDEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++\n");
displayMessage(PxErrorCode::eDEBUG_INFO, "\t0x%p\t%02x\t\t\t%s", Address, static_cast<unsigned char>(Address[0]), entry.mName);
for (int byteCount = 1; byteCount < ptrSize_Src*count; ++byteCount)
displayMessage(PxErrorCode::eDEBUG_INFO, "\t0x%p\t%02x\t\t\t.", Address + byteCount, static_cast<unsigned char>(Address[byteCount]));
convertPtr(Address, tmpSrc, tmpDst);
Address += count * ptrSize_Src;
assert(Address<=lastAddress);
return Address;
}
const char* Sn::ConvX::convertExtraData_Handle(const char* Address, const char* lastAddress, const PxMetaDataEntry& entry, int count)
{
(void)lastAddress;
MetaClass* fieldType = getMetaClass(entry.mType, META_DATA_SRC);
int typeSize = fieldType->mSize;
PxMetaDataEntry tmpSrc = entry;
tmpSrc.mCount = count;
tmpSrc.mSize = count*typeSize;
PxMetaDataEntry tmpDst = entry;
tmpDst.mCount = count;
tmpDst.mSize = count*typeSize;
displayMessage(PxErrorCode::eDEBUG_INFO, "extra data handles\n");
displayMessage(PxErrorCode::eDEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++\n");
displayMessage(PxErrorCode::eDEBUG_INFO, "\t0x%p\t%02x\t\t\t%s", Address, static_cast<unsigned char>(Address[0]), entry.mName);
for (int byteCount = 1; byteCount < tmpSrc.mSize; ++byteCount)
displayMessage(PxErrorCode::eDEBUG_INFO, "\t0x%p\t%02x\t\t\t.", Address + byteCount, static_cast<unsigned char>(Address[byteCount]));
convertHandle16(Address, tmpSrc, tmpDst);
Address += count*typeSize;
assert(Address<=lastAddress);
return Address;
}
static bool decodeControl(PxU64 control, const ExtraDataEntry& ed, PxU64 controlMask = 0)
{
if(ed.entry.mFlags & PxMetaDataFlag::eCONTROL_FLIP)
{
if(controlMask)
{
return (control & controlMask) ? false : true;
}
else
{
return control==0;
}
}
else
{
if(controlMask)
{
return (control & controlMask) ? true : false;
}
else
{
return control!=0;
}
}
}
// ### currently hardcoded, should change
int Sn::ConvX::getConcreteType(const char* buffer)
{
MetaClass* mc = getMetaClass("PxBase", META_DATA_SRC);
assert(mc);
PxMetaDataEntry entry;
if(mc->getFieldByType("PxType", entry))
{
// PT: safe to cast to int here since we're reading our own PxType
return int(peek(entry.mSize, buffer + entry.mOffset));
}
assert(0);
return 0xffffffff;
}
struct Item : public PxUserAllocated
{
MetaClass* mc;
const char* address;
};
bool Sn::ConvX::convertCollection(const void* buffer, int fileSize, int nbObjects)
{
const char* lastAddress = reinterpret_cast<const char*>(buffer) + fileSize;
const char* Address = alignStream(reinterpret_cast<const char*>(buffer));
const int ptrSize_Src = mSrcPtrSize;
const int ptrSize_Dst = mDstPtrSize;
Item* objects = PX_NEW(Item)[PxU32(nbObjects)];
for(PxU32 i=0;i<PxU32(nbObjects);i++)
{
const float percents = float(i)/float(nbObjects);
displayMessage(PxErrorCode::eDEBUG_INFO, "Object conversion: %d%%", int(percents*100.0f));
Address = alignStream(Address);
assert(Address<=lastAddress);
PxConcreteType::Enum classType = PxConcreteType::Enum(getConcreteType(Address));
MetaClass* metaClass = getMetaClass(classType, META_DATA_SRC);
if(!metaClass)
{
PX_DELETE_ARRAY(objects);
return false;
}
objects[i].mc = metaClass;
objects[i].address = Address;
if(!convertClass(Address, metaClass, 0))
{
PX_DELETE_ARRAY(objects);
return false;
}
Address += metaClass->mSize;
assert(Address<=lastAddress);
}
// Fields / extra data
if(1)
{
// ---- big convex surgery ----
unsigned int nbConvexes = 0;
// ---- big convex surgery ----
//const char* StartAddress2 = Address;
//int startDstSize2 = getCurrentOutputSize();
for(int i=0;i<nbObjects;i++)
{
//const char* StartAddress = Address;
//int startDstSize = getCurrentOutputSize();
const float percents = float(i)/float(nbObjects);
displayMessage(PxErrorCode::eDEBUG_INFO, "Extra data conversion: %d%%", int(percents*100.0f));
MetaClass* mc0 = objects[i].mc;
const char* objectAddress = objects[i].address;
// printf("%d: %s\n", i, mc->mClassName);
// if(strcmp(mc->mClassName, "TriangleMesh")==0)
// if(strcmp(mc->mClassName, "NpRigidDynamic")==0)
if(Pxstrcmp(mc0->mClassName, "HybridModel")==0)
{
int stop=1;
(void)(stop);
}
// ### we actually need to collect all extra data for this class, including data from embedded members.
PX_ALLOCA(entries, ExtraDataEntry, 256);
int nbEntries = 0;
_enumerateExtraData(objectAddress, mc0, entries, nbEntries, 0, META_DATA_SRC);
assert(nbEntries<256);
Address = alignStream(Address);
assert(Address<=lastAddress);
for(int j=0;j<nbEntries;j++)
{
const ExtraDataEntry& ed = entries[j];
assert(ed.entry.mFlags & PxMetaDataFlag::eEXTRA_DATA);
if(ed.entry.mFlags & PxMetaDataFlag::eEXTRA_ITEM)
{
// ---- big convex surgery ----
if(1)
{
const bool isBigConvexData = Pxstrcmp(ed.entry.mType, "BigConvexData")==0;
if(isBigConvexData)
{
assert(nbConvexes<mConvexFlags.size());
if(mConvexFlags[nbConvexes++])
setNoOutput(true);
}
}
// ---- big convex surgery ----
MetaClass* extraDataType = getMetaClass(ed.entry.mType, META_DATA_SRC);
assert(extraDataType);
//sschirm: we used to have ed.entry.mOffset here, but that made cloth deserialization fail. - sschirm: cloth is gone now...
const char* controlAddress = objectAddress + ed.offset;
const PxU64 controlValue = peek(ed.entry.mOffsetSize, controlAddress);
if(controlValue)
{
if(ed.entry.mAlignment)
{
Address = alignStream(Address, ed.entry.mAlignment);
assert(Address<=lastAddress);
}
const char* classAddress = Address;
convertClass(Address, extraDataType, 0);
Address += extraDataType->mSize;
assert(Address<=lastAddress);
// Enumerate extra data for this optional class, and convert it too.
// This assumes the extra data for the optional class is always appended to the class itself,
// which is something we'll need to enforce in the SDK. So far this is only to handle optional
// inline arrays.
// ### this should probably be recursive eventually
PX_ALLOCA(entries2, ExtraDataEntry, 256);
int nbEntries2 = 0;
_enumerateExtraData(objectAddress, extraDataType, entries2, nbEntries2, 0, META_DATA_SRC);
assert(nbEntries2<256);
for(int k=0;k<nbEntries2;k++)
{
const ExtraDataEntry& ed2 = entries2[k];
assert(ed2.entry.mFlags & PxMetaDataFlag::eEXTRA_DATA);
if(ed2.entry.mFlags & PxMetaDataFlag::eEXTRA_ITEMS)
{
const int controlOffset = ed2.entry.mOffset;
const int controlSize = ed2.entry.mSize;
const int countOffset = ed2.entry.mCount;
const int countSize = ed2.entry.mOffsetSize;
const PxU64 controlValue2 = peek(controlSize, classAddress + controlOffset);
PxU64 controlMask = 0;
if(ed2.entry.mFlags & PxMetaDataFlag::eCONTROL_MASK)
{
controlMask = PxU64(ed2.entry.mFlags & (PxMetaDataFlag::eCONTROL_MASK_RANGE << 16));
controlMask = controlMask >> 16;
}
if(decodeControl(controlValue2, ed2, controlMask))
{
// PT: safe to cast to int here since we're reading a count
int count = int(peek(countSize, classAddress + countOffset, ed2.entry.mFlags));
if(ed2.entry.mAlignment)
{
assert(0); // Never tested
Address = alignStream(Address, ed2.entry.mAlignment);
assert(Address<=lastAddress);
}
if(ed2.entry.mFlags & PxMetaDataFlag::ePTR)
{
assert(0); // Never tested
}
else
{
MetaClass* mc = getMetaClass(ed2.entry.mType, META_DATA_SRC);
assert(mc);
while(count--)
{
convertClass(Address, mc, 0);
Address += mc->mSize;
assert(Address<=lastAddress);
}
}
}
}
else
{
if( (ed2.entry.mFlags & PxMetaDataFlag::eALIGNMENT) && ed2.entry.mAlignment)
{
Address = alignStream(Address, ed2.entry.mAlignment);
assert(Address<=lastAddress);
}
else
{
// We assume it's an normal array, e.g. the ones from "big convexes"
assert(!(ed2.entry.mFlags & PxMetaDataFlag::eEXTRA_ITEM));
Address = convertExtraData_Array(Address, lastAddress, classAddress, ed2);
}
}
}
}
else
{
int stop = 0;
(void)(stop);
}
// ---- big convex surgery ----
setNoOutput(false);
// ---- big convex surgery ----
}
else if(ed.entry.mFlags & PxMetaDataFlag::eEXTRA_ITEMS)
{
// PX_DEF_BIN_METADATA_EXTRA_ITEMS
int reloc = ed.offset - ed.entry.mOffset; // ### because the enum code only fixed the "controlOffset"!
const int controlOffset = ed.entry.mOffset;
const int controlSize = ed.entry.mSize;
const int countOffset = ed.entry.mCount;
const int countSize = ed.entry.mOffsetSize;
// const int controlValue2 = peek(controlSize, objectAddress + controlOffset);
const PxU64 controlValue2 = peek(controlSize, objectAddress + controlOffset + reloc);
PxU64 controlMask = 0;
if(ed.entry.mFlags & PxMetaDataFlag::eCONTROL_MASK)
{
controlMask = PxU64(ed.entry.mFlags & (PxMetaDataFlag::eCONTROL_MASK_RANGE << 16));
controlMask = controlMask >> 16;
}
if(decodeControl(controlValue2, ed, controlMask))
{
// PT: safe to cast to int here since we're reading a count
// int count = peek(countSize, objectAddress + countOffset); // ###
int count = int(peek(countSize, objectAddress + countOffset + reloc, ed.entry.mFlags)); // ###
if(ed.entry.mAlignment)
{
Address = alignStream(Address, ed.entry.mAlignment);
assert(Address<=lastAddress);
}
if(ed.entry.mFlags & PxMetaDataFlag::ePTR)
{
Address = convertExtraData_Ptr(Address, lastAddress, ed.entry, count, ptrSize_Src, ptrSize_Dst);
}
else if (ed.entry.mFlags & PxMetaDataFlag::eHANDLE)
{
Address = convertExtraData_Handle(Address, lastAddress, ed.entry, count);
}
else
{
MetaClass* mc = getMetaClass(ed.entry.mType, META_DATA_SRC);
assert(mc);
while(count--)
{
convertClass(Address, mc, 0);
Address += mc->mSize;
assert(Address<=lastAddress);
}
}
}
}
else if(ed.entry.mFlags & PxMetaDataFlag::eALIGNMENT)
{
if(ed.entry.mAlignment)
{
displayMessage(PxErrorCode::eDEBUG_INFO, " align to %d bytes\n", ed.entry.mAlignment);
displayMessage(PxErrorCode::eDEBUG_INFO, "---------------------------------------------\n");
Address = alignStream(Address, ed.entry.mAlignment);
assert(Address<=lastAddress);
}
}
else if(ed.entry.mFlags & PxMetaDataFlag::eEXTRA_NAME)
{
if(ed.entry.mAlignment)
{
Address = alignStream(Address, ed.entry.mAlignment);
assert(Address<=lastAddress);
}
//get string count
MetaClass* mc = getMetaClass("PxU32", META_DATA_SRC);
assert(mc);
//safe to cast to int here since we're reading a count.
const int count = int(peek(mc->mSize, Address, 0));
displayMessage(PxErrorCode::eDEBUG_INFO, " convert %d bytes string\n", count);
convertClass(Address, mc, 0);
Address += mc->mSize;
mc = getMetaClass(ed.entry.mType, META_DATA_SRC);
assert(mc);
for(int c=0;c<count;c++)
{
convertClass(Address, mc, 0);
Address += mc->mSize;
assert(Address<=lastAddress);
}
}
else
{
Address = convertExtraData_Array(Address, lastAddress, objectAddress, ed);
}
}
}
PX_DELETE_ARRAY(objects);
assert(nbConvexes==mConvexFlags.size());
}
assert(Address==lastAddress);
return true;
}
bool Sn::ConvX::convert(const void* buffer, int fileSize)
{
// Test initial alignment
if(size_t(buffer) & (ALIGN_DEFAULT-1))
{
assert(0);
return false;
}
const int header = read32(buffer); fileSize -= 4; (void)header;
if (header != PX_MAKE_FOURCC('S','E','B','D'))
{
displayMessage(physx::PxErrorCode::eINVALID_PARAMETER,
"PxBinaryConverter: Buffer contains data with bad header indicating invalid serialized data.");
return false;
}
const int version = read32(buffer); fileSize -= 4; (void)version;
char binaryVersionGuid[SN_BINARY_VERSION_GUID_NUM_CHARS + 1];
memcpy(binaryVersionGuid, buffer, SN_BINARY_VERSION_GUID_NUM_CHARS);
binaryVersionGuid[SN_BINARY_VERSION_GUID_NUM_CHARS] = 0;
buffer = reinterpret_cast<const void*>(size_t(buffer) + SN_BINARY_VERSION_GUID_NUM_CHARS);
fileSize -= SN_BINARY_VERSION_GUID_NUM_CHARS;
output(binaryVersionGuid, SN_BINARY_VERSION_GUID_NUM_CHARS);
if (!checkCompatibility(binaryVersionGuid))
{
displayMessage(physx::PxErrorCode::eINVALID_PARAMETER,
"PxBinaryConverter: Buffer contains binary data version 0x%s which is incompatible with this PhysX sdk (0x%s).\n",
binaryVersionGuid, getBinaryVersionGuid());
return false;
}
//read src platform tag and write dst platform tag according dst meta data
const int srcPlatformTag = *reinterpret_cast<const int*>(buffer);
buffer = reinterpret_cast<const void*>(size_t(buffer) + 4);
fileSize -= 4;
const int dstPlatformTag = mMetaData_Dst->getPlatformTag();
output(dstPlatformTag);
if (srcPlatformTag != mMetaData_Src->getPlatformTag())
{
displayMessage(physx::PxErrorCode::eINVALID_PARAMETER,
"PxBinaryConverter: Mismatch of platform tags of binary data and metadata:\n Binary Data: %s\n MetaData: %s\n",
getBinaryPlatformName(PxU32(srcPlatformTag)),
getBinaryPlatformName(PxU32(mMetaData_Src->getPlatformTag())));
return false;
}
//read whether input data has marked padding, and set it for the output data (since 0xcd is written into pads on conversion)
const int srcMarkedPadding = *reinterpret_cast<const int*>(buffer);
buffer = reinterpret_cast<const void*>(size_t(buffer) + 4);
fileSize -= 4;
mMarkedPadding = srcMarkedPadding != 0;
const int dstMarkedPadding = 1;
output(dstMarkedPadding);
int nbObjectsInCollection;
buffer = convertReferenceTables(buffer, fileSize, nbObjectsInCollection);
if(!buffer)
return false;
bool ret = convertCollection(buffer, fileSize, nbObjectsInCollection);
mMarkedPadding = false;
return ret;
}
// PT: code below added to support 64bit-to-32bit conversions
void Sn::ConvX::exportIntAsPtr(int value)
{
const int ptrSize_Src = mSrcPtrSize;
const int ptrSize_Dst = mDstPtrSize;
PxMetaDataEntry entry;
const char* address = NULL;
const PxU32 value32 = PxU32(value);
const PxU64 value64 = PxU64(value)&0xffffffff;
if(ptrSize_Src==4)
{
address = reinterpret_cast<const char*>(&value32);
}
else if(ptrSize_Src==8)
{
address = reinterpret_cast<const char*>(&value64);
}
else assert(0);
convertExtraData_Ptr(address, address + ptrSize_Src, entry, 1, ptrSize_Src, ptrSize_Dst);
}
void Sn::ConvX::exportInt(int value)
{
output(value);
}
void Sn::ConvX::exportInt64(PxU64 value)
{
output(value);
}
PointerRemap::PointerRemap()
{
}
PointerRemap::~PointerRemap()
{
}
void PointerRemap::setObjectRef(PxU64 object64, PxU32 ref)
{
mData[object64] = ref;
}
bool PointerRemap::getObjectRef(PxU64 object64, PxU32& ref) const
{
const PointerMap::Entry* entry = mData.find(object64);
if(entry)
{
ref = entry->second;
return true;
}
return false;
}
Handle16Remap::Handle16Remap()
{
}
Handle16Remap::~Handle16Remap()
{
}
void Handle16Remap::setObjectRef(PxU16 object, PxU16 ref)
{
mData[object] = ref;
}
bool Handle16Remap::getObjectRef(PxU16 object, PxU16& ref) const
{
const Handle16Map::Entry* entry = mData.find(object);
if(entry)
{
ref = entry->second;
return true;
}
return false;
}
/**
Converting the PxBase object offsets in the manifest table is fairly complicated now.
It would be good to have an easy callback mechanism for custom things like this.
*/
const void* Sn::ConvX::convertManifestTable(const void* buffer, int& fileSize)
{
PxU32 padding = getPadding(size_t(buffer), ALIGN_DEFAULT);
buffer = alignStream(reinterpret_cast<const char*>(buffer));
fileSize -= padding;
int nb = read32(buffer);
fileSize -= 4;
MetaClass* mc_src = getMetaClass("Sn::ManifestEntry", META_DATA_SRC);
assert(mc_src);
MetaClass* mc_dst = getMetaClass("Sn::ManifestEntry", META_DATA_DST);
assert(mc_dst);
bool mdOk;
PxMetaDataEntry srcTypeField;
mdOk = mc_src->getFieldByName("type", srcTypeField);
PX_UNUSED(mdOk);
PX_ASSERT(mdOk);
PxMetaDataEntry dstOffsetField;
mdOk = mc_dst->getFieldByName("offset", dstOffsetField);
PX_ASSERT(mdOk);
const char* address = reinterpret_cast<const char*>(buffer);
PxU32 headerOffset = 0;
for(int i=0;i<nb;i++)
{
PxConcreteType::Enum classType = PxConcreteType::Enum(peek(srcTypeField.mSize, address + srcTypeField.mOffset));
//convert ManifestEntry but output to tmpStream
PxDefaultMemoryOutputStream tmpStream;
{
//backup output state
PxOutputStream* outStream = mOutStream;
PxU32 outputSize = PxU32(mOutputSize);
mOutStream = &tmpStream;
mOutputSize = 0;
convertClass(address, mc_src, 0);
PX_ASSERT(tmpStream.getSize() == PxU32(mc_dst->mSize));
//restore output state
mOutStream = outStream;
mOutputSize = int(outputSize);
}
//output patched offset
PX_ASSERT(dstOffsetField.mOffset == 0); //assuming offset is the first data
output(int(headerOffset));
//output rest of ManifestEntry
PxU32 restSize = PxU32(mc_dst->mSize - dstOffsetField.mSize);
mOutStream->write(tmpStream.getData() + dstOffsetField.mSize, restSize);
mOutputSize += restSize;
//increment source stream
address += mc_src->mSize;
fileSize -= mc_src->mSize;
assert(fileSize>=0);
//update headerOffset using the type and dst meta data of the type
MetaClass* mc_classType_dst = getMetaClass(classType, META_DATA_DST);
if(!mc_classType_dst)
return NULL;
headerOffset += getPadding(size_t(mc_classType_dst->mSize), PX_SERIAL_ALIGN) + mc_classType_dst->mSize;
}
output(int(headerOffset)); //endoffset
buffer = address + 4;
fileSize -= 4;
return buffer;
}
const void* Sn::ConvX::convertImportReferences(const void* buffer, int& fileSize)
{
PxU32 padding = getPadding(size_t(buffer), ALIGN_DEFAULT);
buffer = alignStream(reinterpret_cast<const char*>(buffer));
fileSize -= padding;
int nb = read32(buffer);
fileSize -= 4;
if(!nb)
return buffer;
MetaClass* mc = getMetaClass("Sn::ImportReference", META_DATA_SRC);
assert(mc);
const char* address = reinterpret_cast<const char*>(buffer);
for(int i=0;i<nb;i++)
{
convertClass(address, mc, 0);
address += mc->mSize;
fileSize -= mc->mSize;
assert(fileSize>=0);
}
return address;
}
const void* Sn::ConvX::convertExportReferences(const void* buffer, int& fileSize)
{
PxU32 padding = getPadding(size_t(buffer), ALIGN_DEFAULT);
buffer = alignStream(reinterpret_cast<const char*>(buffer));
fileSize -= padding;
int nb = read32(buffer);
fileSize -= 4;
if(!nb)
return buffer;
MetaClass* mc = getMetaClass("Sn::ExportReference", META_DATA_SRC);
assert(mc);
const char* address = reinterpret_cast<const char*>(buffer);
for(int i=0;i<nb;i++)
{
convertClass(address, mc, 0);
address += mc->mSize;
fileSize -= mc->mSize;
assert(fileSize>=0);
}
return address;
}
const void* Sn::ConvX::convertInternalReferences(const void* buffer, int& fileSize)
{
PxU32 padding = getPadding(size_t(buffer), ALIGN_DEFAULT);
buffer = alignStream(reinterpret_cast<const char*>(buffer));
fileSize -= padding;
//pointer references
int nbPtrReferences = read32(buffer);
fileSize -= 4;
if(nbPtrReferences)
{
const char* address = reinterpret_cast<const char*>(buffer);
MetaClass* mc = getMetaClass("Sn::InternalReferencePtr", META_DATA_SRC);
assert(mc);
for(int i=0;i<nbPtrReferences;i++)
{
convertClass(address, mc, 0);
address += mc->mSize;
fileSize -= mc->mSize;
assert(fileSize>=0);
}
buffer = address;
}
//16 bit handle references
int nbHandle16References = read32(buffer);
fileSize -= 4;
if (nbHandle16References)
{
//pre add invalid handle value
mHandle16Remap.setObjectRef(0xffff, 0xffff);
const char* address = reinterpret_cast<const char*>(buffer);
MetaClass* mc = getMetaClass("Sn::InternalReferenceHandle16", META_DATA_SRC);
assert(mc);
for(int i=0;i<nbHandle16References;i++)
{
convertClass(address, mc, 0);
address += mc->mSize;
fileSize -= mc->mSize;
assert(fileSize>=0);
}
buffer = address;
}
return buffer;
}
const void* Sn::ConvX::convertReferenceTables(const void* buffer, int& fileSize, int& nbObjectsInCollection)
{
// PT: the map should not be used while creating it, so use one indirection
mPointerActiveRemap = NULL;
mPointerRemap.mData.clear();
mPointerRemapCounter = 0;
mHandle16ActiveRemap = NULL;
mHandle16Remap.mData.clear();
mHandle16RemapCounter = 0;
PxU32 padding = getPadding(size_t(buffer), ALIGN_DEFAULT);
buffer = alignStream(reinterpret_cast<const char*>(buffer));
fileSize -= padding;
nbObjectsInCollection = read32(buffer);
if (nbObjectsInCollection == 0)
displayMessage(PxErrorCode::eDEBUG_INFO, "\n\nConverting empty collection!\n\n");
fileSize -= 4;
buffer = convertManifestTable(buffer, fileSize);
if(!buffer)
return NULL;
buffer = convertImportReferences(buffer, fileSize);
buffer = convertExportReferences(buffer, fileSize);
buffer = convertInternalReferences(buffer, fileSize);
// PT: the map can now be used
mPointerActiveRemap = &mPointerRemap;
mHandle16ActiveRemap = &mHandle16Remap;
return buffer;
}
bool Sn::ConvX::checkPaddingBytes(const char* buffer, int byteCount)
{
const unsigned char* src = reinterpret_cast<const unsigned char*>(buffer);
int i = 0;
while ((i < byteCount) && (src[i] == 0xcd))
i++;
return (i == byteCount);
}
| 45,113 | C++ | 29.379798 | 165 | 0.665152 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Union.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 SN_CONVX_UNION_H
#define SN_CONVX_UNION_H
namespace physx { namespace Sn {
struct UnionType
{
const char* mTypeName;
int mTypeValue;
};
struct Union
{
const char* mName;
PsArray<UnionType> mTypes;
};
} }
#endif
| 1,807 | C | 39.177777 | 74 | 0.754289 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Union.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 "SnConvX.h"
#include <assert.h>
#include "foundation/PxString.h"
using namespace physx;
void Sn::ConvX::resetUnions()
{
mUnions.clear();
}
bool Sn::ConvX::registerUnion(const char* name)
{
displayMessage(PxErrorCode::eDEBUG_INFO, "Registering union: %s\n", name);
Sn::Union u;
u.mName = name;
mUnions.pushBack(u);
return true;
}
bool Sn::ConvX::registerUnionType(const char* unionName, const char* typeName, int typeValue)
{
const PxU32 nb = mUnions.size();
for(PxU32 i=0;i<nb;i++)
{
if(Pxstrcmp(mUnions[i].mName, unionName)==0)
{
UnionType t;
t.mTypeName = typeName;
t.mTypeValue = typeValue;
mUnions[i].mTypes.pushBack(t);
displayMessage(PxErrorCode::eDEBUG_INFO, "Registering union type: %s | %s | %d\n", unionName, typeName, typeValue);
return true;
}
}
displayMessage(PxErrorCode::eINTERNAL_ERROR, "PxBinaryConverter: union not found: %s, please check the source metadata.\n", unionName);
return false;
}
const char* Sn::ConvX::getTypeName(const char* unionName, int typeValue)
{
const PxU32 nb = mUnions.size();
for(PxU32 i=0;i<nb;i++)
{
if(Pxstrcmp(mUnions[i].mName, unionName)==0)
{
const PxU32 nbTypes = mUnions[i].mTypes.size();
for(PxU32 j=0;j<nbTypes;j++)
{
const UnionType& t = mUnions[i].mTypes[j];
if(t.mTypeValue==typeValue)
return t.mTypeName;
}
break;
}
}
displayMessage(PxErrorCode::eINTERNAL_ERROR,
"PxBinaryConverter: union type not found: %s, type %d, please check the source metadata.\n", unionName, typeValue);
assert(0);
return NULL;
}
| 3,126 | C++ | 33.362637 | 136 | 0.727767 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 SN_CONVX_H
#define SN_CONVX_H
#include "foundation/PxErrors.h"
#include "common/PxTypeInfo.h"
#include "extensions/PxBinaryConverter.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxArray.h"
#include "foundation/PxHashMap.h"
#include "SnConvX_Common.h"
#include "SnConvX_Union.h"
#include "SnConvX_MetaData.h"
#include "SnConvX_Align.h"
#define CONVX_ZERO_BUFFER_SIZE 256
namespace physx {
class PxSerializationRegistry;
namespace Sn {
struct HeightFieldData;
class PointerRemap
{
public:
PointerRemap();
~PointerRemap();
void setObjectRef(PxU64 object64, PxU32 ref);
bool getObjectRef(PxU64 object64, PxU32& ref) const;
typedef PxHashMap<PxU64, PxU32> PointerMap;
PointerMap mData;
};
class Handle16Remap
{
public:
Handle16Remap();
~Handle16Remap();
void setObjectRef(PxU16 object, PxU16 ref);
bool getObjectRef(PxU16 object, PxU16& ref) const;
typedef PxHashMap<PxU16, PxU16> Handle16Map;
Handle16Map mData;
};
class ConvX : public physx::PxBinaryConverter, public PxUserAllocated
{
public:
ConvX();
virtual ~ConvX();
virtual void release();
virtual void setReportMode(PxConverterReportMode::Enum mode) { mReportMode = mode; }
PX_FORCE_INLINE bool silentMode() const { return mReportMode==PxConverterReportMode::eNONE; }
PX_FORCE_INLINE bool verboseMode() const { return mReportMode==PxConverterReportMode::eVERBOSE; }
virtual bool setMetaData(PxInputStream& srcMetaData, PxInputStream& dstMetaData);
virtual bool compareMetaData() const;
virtual bool convert(PxInputStream& srcStream, PxU32 srcSize, PxOutputStream& targetStream);
private:
ConvX& operator=(const ConvX&);
bool setMetaData(PxInputStream& inputStream, MetaDataType type);
// Meta-data
void releaseMetaData();
const MetaData* loadMetaData(PxInputStream& inputStream, MetaDataType type);
const MetaData* getBinaryMetaData(MetaDataType type);
int getNbMetaClasses(MetaDataType type);
MetaClass* getMetaClass(unsigned int i, MetaDataType type) const;
MetaClass* getMetaClass(const char* name, MetaDataType type) const;
MetaClass* getMetaClass(PxConcreteType::Enum concreteType, MetaDataType type);
MetaData* mMetaData_Src;
MetaData* mMetaData_Dst;
// Convert
bool convert(const void* buffer, int fileSize);
void resetConvexFlags();
void _enumerateFields(const MetaClass* mc, ExtraDataEntry2* entries, int& nb, int baseOffset, MetaDataType type) const;
void _enumerateExtraData(const char* address, const MetaClass* mc, ExtraDataEntry* entries, int& nb, int offset, MetaDataType type) const;
PxU64 read64(const void*& buffer);
int read32(const void*& buffer);
short read16(const void*& buffer);
bool convertClass(const char* buffer, const MetaClass* mc, int offset);
const char* convertExtraData_Array(const char* Address, const char* lastAddress, const char* objectAddress, const ExtraDataEntry& ed);
const char* convertExtraData_Ptr(const char* Address, const char* lastAddress, const PxMetaDataEntry& entry, int count, int ptrSize_Src, int ptrSize_Dst);
const char* convertExtraData_Handle(const char* Address, const char* lastAddress, const PxMetaDataEntry& entry, int count);
int getConcreteType(const char* buffer);
bool convertCollection(const void* buffer, int fileSize, int nbObjects);
const void* convertManifestTable(const void* buffer, int& fileSize);
const void* convertImportReferences(const void* buffer, int& fileSize);
const void* convertExportReferences(const void* buffer, int& fileSize);
const void* convertInternalReferences(const void* buffer, int& fileSize);
const void* convertReferenceTables(const void* buffer, int& fileSize, int& nbObjectsInCollection);
bool checkPaddingBytes(const char* buffer, int byteCount);
// ---- big convex surgery ----
PsArray<bool> mConvexFlags;
// Align
const char* alignStream(const char* buffer, int alignment=ALIGN_DEFAULT);
void alignTarget(int alignment);
char mZeros[CONVX_ZERO_BUFFER_SIZE];
// Unions
bool registerUnion(const char* name);
bool registerUnionType(const char* unionName, const char* typeName, int typeValue);
const char* getTypeName(const char* unionName, int typeValue);
void resetUnions();
PsArray<Union> mUnions;
// Output
void setNullPtr(bool);
void setNoOutput(bool);
bool initOutput(PxOutputStream& targetStream);
void closeOutput();
int getCurrentOutputSize();
void output(short value);
void output(int value);
void output(PxU64 value);
void output(const char* buffer, int nbBytes);
void convert8 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convertPad8 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convert16 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convert32 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convert64 (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convertFloat(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convertPtr (const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
void convertHandle16(const char* src, const PxMetaDataEntry& entry, const PxMetaDataEntry& dstEntry);
PxOutputStream* mOutStream;
bool mMustFlip;
int mOutputSize;
int mSrcPtrSize;
int mDstPtrSize;
bool mNullPtr;
bool mNoOutput;
bool mMarkedPadding;
// Errors
void resetNbErrors();
int getNbErrors() const;
void displayMessage(physx::PxErrorCode::Enum code, const char* format, ...);
int mNbErrors;
int mNbWarnings;
// Settings
PxConverterReportMode::Enum mReportMode;
bool mPerformConversion;
// Remap pointers
void exportIntAsPtr(int value);
void exportInt(int value);
void exportInt64(PxU64 value);
PointerRemap mPointerRemap;
PointerRemap* mPointerActiveRemap;
PxU32 mPointerRemapCounter;
Handle16Remap mHandle16Remap;
Handle16Remap* mHandle16ActiveRemap;
PxU16 mHandle16RemapCounter;
friend class MetaData;
friend struct MetaClass;
};
} }
#endif
| 8,453 | C | 42.132653 | 163 | 0.698923 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_Error.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/PxErrorCallback.h"
#include "foundation/PxString.h"
#include "SnConvX.h"
#include <stdarg.h>
#define MAX_DISPLAYED_ISSUES 10
using namespace physx;
void Sn::ConvX::resetNbErrors()
{
mNbErrors = 0;
mNbWarnings = 0;
}
int Sn::ConvX::getNbErrors() const
{
return mNbErrors;
}
void Sn::ConvX::displayMessage(PxErrorCode::Enum code, const char* format, ...)
{
if(silentMode())
return;
int sum = mNbWarnings + mNbErrors;
if(sum >= MAX_DISPLAYED_ISSUES)
return;
bool display = false;
if(code==PxErrorCode::eINTERNAL_ERROR || code==PxErrorCode::eINVALID_OPERATION || code==PxErrorCode::eINVALID_PARAMETER)
{
mNbErrors++;
display = true;
}
else if(code == PxErrorCode::eDEBUG_WARNING)
{
mNbWarnings++;
display = true;
}
if(display || ((sum == 0) && verboseMode()) )
{
va_list va;
va_start(va, format);
PxGetFoundation().error(code, PX_FL, format, va);
va_end(va);
}
if(display)
{
if( sum == 0)
{
PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "Hit warnings or errors: skipping further verbose output.\n");
}
else if(sum == MAX_DISPLAYED_ISSUES-1)
{
PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "Exceeding 10 warnings or errors: skipping further output.\n");
}
}
return;
}
| 2,855 | C++ | 30.384615 | 129 | 0.723993 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnSerializationContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_SERIALIZATION_CONTEXT_H
#define SN_SERIALIZATION_CONTEXT_H
#include "foundation/PxAssert.h"
#include "foundation/PxMemory.h"
#include "foundation/PxHash.h"
#include "common/PxSerialFramework.h"
#include "extensions/PxDefaultStreams.h"
#include "foundation/PxUserAllocated.h"
#include "CmCollection.h"
#include "CmUtils.h"
#include "SnConvX_Align.h"
namespace physx
{
namespace Sn
{
struct ManifestEntry
{
PX_FORCE_INLINE ManifestEntry(PxU32 _offset, PxType _type)
{
PxMarkSerializedMemory(this, sizeof(ManifestEntry));
offset = _offset;
type = _type;
}
PX_FORCE_INLINE ManifestEntry() { PxMarkSerializedMemory(this, sizeof(ManifestEntry)); }
PX_FORCE_INLINE void operator =(const ManifestEntry& m)
{
PxMemCopy(this, &m, sizeof(ManifestEntry));
}
PxU32 offset;
PxType type;
};
struct ImportReference
{
PX_FORCE_INLINE ImportReference(PxSerialObjectId _id, PxType _type)
{
PxMarkSerializedMemory(this, sizeof(ImportReference));
id = _id;
type = _type;
}
PX_FORCE_INLINE ImportReference() { PxMarkSerializedMemory(this, sizeof(ImportReference)); }
PX_FORCE_INLINE void operator =(const ImportReference& m)
{
PxMemCopy(this, &m, sizeof(ImportReference));
}
PxSerialObjectId id;
PxType type;
};
#define SERIAL_OBJECT_INDEX_TYPE_BIT (1u<<31)
struct SerialObjectIndex
{
PX_FORCE_INLINE SerialObjectIndex(PxU32 index, bool external) { setIndex(index, external); }
PX_FORCE_INLINE SerialObjectIndex(const SerialObjectIndex& objIndex) : mObjIndex(objIndex.mObjIndex) {}
PX_FORCE_INLINE SerialObjectIndex() : mObjIndex(PX_INVALID_U32) {}
PX_FORCE_INLINE void setIndex(PxU32 index, bool external)
{
PX_ASSERT((index & SERIAL_OBJECT_INDEX_TYPE_BIT) == 0);
mObjIndex = index | (external ? SERIAL_OBJECT_INDEX_TYPE_BIT : 0);
}
PX_FORCE_INLINE PxU32 getIndex(bool& isExternal)
{
PX_ASSERT(mObjIndex != PX_INVALID_U32);
isExternal = (mObjIndex & SERIAL_OBJECT_INDEX_TYPE_BIT) > 0;
return mObjIndex & ~SERIAL_OBJECT_INDEX_TYPE_BIT;
}
PX_FORCE_INLINE bool operator < (const SerialObjectIndex& so) const
{
return mObjIndex < so.mObjIndex;
}
private:
PxU32 mObjIndex;
};
struct ExportReference
{
PX_FORCE_INLINE ExportReference(PxSerialObjectId _id, SerialObjectIndex _objIndex)
{
PxMarkSerializedMemory(this, sizeof(ExportReference));
id = _id;
objIndex = _objIndex;
}
PX_FORCE_INLINE ExportReference() { PxMarkSerializedMemory(this, sizeof(ExportReference)); }
PX_FORCE_INLINE void operator =(const ExportReference& m)
{
PxMemCopy(this, &m, sizeof(ExportReference));
}
PxSerialObjectId id;
SerialObjectIndex objIndex;
};
struct InternalReferencePtr
{
PX_FORCE_INLINE InternalReferencePtr() {}
PX_FORCE_INLINE InternalReferencePtr(size_t _reference, SerialObjectIndex _objIndex) :
reference(_reference),
objIndex(_objIndex)
#if PX_P64_FAMILY
,pad(PX_PADDING_32)
#endif
{
}
size_t reference;
SerialObjectIndex objIndex;
#if PX_P64_FAMILY
PxU32 pad;
#endif
};
struct InternalReferenceHandle16
{
PX_FORCE_INLINE InternalReferenceHandle16() {}
PX_FORCE_INLINE InternalReferenceHandle16(PxU16 _reference, SerialObjectIndex _objIndex) :
reference(_reference),
pad(PX_PADDING_16),
objIndex(_objIndex)
{
}
PxU16 reference;
PxU16 pad;
SerialObjectIndex objIndex;
};
typedef Cm::CollectionHashMap<size_t, SerialObjectIndex> InternalPtrRefMap;
typedef Cm::CollectionHashMap<PxU16, SerialObjectIndex> InternalHandle16RefMap;
class DeserializationContext : public PxDeserializationContext, public PxUserAllocated
{
PX_NOCOPY(DeserializationContext)
public:
DeserializationContext(const ManifestEntry* manifestTable,
const ImportReference* importReferences,
PxU8* objectDataAddress,
const InternalPtrRefMap& internalPtrReferencesMap,
const InternalHandle16RefMap& internalHandle16ReferencesMap,
const Cm::Collection* externalRefs,
PxU8* extraData)
: mManifestTable(manifestTable)
, mImportReferences(importReferences)
, mObjectDataAddress(objectDataAddress)
, mInternalPtrReferencesMap(internalPtrReferencesMap)
, mInternalHandle16ReferencesMap(internalHandle16ReferencesMap)
, mExternalRefs(externalRefs)
{
mExtraDataAddress = extraData;
}
virtual PxBase* resolveReference(PxU32 kind, size_t reference) const;
private:
//various pointers to deserialized data
const ManifestEntry* mManifestTable;
const ImportReference* mImportReferences;
PxU8* mObjectDataAddress;
//internal references maps for resolving references.
const InternalPtrRefMap& mInternalPtrReferencesMap;
const InternalHandle16RefMap& mInternalHandle16ReferencesMap;
//external collection for resolving import references.
const Cm::Collection* mExternalRefs;
//const PxU32 mPhysXVersion;
};
class SerializationContext : public PxSerializationContext, public PxUserAllocated
{
PX_NOCOPY(SerializationContext)
public:
SerializationContext(const Cm::Collection& collection, const Cm::Collection* externalRefs)
: mCollection(collection)
, mExternalRefs(externalRefs)
{
// fill object to collection index map (same ordering as manifest)
for (PxU32 i=0;i<mCollection.internalGetNbObjects();i++)
{
mObjToCollectionIndexMap[mCollection.internalGetObject(i)] = i;
}
}
virtual void writeData(const void* buffer, PxU32 size) { mMemStream.write(buffer, size); }
virtual PxU32 getTotalStoredSize() { return mMemStream.getSize(); }
virtual void alignData(PxU32 alignment = PX_SERIAL_ALIGN)
{
if(!alignment)
return;
PxI32 bytesToPad = PxI32(getPadding(mMemStream.getSize(), alignment));
static const PxI32 BUFSIZE = 64;
char buf[BUFSIZE];
PxMemSet(buf, 0, bytesToPad < BUFSIZE ? PxU32(bytesToPad) : PxU32(BUFSIZE));
while(bytesToPad > 0)
{
mMemStream.write(buf, bytesToPad < BUFSIZE ? PxU32(bytesToPad) : PxU32(BUFSIZE));
bytesToPad -= BUFSIZE;
}
PX_ASSERT(!getPadding(getTotalStoredSize(), alignment));
}
virtual void writeName(const char*)
{
PxGetFoundation().error(physx::PxErrorCode::eINVALID_OPERATION, PX_FL,
"Cannot export names during exportData.");
}
const PxCollection& getCollection() const { return mCollection; }
virtual void registerReference(PxBase& serializable, PxU32 kind, size_t reference);
const PxArray<ImportReference>& getImportReferences() { return mImportReferences; }
InternalPtrRefMap& getInternalPtrReferencesMap() { return mInternalPtrReferencesMap; }
InternalHandle16RefMap& getInternalHandle16ReferencesMap() { return mInternalHandle16ReferencesMap; }
PxU32 getSize() const { return mMemStream.getSize(); }
PxU8* getData() const { return mMemStream.getData(); }
private:
//import reference map for unique registration of import references and corresponding buffer.
PxHashMap<PxSerialObjectId, PxU32> mImportReferencesMap;
PxArray<ImportReference> mImportReferences;
//maps for unique registration of internal references
InternalPtrRefMap mInternalPtrReferencesMap;
InternalHandle16RefMap mInternalHandle16ReferencesMap;
//map for quick lookup of manifest index.
PxHashMap<const PxBase*, PxU32> mObjToCollectionIndexMap;
//collection and externalRefs collection for assigning references.
const Cm::Collection& mCollection;
const Cm::Collection* mExternalRefs;
PxDefaultMemoryOutputStream mMemStream;
};
} // namespace Sn
}
#endif
| 9,416 | C | 32.275618 | 106 | 0.733857 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX.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.
/*
- get rid of STL
- NpArticulationLinkArray with more than 4 entries
- big convexes Xbox => PC
- put a cache in "convertClass" function
- remove MD one at a time and check what happens in the converter. Make it robust/report errors
- for xbox, compare against source xbox file if it exists
- maybe put some info in the header to display "File generated by ConvX 1.xx" on screen (to debug)
- report inconsistent naming convention in each class!!!!
- try to automatically discover padding bytes? use "0xcd" pattern?
* do last param of XXXX_ITEMS macro automatically
- what if source files are 64bits? can we safely convert a 64bit ptr to 32bit?
*/
#include "foundation/PxErrorCallback.h"
#include "foundation/PxAllocatorCallback.h"
#include "foundation/PxIO.h"
#include "SnConvX.h"
#include "serialization/SnSerializationRegistry.h"
#include <assert.h>
using namespace physx;
Sn::ConvX::ConvX() :
mMetaData_Src (NULL),
mMetaData_Dst (NULL),
mOutStream (NULL),
mMustFlip (false),
mOutputSize (0),
mSrcPtrSize (0),
mDstPtrSize (0),
mNullPtr (false),
mNoOutput (false),
mMarkedPadding (false),
mNbErrors (0),
mNbWarnings (0),
mReportMode (PxConverterReportMode::eNORMAL),
mPerformConversion (true)
{
// memset(mZeros, 0, CONVX_ZERO_BUFFER_SIZE);
memset(mZeros, 0x42, CONVX_ZERO_BUFFER_SIZE);
}
Sn::ConvX::~ConvX()
{
resetNbErrors();
resetConvexFlags();
releaseMetaData();
resetUnions();
}
void Sn::ConvX::release()
{
PX_DELETE_THIS;
}
bool Sn::ConvX::setMetaData(PxInputStream& inputStream, MetaDataType type)
{
resetNbErrors();
return (loadMetaData(inputStream, type) != NULL);
}
bool Sn::ConvX::setMetaData(PxInputStream& srcMetaData, PxInputStream& dstMetaData)
{
releaseMetaData();
resetUnions();
if(!setMetaData(srcMetaData, META_DATA_SRC))
return false;
if(!setMetaData(dstMetaData, META_DATA_DST))
return false;
return true;
}
bool Sn::ConvX::compareMetaData() const
{
if (!mMetaData_Src || !mMetaData_Dst) {
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL,
"PxBinaryConverter: metadata not defined. Call PxBinaryConverter::setMetaData first.\n");
return false;
}
return mMetaData_Src->compare(*mMetaData_Dst);
}
bool Sn::ConvX::convert(PxInputStream& srcStream, PxU32 srcSize, PxOutputStream& targetStream)
{
if(!mMetaData_Src || !mMetaData_Dst)
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL,
"PxBinaryConverter: metadata not defined. Call PxBinaryConverter::setMetaData first.\n");
return false;
}
resetConvexFlags();
resetNbErrors();
bool conversionStatus = false;
if(mPerformConversion)
{
if(srcSize == 0)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxBinaryConverter: source serialized data size is zero.\n");
return false;
}
void* memory = PX_ALLOC(srcSize+ALIGN_FILE, "ConvX source file");
void* memoryA = reinterpret_cast<void*>((size_t(memory) + ALIGN_FILE)&~(ALIGN_FILE-1));
const PxU32 nbBytesRead = srcStream.read(memoryA, srcSize);
if(nbBytesRead != srcSize)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL,
"PxBinaryConverter: failure on reading source serialized data.\n");
PX_FREE(memory);
return false;
}
displayMessage(PxErrorCode::eDEBUG_INFO, "\n\nConverting...\n\n");
{
if(!initOutput(targetStream))
{
PX_FREE(memory);
return false;
}
conversionStatus = convert(memoryA, int(srcSize));
closeOutput();
}
PX_FREE(memory);
}
return conversionStatus;
}
| 5,095 | C++ | 29.884848 | 98 | 0.734249 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Binary/SnConvX_MetaData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 SN_CONVX_METADATA_H
#define SN_CONVX_METADATA_H
#include "common/PxMetaDataFlags.h"
#include "SnConvX_Output.h"
#include "serialization/SnSerialUtils.h"
namespace physx { namespace Sn {
#if PX_VC
#pragma warning (push)
#pragma warning (disable : 4371) //layout of class may have changed from a previous version of the compiler due to better packing of member
#endif
// PT: beware, must match corresponding structure in PxMetaData.h
struct PxMetaDataEntry : public PxUserAllocated
{
PxMetaDataEntry()
{
memset(this, 0, sizeof(*this));
}
bool isVTablePtr() const;
const char* mType; //!< Field type (bool, byte, quaternion, etc)
const char* mName; //!< Field name (appears exactly as in the source file)
int mOffset; //!< Offset from the start of the class (ie from "this", field is located at "this"+Offset)
int mSize; //!< sizeof(Type)
int mCount; //!< Number of items of type Type (0 for dynamic sizes)
int mOffsetSize; //!< Offset of dynamic size param, for dynamic arrays
int mFlags; //!< Field parameters
int mAlignment; //!< Explicit alignment added for DE1340
};
struct MetaDataEntry32
{
PxI32 mType; //!< Field type (bool, byte, quaternion, etc)
PxI32 mName; //!< Field name (appears exactly as in the source file)
int mOffset; //!< Offset from the start of the class (ie from "this", field is located at "this"+Offset)
int mSize; //!< sizeof(Type)
int mCount; //!< Number of items of type Type (0 for dynamic sizes)
int mOffsetSize; //!< Offset of dynamic size param, for dynamic arrays
int mFlags; //!< Field parameters
int mAlignment; //!< Explicit alignment added for DE1340
};
struct MetaDataEntry64
{
PxI64 mType; //!< Field type (bool, byte, quaternion, etc)
PxI64 mName; //!< Field name (appears exactly as in the source file)
int mOffset; //!< Offset from the start of the class (ie from "this", field is located at "this"+Offset)
int mSize; //!< sizeof(Type)
int mCount; //!< Number of items of type Type (0 for dynamic sizes)
int mOffsetSize; //!< Offset of dynamic size param, for dynamic arrays
int mFlags; //!< Field parameters
int mAlignment; //!< Explicit alignment added for DE1340
};
struct ExtraDataEntry
{
PxMetaDataEntry entry;
int offset;
};
struct ExtraDataEntry2 : ExtraDataEntry
{
ConvertCallback cb;
};
class MetaData;
struct MetaClass : public PxUserAllocated
{
bool getFieldByType(const char* type, PxMetaDataEntry& entry) const;
bool getFieldByName(const char* name, PxMetaDataEntry& entry) const;
bool check(const MetaData& owner);
ConvertCallback mCallback;
MetaClass* mMaster;
const char* mClassName;
int mSize;
int mDepth;
PsArray<PxMetaDataEntry> mBaseClasses;
PsArray<PxMetaDataEntry> mFields;
bool mProcessed;
// int mNbEntries;
// ExtraDataEntry2 mEntries[256];
private:
void checkAndCompleteClass(const MetaData& owner, int& startOffset, int& nbBytes);
};
enum MetaDataType
{
META_DATA_NONE,
META_DATA_SRC,
META_DATA_DST
};
class ConvX;
class MetaData : public PxUserAllocated
{
public:
MetaData(Sn::ConvX&);
~MetaData();
bool load(PxInputStream& inputStream, MetaDataType type);
inline_ MetaDataType getType() const { return mType; }
inline_ int getVersion() const { return mVersion; }
inline_ int getPtrSize() const { return mSizeOfPtr; }
inline_ int getPlatformTag() const { return mPlatformTag; }
inline_ int getGaussMapLimit() const { return mGaussMapLimit; }
inline_ int getNbMetaClasses() const { return int(mMetaClasses.size()); }
inline_ MetaClass* getMetaClass(unsigned int i) const { return mMetaClasses[i]; }
inline_ bool getFlip() const { return mFlip; }
MetaClass* getMetaClass(const char* name) const;
MetaClass* getMetaClass(PxConcreteType::Enum concreteType) const;
MetaClass* addNewClass(const char* name, int size, MetaClass* master=NULL, ConvertCallback callback=NULL);
bool compare(const MetaData& candidate) const;
private:
MetaData& operator=(const MetaData&);
Sn::ConvX& mConvX;
MetaDataType mType;
int mNbEntries;
PxMetaDataEntry* mEntries;
char* mStringTable;
PsArray<MetaClass*> mMetaClasses;
int mVersion;
char mBinaryVersionGuid[SN_BINARY_VERSION_GUID_NUM_CHARS + 1];
int mSizeOfPtr;
int mPlatformTag;
int mGaussMapLimit;
bool mFlip;
PsArray< PxPair<PxConcreteType::Enum, PxU32> > mConcreteTypeTable;
inline_ const char* offsetToText(const char* text) const
{
const size_t offset = size_t(text);
const PxU32 offset32 = PxU32(offset);
// if(offset==-1)
if(offset32==0xffffffff)
return NULL;
return mStringTable + offset32;
}
friend struct MetaClass;
};
PxU64 peek(int size, const char* buffer, int flags=0);
#if PX_VC
#pragma warning (pop)
#endif
} }
#endif
| 6,774 | C | 35.037234 | 139 | 0.683791 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/File/SnFile.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_FILE_H
#define SN_FILE_H
// fopen_s - returns 0 on success, non-zero on failure
#if PX_WINDOWS_FAMILY
#include <stdio.h>
namespace physx
{
namespace sn
{
PX_INLINE PxI32 fopen_s(FILE** file, const char* name, const char* mode)
{
static const PxU32 MAX_LEN = 300;
char buf[MAX_LEN+1];
PxU32 i;
for(i = 0; i<MAX_LEN && name[i]; i++)
buf[i] = name[i] == '/' ? '\\' : name[i];
buf[i] = 0;
return i == MAX_LEN ? -1 : ::fopen_s(file, buf, mode);
};
} // namespace sn
} // namespace physx
#elif PX_UNIX_FAMILY || PX_SWITCH
#include <stdio.h>
namespace physx
{
namespace sn
{
PX_INLINE PxI32 fopen_s(FILE** file, const char* name, const char* mode)
{
FILE* fp = ::fopen(name, mode);
if(fp)
{
*file = fp;
return PxI32(0);
}
return -1;
}
} // namespace sn
} // namespace physx
#else
#error "Platform not supported!"
#endif
#endif //SN_FILE_H
| 2,572 | C | 29.270588 | 74 | 0.717729 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlMemoryAllocator.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_XML_MEMORY_ALLOCATOR_H
#define SN_XML_MEMORY_ALLOCATOR_H
#include "foundation/PxSimpleTypes.h"
namespace physx {
class PX_DEPRECATED XmlMemoryAllocator
{
protected:
virtual ~XmlMemoryAllocator(){}
public:
virtual PxU8* allocate(PxU32 inSize) = 0;
virtual void deallocate( PxU8* inMem ) = 0;
virtual PxAllocatorCallback& getAllocator() = 0;
template<typename TObjectType>
TObjectType* allocate()
{
TObjectType* retval = reinterpret_cast< TObjectType* >( allocate( sizeof( TObjectType ) ) );
new (retval) TObjectType();
return retval;
}
template<typename TObjectType, typename TArgType>
TObjectType* allocate(const TArgType &arg)
{
TObjectType* retval = reinterpret_cast< TObjectType* >( allocate( sizeof( TObjectType ) ) );
new (retval) TObjectType(arg);
return retval;
}
template<typename TObjectType>
void deallocate( TObjectType* inObject )
{
deallocate( reinterpret_cast<PxU8*>( inObject ) );
}
template<typename TObjectType>
inline TObjectType* batchAllocate(PxU32 inCount )
{
TObjectType* retval = reinterpret_cast<TObjectType*>( allocate( sizeof(TObjectType) * inCount ) );
for ( PxU32 idx = 0; idx < inCount; ++idx )
{
new (retval + idx) TObjectType();
}
return retval;
}
template<typename TObjectType, typename TArgType>
inline TObjectType* batchAllocate(PxU32 inCount, const TArgType &arg)
{
TObjectType* retval = reinterpret_cast<TObjectType*>( allocate( sizeof(TObjectType) * inCount ) );
for ( PxU32 idx = 0; idx < inCount; ++idx )
{
new (retval + idx) TObjectType(arg);
}
return retval;
}
//Duplicate function definition for gcc.
template<typename TObjectType>
inline TObjectType* batchAllocate(TObjectType*, PxU32 inCount )
{
TObjectType* retval = reinterpret_cast<TObjectType*>( allocate( sizeof(TObjectType) * inCount ) );
for ( PxU32 idx = 0; idx < inCount; ++idx )
{
new (retval + idx) TObjectType();
}
return retval;
}
};
struct PX_DEPRECATED XmlMemoryAllocatorImpl : public XmlMemoryAllocator
{
Sn::TMemoryPoolManager mManager;
XmlMemoryAllocatorImpl( PxAllocatorCallback& inAllocator )
: mManager( inAllocator )
{
}
XmlMemoryAllocatorImpl &operator=(const XmlMemoryAllocatorImpl &);
virtual PxAllocatorCallback& getAllocator()
{
return mManager.getWrapper().getAllocator();
}
virtual PxU8* allocate(PxU32 inSize )
{
if ( !inSize )
return NULL;
return mManager.allocate( inSize );
}
virtual void deallocate( PxU8* inMem )
{
if ( inMem )
mManager.deallocate( inMem );
}
};
}
#endif
| 4,321 | C | 32.246154 | 101 | 0.723444 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlReader.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_XML_READER_H
#define SN_XML_READER_H
#include "foundation/PxSimpleTypes.h"
#include "extensions/PxRepXSimpleType.h"
namespace physx {
namespace Sn { struct XmlNode; }
/**
* Reader used to read data out of the repx format.
*/
class XmlReader
{
protected:
virtual ~XmlReader(){}
public:
/** Read a key-value pair out of the database */
virtual bool read( const char* inName, const char*& outData ) = 0;
/** Read an object id out of the database */
virtual bool read( const char* inName, PxSerialObjectId& outId ) = 0;
/** Goto a child element by name. That child becomes this reader's context */
virtual bool gotoChild( const char* inName ) = 0;
/** Goto the first child regardless of name */
virtual bool gotoFirstChild() = 0;
/** Goto the next sibling regardless of name */
virtual bool gotoNextSibling() = 0;
/** Count all children of the current object */
virtual PxU32 countChildren() = 0;
/** Get the name of the current item */
virtual const char* getCurrentItemName() = 0;
/** Get the value of the current item */
virtual const char* getCurrentItemValue() = 0;
/** Leave the current child */
virtual bool leaveChild() = 0;
/** Get reader for the parental object */
virtual XmlReader* getParentReader() = 0;
/**
* Ensures we don't leave the reader in an odd state
* due to not leaving a given child
*/
virtual void pushCurrentContext() = 0;
/** Pop the current context back to where it during push*/
virtual void popCurrentContext() = 0;
};
//Used when upgrading a repx collection
class XmlReaderWriter : public XmlReader
{
public:
//Clears the stack of nodes (push/pop current node reset)
//and sets the current node to inNode.
virtual void setNode( Sn::XmlNode& node ) = 0;
//If the child exists, add it.
//the either way goto that child.
virtual void addOrGotoChild( const char* name ) = 0;
//Value is copied into the collection, inValue has no further references
//to it.
virtual void setCurrentItemValue( const char* value ) = 0;
//Removes the child but does not release the char* name or char* data ptrs.
//Those pointers are never released and are shared among collections.
//Thus copying nodes is cheap and safe.
virtual bool removeChild( const char* name ) = 0;
virtual void release() = 0;
bool renameProperty( const char* oldName, const char* newName )
{
if ( gotoChild( oldName ) )
{
const char* value = getCurrentItemValue();
leaveChild();
removeChild( oldName );
addOrGotoChild( newName );
setCurrentItemValue( value );
leaveChild();
return true;
}
return false;
}
bool readAndRemoveProperty( const char* name, const char*& outValue )
{
bool retval = read( name, outValue );
if ( retval ) removeChild( name );
return retval;
}
bool writePropertyIfNotEmpty( const char* name, const char* value )
{
if ( value && *value )
{
addOrGotoChild( name );
setCurrentItemValue( value );
leaveChild();
return true;
}
return false;
}
};
}
#endif
| 4,775 | C | 35.458015 | 80 | 0.709319 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepXUpgrader.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "SnXmlImpl.h"
#include "SnXmlReader.h"
#include "SnXmlMemoryAllocator.h"
#include "SnRepXCollection.h"
#include "SnRepXUpgrader.h"
using namespace physx::profile;
namespace physx { namespace Sn {
#define DEFINE_REPX_DEFAULT_PROPERTY( name, val ) RepXDefaultEntry( name, val ),
static RepXDefaultEntry gRepX1_0Defaults[] = {
#include "SnRepX1_0Defaults.h"
};
static PxU32 gNumRepX1_0Default = sizeof( gRepX1_0Defaults ) / sizeof ( *gRepX1_0Defaults );
static RepXDefaultEntry gRepX3_1Defaults[] = {
#include "SnRepX3_1Defaults.h"
};
static PxU32 gNumRepX3_1Defaults = sizeof( gRepX3_1Defaults ) / sizeof ( *gRepX3_1Defaults );
static RepXDefaultEntry gRepX3_2Defaults[] = {
#include "SnRepX3_2Defaults.h"
};
static PxU32 gNumRepX3_2Defaults = sizeof( gRepX3_2Defaults ) / sizeof ( *gRepX3_2Defaults );
inline const char* nextPeriod( const char* str )
{
for( ++str; str && *str && *str != '.'; ++str ); //empty loop intentional
return str;
}
inline bool safeStrEq(const char* lhs, const char* rhs)
{
if (lhs == rhs)
return true;
//If they aren't equal, and one of them is null,
//then they can't be equal.
//This is assuming that the null char* is not equal to
//the empty "" char*.
if (!lhs || !rhs)
return false;
return ::strcmp(lhs, rhs) == 0;
}
typedef PxProfileHashMap<const char*, PxU32> TNameOffsetMap;
void setMissingPropertiesToDefault( XmlNode* topNode, XmlReaderWriter& editor, const RepXDefaultEntry* defaults, PxU32 numDefaults, TNameOffsetMap& map )
{
for ( XmlNode* child = topNode->mFirstChild; child != NULL; child = child->mNextSibling )
setMissingPropertiesToDefault( child, editor, defaults, numDefaults, map );
const TNameOffsetMap::Entry* entry( map.find( topNode->mName ) );
if ( entry )
{
XmlReaderWriter& theReader( editor );
theReader.setNode( *topNode );
char nameBuffer[512] = {0};
size_t nameLen = strlen( topNode->mName );
//For each default property entry for this node type.
for ( const RepXDefaultEntry* item = defaults + entry->second; Pxstrncmp( item->name, topNode->mName, nameLen ) == 0; ++item )
{
bool childAdded = false;
const char* nameStart = item->name + nameLen;
++nameStart;
theReader.pushCurrentContext();
const char* str = nameStart;
while( *str )
{
const char *period = nextPeriod( str );
size_t len = size_t(PxMin( period - str, ptrdiff_t(1023) )); //can't be too careful these days.
PxMemCopy( nameBuffer, str, PxU32(len) );
nameBuffer[len] = 0;
if ( theReader.gotoChild( nameBuffer ) == false )
{
childAdded = true;
theReader.addOrGotoChild( nameBuffer );
}
if (*period )
str = period + 1;
else
str = period;
}
if ( childAdded )
theReader.setCurrentItemValue( item->value );
theReader.popCurrentContext();
}
}
}
static void setMissingPropertiesToDefault( RepXCollection& collection, XmlReaderWriter& editor, const RepXDefaultEntry* defaults, PxU32 numDefaults )
{
PxProfileAllocatorWrapper wrapper( collection.getAllocator() );
//Release all strings at once, instead of piece by piece
XmlMemoryAllocatorImpl alloc( collection.getAllocator() );
//build a hashtable of the initial default value strings.
TNameOffsetMap nameOffsets( wrapper );
for ( PxU32 idx = 0; idx < numDefaults; ++idx )
{
const RepXDefaultEntry& item( defaults[idx] );
size_t nameLen = 0;
const char* periodPtr = nextPeriod (item.name);
for ( ; periodPtr && *periodPtr; ++periodPtr ) if( *periodPtr == '.' ) break;
if ( periodPtr == NULL || *periodPtr != '.' ) continue;
nameLen = size_t(periodPtr - item.name);
char* newMem = reinterpret_cast<char*>(alloc.allocate( PxU32(nameLen + 1) ));
PxMemCopy( newMem, item.name, PxU32(nameLen) );
newMem[nameLen] = 0;
if ( nameOffsets.find( newMem ) )
alloc.deallocate( reinterpret_cast<PxU8*>(newMem) );
else
nameOffsets.insert( newMem, idx );
}
//Run through each collection item, and recursively find it and its children
//If an object's name is in the hash map, check and add any properties that don't exist.
//else return.
for ( const RepXCollectionItem* item = collection.begin(), *end = collection.end(); item != end; ++ item )
{
RepXCollectionItem theItem( *item );
setMissingPropertiesToDefault( theItem.descriptor, editor, defaults, numDefaults, nameOffsets );
}
}
struct RecursiveTraversal
{
RecursiveTraversal(XmlReaderWriter& editor): mEditor(editor) {}
void traverse()
{
mEditor.pushCurrentContext();
updateNode();
for(bool exists = mEditor.gotoFirstChild(); exists; exists = mEditor.gotoNextSibling())
traverse();
mEditor.popCurrentContext();
}
virtual void updateNode() = 0;
virtual ~RecursiveTraversal() {}
XmlReaderWriter& mEditor;
protected:
RecursiveTraversal& operator=(const RecursiveTraversal&){return *this;}
};
RepXCollection& RepXUpgrader::upgrade10CollectionTo3_1Collection(RepXCollection& src)
{
XmlReaderWriter& editor( src.createNodeEditor() );
setMissingPropertiesToDefault(src, editor, gRepX1_0Defaults, gNumRepX1_0Default );
RepXCollection* dest = &src.createCollection("3.1.1");
for ( const RepXCollectionItem* item = src.begin(), *end = src.end(); item != end; ++ item )
{
//either src or dest could do the copy operation, it doesn't matter who does it.
RepXCollectionItem newItem( item->liveObject, src.copyRepXNode( item->descriptor ) );
editor.setNode( *const_cast<XmlNode*>( newItem.descriptor ) );
//Some old files have this name in their system.
editor.renameProperty( "MassSpaceInertia", "MassSpaceInertiaTensor" );
editor.renameProperty( "SleepEnergyThreshold", "SleepThreshold" );
if ( strstr( newItem.liveObject.typeName, "Joint" ) || strstr( newItem.liveObject.typeName, "joint" ) )
{
//Joints changed format a bit. old joints looked like:
/*
<Actor0 >1627536</Actor0>
<Actor1 >1628368</Actor1>
<LocalPose0 >0 0 0 1 0.5 0.5 0.5</LocalPose0>
<LocalPose1 >0 0 0 1 0.3 0.3 0.3</LocalPose1>*/
//New joints look like:
/*
<Actors >
<actor0 >58320336</actor0>
<actor1 >56353568</actor1>
</Actors>
<LocalPose >
<eACTOR0 >0 0 0 1 0.5 0.5 0.5</eACTOR0>
<eACTOR1 >0 0 0 1 0.3 0.3 0.3</eACTOR1>
</LocalPose>
*/
const char* actor0, *actor1, *lp0, *lp1;
editor.readAndRemoveProperty( "Actor0", actor0 );
editor.readAndRemoveProperty( "Actor1", actor1 );
editor.readAndRemoveProperty( "LocalPose0", lp0 );
editor.readAndRemoveProperty( "LocalPose1", lp1 );
editor.addOrGotoChild( "Actors" );
editor.writePropertyIfNotEmpty( "actor0", actor0 );
editor.writePropertyIfNotEmpty( "actor1", actor1 );
editor.leaveChild();
editor.addOrGotoChild( "LocalPose" );
editor.writePropertyIfNotEmpty( "eACTOR0", lp0 );
editor.writePropertyIfNotEmpty( "eACTOR1", lp1 );
editor.leaveChild();
}
//now desc owns the new node. Collections share a single allocation pool, however,
//which will get destroyed when all the collections referencing it are destroyed themselves.
//Data on nodes is shared between nodes, but the node structure itself is allocated.
dest->addCollectionItem( newItem );
}
editor.release();
src.destroy();
return *dest;
}
RepXCollection& RepXUpgrader::upgrade3_1CollectionTo3_2Collection(RepXCollection& src)
{
XmlReaderWriter& editor( src.createNodeEditor() );
setMissingPropertiesToDefault(src, editor, gRepX3_1Defaults, gNumRepX3_1Defaults );
RepXCollection* dest = &src.createCollection("3.2.0");
for ( const RepXCollectionItem* item = src.begin(), *end = src.end(); item != end; ++ item )
{
//either src or dest could do the copy operation, it doesn't matter who does it.
RepXCollectionItem newItem( item->liveObject, src.copyRepXNode( item->descriptor ) );
editor.setNode( *const_cast<XmlNode*>( newItem.descriptor ) );
if ( strstr( newItem.liveObject.typeName, "PxMaterial" ) )
{
editor.removeChild( "DynamicFrictionV" );
editor.removeChild( "StaticFrictionV" );
editor.removeChild( "dirOfAnisotropy" );
}
//now desc owns the new node. Collections share a single allocation pool, however,
//which will get destroyed when all the collections referencing it are destroyed themselves.
//Data on nodes is shared between nodes, but the node structure itself is allocated.
dest->addCollectionItem( newItem );
}
editor.release();
src.destroy();
return *dest;
}
RepXCollection& RepXUpgrader::upgrade3_2CollectionTo3_3Collection(RepXCollection& src)
{
XmlReaderWriter& editor( src.createNodeEditor() );
setMissingPropertiesToDefault(src, editor, gRepX3_2Defaults, gNumRepX3_2Defaults );
RepXCollection* dest = &src.createCollection("3.3.0");
struct RenameSpringToStiffness : public RecursiveTraversal
{
RenameSpringToStiffness(XmlReaderWriter& editor_): RecursiveTraversal(editor_) {}
void updateNode()
{
mEditor.renameProperty("Spring", "Stiffness");
mEditor.renameProperty("TangentialSpring", "TangentialStiffness");
}
};
struct UpdateArticulationSwingLimit : public RecursiveTraversal
{
UpdateArticulationSwingLimit(XmlReaderWriter& editor_): RecursiveTraversal(editor_) {}
void updateNode()
{
if(!Pxstricmp(mEditor.getCurrentItemName(), "yLimit") && !Pxstricmp(mEditor.getCurrentItemValue(), "0"))
mEditor.setCurrentItemValue("0.785398");
if(!Pxstricmp(mEditor.getCurrentItemName(), "zLimit") && !Pxstricmp(mEditor.getCurrentItemValue(), "0"))
mEditor.setCurrentItemValue("0.785398");
if(!Pxstricmp(mEditor.getCurrentItemName(), "TwistLimit"))
{
mEditor.gotoFirstChild();
PxReal lower = PxReal(strtod(mEditor.getCurrentItemValue(), NULL));
mEditor.gotoNextSibling();
PxReal upper = PxReal(strtod(mEditor.getCurrentItemValue(), NULL));
mEditor.leaveChild();
if(lower>=upper)
{
mEditor.writePropertyIfNotEmpty("lower", "-0.785398");
mEditor.writePropertyIfNotEmpty("upper", "0.785398");
}
}
}
};
for ( const RepXCollectionItem* item = src.begin(), *end = src.end(); item != end; ++ item )
{
//either src or dest could do the copy operation, it doesn't matter who does it.
RepXCollectionItem newItem( item->liveObject, src.copyRepXNode( item->descriptor ) );
if ( strstr( newItem.liveObject.typeName, "PxCloth" ) || strstr( newItem.liveObject.typeName, "PxClothFabric" ) )
{
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "Didn't suppot PxCloth upgrate from 3.2 to 3.3! ");
continue;
}
if ( strstr( newItem.liveObject.typeName, "PxParticleSystem" ) || strstr( newItem.liveObject.typeName, "PxParticleFluid" ) )
{
editor.setNode( *const_cast<XmlNode*>( newItem.descriptor ) );
editor.renameProperty( "PositionBuffer", "Positions" );
editor.renameProperty( "VelocityBuffer", "Velocities" );
editor.renameProperty( "RestOffsetBuffer", "RestOffsets" );
}
if(strstr(newItem.liveObject.typeName, "PxPrismaticJoint" )
|| strstr(newItem.liveObject.typeName, "PxRevoluteJoint")
|| strstr(newItem.liveObject.typeName, "PxSphericalJoint")
|| strstr(newItem.liveObject.typeName, "PxD6Joint")
|| strstr(newItem.liveObject.typeName, "PxArticulation"))
{
editor.setNode( *const_cast<XmlNode*>( newItem.descriptor ) );
RenameSpringToStiffness(editor).traverse();
}
if(strstr(newItem.liveObject.typeName, "PxArticulation"))
{
editor.setNode( *const_cast<XmlNode*>( newItem.descriptor ) );
UpdateArticulationSwingLimit(editor).traverse();
}
//now dest owns the new node. Collections share a single allocation pool, however,
//which will get destroyed when all the collections referencing it are destroyed themselves.
//Data on nodes is shared between nodes, but the node structure itself is allocated.
dest->addCollectionItem( newItem );
}
editor.release();
src.destroy();
return *dest;
}
RepXCollection& RepXUpgrader::upgrade3_3CollectionTo3_4Collection(RepXCollection& src)
{
RepXCollection* dest = &src.createCollection("3.4.0");
for ( const RepXCollectionItem* item = src.begin(), *end = src.end(); item != end; ++ item )
{
if(strstr(item->liveObject.typeName, "PxTriangleMesh"))
{
PxRepXObject newMeshRepXObj("PxBVH33TriangleMesh", item->liveObject.serializable, item->liveObject.id);
XmlNode* newMeshNode = src.copyRepXNode( item->descriptor );
newMeshNode->mName = "PxBVH33TriangleMesh";
RepXCollectionItem newMeshItem(newMeshRepXObj, newMeshNode);
dest->addCollectionItem( newMeshItem );
continue;
}
RepXCollectionItem newItem( item->liveObject, src.copyRepXNode( item->descriptor ) );
dest->addCollectionItem( newItem );
}
src.destroy();
return *dest;
}
RepXCollection& RepXUpgrader::upgrade3_4CollectionTo4_0Collection(RepXCollection& src)
{
RepXCollection* dest = &src.createCollection("4.0.0");
for (const RepXCollectionItem* item = src.begin(), *end = src.end(); item != end; ++item)
{
if (strstr(item->liveObject.typeName, "PxParticleFluid") ||
strstr(item->liveObject.typeName, "PxParticleSystem") ||
strstr(item->liveObject.typeName, "PxClothFabric") ||
strstr(item->liveObject.typeName, "PxCloth"))
{
continue;
}
RepXCollectionItem newItem(item->liveObject, src.copyRepXNode(item->descriptor));
dest->addCollectionItem(newItem);
}
src.destroy();
return *dest;
}
RepXCollection& RepXUpgrader::upgradeCollection(RepXCollection& src)
{
const char* srcVersion = src.getVersion();
if( safeStrEq( srcVersion, RepXCollection::getLatestVersion() ))
return src;
typedef RepXCollection& (*UPGRADE_FUNCTION)(RepXCollection& src);
struct Upgrade { const char* versionString; UPGRADE_FUNCTION upgradeFunction; };
static const Upgrade upgradeTable[] =
{
{ "1.0", upgrade10CollectionTo3_1Collection },
{ "3.1", NULL },
{ "3.1.1", upgrade3_1CollectionTo3_2Collection },
{ "3.2.0", upgrade3_2CollectionTo3_3Collection },
{ "3.3.0", NULL },
{ "3.3.1", NULL },
{ "3.3.2", NULL },
{ "3.3.3", NULL },
{ "3.3.4", upgrade3_3CollectionTo3_4Collection },
{ "3.4.0", NULL },
{ "3.4.1", NULL },
{ "3.4.2", upgrade3_4CollectionTo4_0Collection }
}; //increasing order and complete
const PxU32 upgradeTableSize = sizeof(upgradeTable)/sizeof(upgradeTable[0]);
PxU32 repxVersion = UINT16_MAX;
for (PxU32 i=0; i<upgradeTableSize; i++)
{
if( safeStrEq( srcVersion, upgradeTable[i].versionString ))
{
repxVersion = i;
break;
}
}
RepXCollection* dest = &src;
for( PxU32 j = repxVersion; j < upgradeTableSize; j++ )
{
if( upgradeTable[j].upgradeFunction )
dest = &(upgradeTable[j].upgradeFunction)(*dest);
}
return *dest;
}
} }
| 16,783 | C++ | 35.25054 | 154 | 0.694631 |
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepXCoreSerializer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef SN_REPX_CORE_SERIALIZER_H
#define SN_REPX_CORE_SERIALIZER_H
/** \addtogroup RepXSerializers
@{
*/
#include "foundation/PxSimpleTypes.h"
#include "SnRepXSerializerImpl.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class XmlReader;
class XmlMemoryAllocator;
class XmlWriter;
class MemoryBuffer;
struct PX_DEPRECATED PxMaterialRepXSerializer : RepXSerializerImpl<PxMaterial>
{
PxMaterialRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxMaterial>( inCallback ) {}
virtual PxMaterial* allocateObject( PxRepXInstantiationArgs& );
};
struct PX_DEPRECATED PxShapeRepXSerializer : public RepXSerializerImpl<PxShape>
{
PxShapeRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxShape>( inCallback ) {}
virtual PxRepXObject fileToObject( XmlReader&, XmlMemoryAllocator&, PxRepXInstantiationArgs&, PxCollection* );
virtual PxShape* allocateObject( PxRepXInstantiationArgs& ) { return NULL; }
};
struct PX_DEPRECATED PxBVH33TriangleMeshRepXSerializer : public RepXSerializerImpl<PxBVH33TriangleMesh>
{
PxBVH33TriangleMeshRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxBVH33TriangleMesh>( inCallback ) {}
virtual void objectToFileImpl( const PxBVH33TriangleMesh*, PxCollection*, XmlWriter&, MemoryBuffer&, PxRepXInstantiationArgs& );
virtual PxRepXObject fileToObject( XmlReader&, XmlMemoryAllocator&, PxRepXInstantiationArgs&, PxCollection* );
virtual PxBVH33TriangleMesh* allocateObject( PxRepXInstantiationArgs& ) { return NULL; }
};
struct PX_DEPRECATED PxBVH34TriangleMeshRepXSerializer : public RepXSerializerImpl<PxBVH34TriangleMesh>
{
PxBVH34TriangleMeshRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxBVH34TriangleMesh>( inCallback ) {}
virtual void objectToFileImpl( const PxBVH34TriangleMesh*, PxCollection*, XmlWriter&, MemoryBuffer&, PxRepXInstantiationArgs& );
virtual PxRepXObject fileToObject( XmlReader&, XmlMemoryAllocator&, PxRepXInstantiationArgs&, PxCollection* );
virtual PxBVH34TriangleMesh* allocateObject( PxRepXInstantiationArgs& ) { return NULL; }
};
struct PX_DEPRECATED PxHeightFieldRepXSerializer : public RepXSerializerImpl<PxHeightField>
{
PxHeightFieldRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxHeightField>( inCallback ) {}
virtual void objectToFileImpl( const PxHeightField*, PxCollection*, XmlWriter&, MemoryBuffer&, PxRepXInstantiationArgs& );
virtual PxRepXObject fileToObject( XmlReader&, XmlMemoryAllocator&, PxRepXInstantiationArgs&, PxCollection* );
virtual PxHeightField* allocateObject( PxRepXInstantiationArgs& ) { return NULL; }
};
struct PX_DEPRECATED PxConvexMeshRepXSerializer : public RepXSerializerImpl<PxConvexMesh>
{
PxConvexMeshRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxConvexMesh>( inCallback ) {}
virtual void objectToFileImpl( const PxConvexMesh*, PxCollection*, XmlWriter&, MemoryBuffer&, PxRepXInstantiationArgs& );
virtual PxRepXObject fileToObject( XmlReader&, XmlMemoryAllocator&, PxRepXInstantiationArgs&, PxCollection* );
virtual PxConvexMesh* allocateObject( PxRepXInstantiationArgs& ) { return NULL; }
};
struct PX_DEPRECATED PxRigidStaticRepXSerializer : public RepXSerializerImpl<PxRigidStatic>
{
PxRigidStaticRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxRigidStatic>( inCallback ) {}
virtual PxRigidStatic* allocateObject( PxRepXInstantiationArgs& );
};
struct PX_DEPRECATED PxRigidDynamicRepXSerializer : public RepXSerializerImpl<PxRigidDynamic>
{
PxRigidDynamicRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxRigidDynamic>( inCallback ) {}
virtual PxRigidDynamic* allocateObject( PxRepXInstantiationArgs& );
};
struct PX_DEPRECATED PxArticulationReducedCoordinateRepXSerializer : public RepXSerializerImpl<PxArticulationReducedCoordinate>
{
PxArticulationReducedCoordinateRepXSerializer(PxAllocatorCallback& inCallback) : RepXSerializerImpl<PxArticulationReducedCoordinate>(inCallback) {}
virtual void objectToFileImpl(const PxArticulationReducedCoordinate*, PxCollection*, XmlWriter&, MemoryBuffer&, PxRepXInstantiationArgs&);
virtual PxArticulationReducedCoordinate* allocateObject(PxRepXInstantiationArgs&);
};
struct PX_DEPRECATED PxAggregateRepXSerializer : public RepXSerializerImpl<PxAggregate>
{
PxAggregateRepXSerializer( PxAllocatorCallback& inCallback ) : RepXSerializerImpl<PxAggregate>( inCallback ) {}
virtual void objectToFileImpl( const PxAggregate*, PxCollection*, XmlWriter& , MemoryBuffer&, PxRepXInstantiationArgs& );
virtual PxRepXObject fileToObject( XmlReader&, XmlMemoryAllocator&, PxRepXInstantiationArgs&, PxCollection* );
virtual PxAggregate* allocateObject( PxRepXInstantiationArgs& ) { return NULL; }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
/** @} */
| 6,597 | C | 51.365079 | 149 | 0.799151 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.