file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingConvexHullLib.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_COOKING_CONVEX_HULL_LIB_H #define GU_COOKING_CONVEX_HULL_LIB_H #include "cooking/PxConvexMeshDesc.h" #include "cooking/PxCooking.h" namespace physx { ////////////////////////////////////////////////////////////////////////// // base class for the convex hull libraries - inflation based and quickhull class ConvexHullLib { PX_NOCOPY(ConvexHullLib) public: // functions ConvexHullLib(const PxConvexMeshDesc& desc, const PxCookingParams& params) : mConvexMeshDesc(desc), mCookingParams(params), mSwappedIndices(NULL), mShiftedVerts(NULL) { } virtual ~ConvexHullLib(); // computes the convex hull from provided points virtual PxConvexMeshCookingResult::Enum createConvexHull() = 0; // fills the PxConvexMeshDesc with computed hull data virtual void fillConvexMeshDesc(PxConvexMeshDesc& desc) = 0; // compute the edge list information if possible virtual bool createEdgeList(const PxU32 nbIndices, const PxU8* indices, PxU8** hullDataFacesByEdges8, PxU16** edgeData16, PxU16** edges) = 0; static const PxU32 gpuMaxVertsPerFace = 31; protected: // clean input vertices from duplicates, normalize etc. bool cleanupVertices(PxU32 svcount, // input vertex count const PxVec3* svertices, // vertices PxU32 stride, // stride PxU32& vcount, // output number of vertices PxVec3* vertices); // location to store the results. // shift vertices around origin and clean input vertices from duplicates, normalize etc. bool shiftAndcleanupVertices(PxU32 svcount, // input vertex count const PxVec3* svertices, // vertices PxU32 stride, // stride PxU32& vcount, // output number of vertices PxVec3* vertices); // location to store the results. void swapLargestFace(PxConvexMeshDesc& desc); void shiftConvexMeshDesc(PxConvexMeshDesc& desc); protected: const PxConvexMeshDesc& mConvexMeshDesc; const PxCookingParams& mCookingParams; PxU32* mSwappedIndices; PxVec3 mOriginShift; PxVec3* mShiftedVerts; }; } #endif
3,729
C
39.107526
143
0.73934
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/cooking/GuCookingQuickHullConvexHullLib.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_COOKING_QUICKHULL_CONVEXHULLLIB_H #define GU_COOKING_QUICKHULL_CONVEXHULLLIB_H #include "GuCookingConvexHullLib.h" #include "foundation/PxArray.h" #include "foundation/PxUserAllocated.h" namespace local { class QuickHull; struct QuickHullVertex; } namespace physx { class ConvexHull; ////////////////////////////////////////////////////////////////////////// // Quickhull lib constructs the hull from given input points. The resulting hull // will only contain a subset of the input points. The algorithm does incrementally // adds most furthest vertices to the starting simplex. The produced hulls are build with high precision // and produce more stable and correct results, than the legacy algorithm. class QuickHullConvexHullLib: public ConvexHullLib, public PxUserAllocated { PX_NOCOPY(QuickHullConvexHullLib) public: // functions QuickHullConvexHullLib(const PxConvexMeshDesc& desc, const PxCookingParams& params); ~QuickHullConvexHullLib(); // computes the convex hull from provided points virtual PxConvexMeshCookingResult::Enum createConvexHull(); // fills the convexmeshdesc with computed hull data virtual void fillConvexMeshDesc(PxConvexMeshDesc& desc); // provide the edge list information virtual bool createEdgeList(const PxU32, const PxU8* , PxU8** , PxU16** , PxU16** ); protected: // if vertex limit reached we need to expand the hull using the OBB slicing PxConvexMeshCookingResult::Enum expandHullOBB(); // if vertex limit reached we need to expand the hull using the plane shifting PxConvexMeshCookingResult::Enum expandHull(); // checks for collinearity and co planarity // returns true if the simplex was ok, we can reuse the computed tolerances and min/max values bool cleanupForSimplex(PxVec3* vertices, PxU32 vertexCount, local::QuickHullVertex* minimumVertex, local::QuickHullVertex* maximumVertex, float& tolerance, float& planeTolerance); // fill the result desc from quick hull convex void fillConvexMeshDescFromQuickHull(PxConvexMeshDesc& desc); // fill the result desc from cropped hull convex void fillConvexMeshDescFromCroppedHull(PxConvexMeshDesc& desc); private: local::QuickHull* mQuickHull; // the internal quick hull representation ConvexHull* mCropedConvexHull; //the hull cropped from OBB, used for vertex limit path PxU8* mOutMemoryBuffer; // memory buffer used for output data PxU16* mFaceTranslateTable; // translation table mapping output faces to internal quick hull table }; } #endif
4,242
C
42.295918
105
0.759547
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuOverlapTestsHF.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 "GuOverlapTests.h" #include "GuHeightFieldUtil.h" #include "GuBoxConversion.h" #include "GuInternal.h" #include "GuVecConvexHull.h" #include "GuEntityReport.h" #include "GuDistancePointTriangle.h" #include "GuIntersectionCapsuleTriangle.h" #include "GuDistanceSegmentTriangle.h" #include "GuBounds.h" #include "GuBV4_Common.h" #include "GuVecTriangle.h" #include "GuConvexMesh.h" #include "GuGJK.h" #include "geometry/PxSphereGeometry.h" using namespace physx; using namespace Gu; using namespace aos; /////////////////////////////////////////////////////////////////////////////// namespace { struct HeightfieldOverlapReport : Gu::OverlapReport { PX_NOCOPY(HeightfieldOverlapReport) public: HeightfieldOverlapReport(const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose) : mHfUtil(hfGeom), mHFPose(hfPose), mOverlap(PxIntFalse) {} const HeightFieldUtil mHfUtil; const PxTransform& mHFPose; PxIntBool mOverlap; }; } bool GeomOverlapCallback_SphereHeightfield(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eSPHERE); PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom0); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1); struct SphereOverlapReport : HeightfieldOverlapReport { Sphere mLocalSphere; SphereOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose, const PxVec3& localSphereCenter, float sphereRadius) : HeightfieldOverlapReport(hfGeom_, hfPose) { mLocalSphere.center = localSphereCenter; mLocalSphere.radius = sphereRadius * sphereRadius; } virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { while(nb--) { const PxU32 triangleIndex = *indices++; PxTriangle currentTriangle; mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false); const PxVec3& p0 = currentTriangle.verts[0]; const PxVec3& p1 = currentTriangle.verts[1]; const PxVec3& p2 = currentTriangle.verts[2]; const PxVec3 edge10 = p1 - p0; const PxVec3 edge20 = p2 - p0; const PxVec3 cp = closestPtPointTriangle2(mLocalSphere.center, p0, p1, p2, edge10, edge20); const float sqrDist = (cp - mLocalSphere.center).magnitudeSquared(); if(sqrDist <= mLocalSphere.radius) // mLocalSphere.radius has been pre-squared in the ctor { mOverlap = PxIntTrue; return false; } } return true; } }; PxBounds3 localBounds; const PxVec3 localSphereCenter = getLocalSphereData(localBounds, pose0, pose1, sphereGeom.radius); SphereOverlapReport report(hfGeom, pose1, localSphereCenter, sphereGeom.radius); report.mHfUtil.overlapAABBTriangles(localBounds, report, 4); return report.mOverlap!=PxIntFalse; } /////////////////////////////////////////////////////////////////////////////// bool GeomOverlapCallback_CapsuleHeightfield(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eCAPSULE); PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom0); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1); struct CapsuleOverlapReport : HeightfieldOverlapReport { Capsule mLocalCapsule; CapsuleTriangleOverlapData mData; CapsuleOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose) : HeightfieldOverlapReport(hfGeom_, hfPose) {} virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { while(nb--) { const PxU32 triangleIndex = *indices++; PxTriangle currentTriangle; mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false); const PxVec3& p0 = currentTriangle.verts[0]; const PxVec3& p1 = currentTriangle.verts[1]; const PxVec3& p2 = currentTriangle.verts[2]; if(0) { PxReal t,u,v; const PxVec3 p1_p0 = p1 - p0; const PxVec3 p2_p0 = p2 - p0; const PxReal sqrDist = distanceSegmentTriangleSquared(mLocalCapsule, p0, p1_p0, p2_p0, &t, &u, &v); if(sqrDist <= mLocalCapsule.radius*mLocalCapsule.radius) { mOverlap = PxIntTrue; return false; } } else { const PxVec3 normal = (p0 - p1).cross(p0 - p2); if(intersectCapsuleTriangle(normal, p0, p1, p2, mLocalCapsule, mData)) { mOverlap = PxIntTrue; return false; } } } return true; } }; CapsuleOverlapReport report(hfGeom, pose1); // PT: TODO: move away from internal header const PxVec3 tmp = getCapsuleHalfHeightVector(pose0, capsuleGeom); // PT: TODO: refactor - but might be difficult because we reuse relPose for two tasks here const PxTransform relPose = pose1.transformInv(pose0); const PxVec3 localDelta = pose1.rotateInv(tmp); report.mLocalCapsule.p0 = relPose.p + localDelta; report.mLocalCapsule.p1 = relPose.p - localDelta; report.mLocalCapsule.radius = capsuleGeom.radius; report.mData.init(report.mLocalCapsule); PxBounds3 localBounds; computeCapsuleBounds(localBounds, capsuleGeom, relPose); report.mHfUtil.overlapAABBTriangles(localBounds, report, 4); //hfUtil.overlapAABBTriangles(pose0, pose1, getLocalCapsuleBounds(capsuleGeom.radius, capsuleGeom.halfHeight), report, 4); return report.mOverlap!=PxIntFalse; } /////////////////////////////////////////////////////////////////////////////// PxIntBool intersectTriangleBoxBV4(const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, const PxMat33& rotModelToBox, const PxVec3& transModelToBox, const PxVec3& extents); bool GeomOverlapCallback_BoxHeightfield(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eBOX); PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom0); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1); struct BoxOverlapReport : HeightfieldOverlapReport { PxMat33 mRModelToBox; PxVec3p mTModelToBox; PxVec3p mBoxExtents; BoxOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose) : HeightfieldOverlapReport(hfGeom_, hfPose) {} virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { while(nb--) { const PxU32 triangleIndex = *indices++; PxTrianglePadded currentTriangle; mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false); if(intersectTriangleBoxBV4(currentTriangle.verts[0], currentTriangle.verts[1], currentTriangle.verts[2], mRModelToBox, mTModelToBox, mBoxExtents)) { mOverlap = PxIntTrue; return false; } } return true; } }; BoxOverlapReport report(hfGeom, pose1); // PT: TODO: revisit / refactor all this code const PxTransform relPose = pose1.transformInv(pose0); Box localBox; buildFrom(localBox, relPose.p, boxGeom.halfExtents, relPose.q); invertBoxMatrix(report.mRModelToBox, report.mTModelToBox, localBox); report.mBoxExtents = localBox.extents; PxBounds3 localBounds; { // PT: TODO: refactor with bounds code? const PxMat33& basis = localBox.rot; // extended basis vectors const Vec4V c0V = V4Scale(V4LoadU(&basis.column0.x), FLoad(localBox.extents.x)); const Vec4V c1V = V4Scale(V4LoadU(&basis.column1.x), FLoad(localBox.extents.y)); const Vec4V c2V = V4Scale(V4LoadU(&basis.column2.x), FLoad(localBox.extents.z)); // find combination of base vectors that produces max. distance for each component = sum of abs() Vec4V extentsV = V4Add(V4Abs(c0V), V4Abs(c1V)); extentsV = V4Add(extentsV, V4Abs(c2V)); const PxVec3p origin(localBox.center); const Vec4V originV = V4LoadU(&origin.x); const Vec4V minV = V4Sub(originV, extentsV); const Vec4V maxV = V4Add(originV, extentsV); StoreBounds(localBounds, minV, maxV); } report.mHfUtil.overlapAABBTriangles(localBounds, report, 4); return report.mOverlap!=PxIntFalse; } /////////////////////////////////////////////////////////////////////////////// bool GeomOverlapCallback_ConvexHeightfield(GU_OVERLAP_FUNC_PARAMS) { PX_ASSERT(geom0.getType()==PxGeometryType::eCONVEXMESH); PX_ASSERT(geom1.getType()==PxGeometryType::eHEIGHTFIELD); PX_UNUSED(cache); PX_UNUSED(threadContext); const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom0); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom1); struct ConvexOverlapReport : HeightfieldOverlapReport { ConvexHullV mConvex; PxMatTransformV aToB; ConvexOverlapReport(const PxHeightFieldGeometry& hfGeom_, const PxTransform& hfPose) : HeightfieldOverlapReport(hfGeom_, hfPose) {} virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { while(nb--) { const PxU32 triangleIndex = *indices++; PxTrianglePadded currentTriangle; mHfUtil.getTriangle(mHFPose, currentTriangle, NULL, NULL, triangleIndex, false, false); const PxVec3& p0 = currentTriangle.verts[0]; const PxVec3& p1 = currentTriangle.verts[1]; const PxVec3& p2 = currentTriangle.verts[2]; // PT: TODO: consider adding an extra triangle-vs-box culling test here // PT: TODO: optimize const Vec3V v0 = V3LoadU(p0); const Vec3V v1 = V3LoadU(p1); const Vec3V v2 = V3LoadU(p2); // PT: TODO: refactor with ConvexVsMeshOverlapCallback TriangleV triangle(v0, v1, v2); Vec3V contactA, contactB, normal; FloatV dist; const RelativeConvex<TriangleV> convexA(triangle, aToB); const LocalConvex<ConvexHullV> convexB(mConvex); const GjkStatus status = gjk(convexA, convexB, aToB.p, FZero(), contactA, contactB, normal, dist); if(status == GJK_CONTACT || status == GJK_CLOSE)// || FAllGrtrOrEq(mSqTolerance, sqDist)) { mOverlap = PxIntTrue; return false; } } return true; } }; ConvexOverlapReport report(hfGeom, pose1); const ConvexMesh* cm = static_cast<const ConvexMesh*>(convexGeom.convexMesh); const bool idtScaleConvex = convexGeom.scale.isIdentity(); { const ConvexHullData* hullData = &cm->getHull(); const Vec3V vScale0 = V3LoadU_SafeReadW(convexGeom.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat0 = QuatVLoadU(&convexGeom.scale.rotation.x); report.mConvex = ConvexHullV(hullData, V3Zero(), vScale0, vQuat0, idtScaleConvex); // PT: TODO: is that transform correct? It looks like the opposite of what we do for other prims? report.aToB = PxMatTransformV(pose0.transformInv(pose1)); //report.aToB = PxMatTransformV(pose1.transformInv(pose0)); } const PxTransform relPose = pose1.transformInv(pose0); PxBounds3 localBounds; computeBounds(localBounds, convexGeom, relPose, 0.0f, 1.0f); report.mHfUtil.overlapAABBTriangles(localBounds, report, 4); return report.mOverlap!=PxIntFalse; }
12,744
C++
34.207182
183
0.726381
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightField.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_HEIGHTFIELD_H #define GU_HEIGHTFIELD_H #include "geometry/PxHeightFieldSample.h" #include "geometry/PxHeightFieldDesc.h" #include "geometry/PxHeightField.h" #include "geometry/PxHeightFieldGeometry.h" #include "foundation/PxUserAllocated.h" #include "CmRefCountable.h" #include "GuSphere.h" #include "GuHeightFieldData.h" //#define PX_HEIGHTFIELD_VERSION 0 //#define PX_HEIGHTFIELD_VERSION 1 // tiled version that was needed for PS3 only has been removed #define PX_HEIGHTFIELD_VERSION 2 // some floats are now integers namespace physx { class PxHeightFieldDesc; namespace Gu { class MeshFactory; class HeightField : public PxHeightField, public PxUserAllocated { public: // PX_SERIALIZATION HeightField(PxBaseFlags baseFlags) : PxHeightField(baseFlags), mData(PxEmpty), mModifyCount(0) {} void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); PX_FORCE_INLINE void setMeshFactory(MeshFactory* f) { mMeshFactory = f; } PX_PHYSX_COMMON_API static HeightField* createObject(PxU8*& address, PxDeserializationContext& context); PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream); void resolveReferences(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&){} //~PX_SERIALIZATION HeightField(MeshFactory* factory); HeightField(MeshFactory* factory, Gu::HeightFieldData& data); // PxHeightField virtual void release(); virtual PxU32 saveCells(void* destBuffer, PxU32 destBufferSize) const; virtual bool modifySamples(PxI32 startCol, PxI32 startRow, const PxHeightFieldDesc& subfieldDesc, bool shrinkBounds); virtual PxU32 getNbRows() const { return mData.rows; } virtual PxU32 getNbColumns() const { return mData.columns; } virtual PxHeightFieldFormat::Enum getFormat() const { return mData.format; } virtual PxU32 getSampleStride() const { return sizeof(PxHeightFieldSample); } virtual PxReal getConvexEdgeThreshold() const { return mData.convexEdgeThreshold; } virtual PxHeightFieldFlags getFlags() const { return mData.flags; } virtual PxReal getHeight(PxReal x, PxReal z) const { return getHeightInternal(x, z); } virtual PxMaterialTableIndex getTriangleMaterialIndex(PxTriangleID triangleIndex) const { return getTriangleMaterial(triangleIndex); } virtual PxVec3 getTriangleNormal(PxTriangleID triangleIndex) const { return getTriangleNormalInternal(triangleIndex); } virtual const PxHeightFieldSample& getSample(PxU32 row, PxU32 column) const { const PxU32 cell = row * getNbColumnsFast() + column; return getSample(cell); } virtual PxU32 getTimestamp() const { return mModifyCount; } //~PxHeightField // PxRefCounted virtual void acquireReference(); virtual PxU32 getReferenceCount() const; //~PxRefCounted // PxBase virtual void onRefCountZero(); //~PxBase bool loadFromDesc(const PxHeightFieldDesc&); bool load(PxInputStream&); bool save(PxOutputStream& stream, bool endianSwap); PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbRowsFast() const { return mData.rows; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNbColumnsFast() const { return mData.columns; } PX_FORCE_INLINE PxHeightFieldFormat::Enum getFormatFast() const { return mData.format; } PX_FORCE_INLINE PxU32 getFlagsFast() const { return mData.flags; } PX_CUDA_CALLABLE PX_FORCE_INLINE bool isZerothVertexShared(PxU32 vertexIndex) const { // return (getSample(vertexIndex).tessFlag & PxHeightFieldTessFlag::e0TH_VERTEX_SHARED); return getSample(vertexIndex).tessFlag() != 0; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex0(PxU32 vertexIndex) const { return getSample(vertexIndex).materialIndex0; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex1(PxU32 vertexIndex) const { return getSample(vertexIndex).materialIndex1; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaterialIndex01(PxU32 vertexIndex) const { const PxHeightFieldSample& sample = getSample(vertexIndex); return PxU32(sample.materialIndex0 | (sample.materialIndex1 << 16)); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getHeight(PxU32 vertexIndex) const { return PxReal(getSample(vertexIndex).height); } PX_INLINE PxReal getHeightInternal2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ) const; PX_FORCE_INLINE PxReal getHeightInternal(PxReal x, PxReal z) const { PxReal fracX, fracZ; const PxU32 vertexIndex = computeCellCoordinates(x, z, fracX, fracZ); return getHeightInternal2(vertexIndex, fracX, fracZ); } PX_FORCE_INLINE bool isValidVertex(PxU32 vertexIndex) const { return vertexIndex < mData.rows*mData.columns; } PX_INLINE PxVec3 getVertex(PxU32 vertexIndex) const; PX_INLINE bool isConvexVertex(PxU32 vertexIndex, PxU32 row, PxU32 column) const; PX_INLINE bool isValidEdge(PxU32 edgeIndex) const; PX_INLINE PxU32 getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2]) const; PX_INLINE PxU32 getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2], PxU32 cell, PxU32 row, PxU32 column) const; PX_INLINE void getEdgeVertexIndices(PxU32 edgeIndex, PxU32& vertexIndex0, PxU32& vertexIndex1) const; // PX_INLINE bool isConvexEdge(PxU32 edgeIndex) const; PX_INLINE bool isConvexEdge(PxU32 edgeIndex, PxU32 cell, PxU32 row, PxU32 column) const; PX_FORCE_INLINE bool isConvexEdge(PxU32 edgeIndex) const { const PxU32 cell = edgeIndex / 3; const PxU32 row = cell / mData.columns; const PxU32 column = cell % mData.columns; return isConvexEdge(edgeIndex, cell, row, column); } PxU32 computeCellCoordinates(PxReal x, PxReal z, PxReal& fracX, PxReal& fracZ) const; PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMin(PxReal x, PxU32 nb) const { if(x<0.0f) return 0; if(x>PxReal(nb)) return nb; const PxReal cx = PxFloor(x); const PxU32 icx = PxU32(cx); return icx; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMax(PxReal x, PxU32 nb) const { if(x<0.0f) return 0; if(x>PxReal(nb)) return nb; const PxReal cx = PxCeil(x); const PxU32 icx = PxU32(cx); return icx; } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMinRow(PxReal x) const { return getMin(x, mData.rows-2); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaxRow(PxReal x) const { return getMax(x, mData.rows-1); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMinColumn(PxReal z) const { return getMin(z, mData.columns-2); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaxColumn(PxReal z) const { return getMax(z, mData.columns-1); } PX_CUDA_CALLABLE PX_INLINE bool isValidTriangle(PxU32 triangleIndex) const; PX_CUDA_CALLABLE PX_FORCE_INLINE bool isFirstTriangle(PxU32 triangleIndex) const { return ((triangleIndex & 0x1) == 0); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getTriangleMaterial(PxU32 triangleIndex) const { return isFirstTriangle(triangleIndex) ? getMaterialIndex0(triangleIndex >> 1) : getMaterialIndex1(triangleIndex >> 1); } PX_CUDA_CALLABLE PX_INLINE void getTriangleVertexIndices(PxU32 triangleIndex, PxU32& vertexIndex0, PxU32& vertexIndex1, PxU32& vertexIndex2) const; PX_CUDA_CALLABLE PX_INLINE PxVec3 getTriangleNormalInternal(PxU32 triangleIndex) const; PX_INLINE void getTriangleAdjacencyIndices(PxU32 triangleIndex,PxU32 vertexIndex0, PxU32 vertexIndex1, PxU32 vertexIndex2, PxU32& adjacencyIndex0, PxU32& adjacencyIndex1, PxU32& adjacencyIndex2) const; PX_INLINE PxVec3 getNormal_2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ, PxReal xcoeff, PxReal ycoeff, PxReal zcoeff) const; PX_FORCE_INLINE PxVec3 getNormal_(PxReal x, PxReal z, PxReal xcoeff, PxReal ycoeff, PxReal zcoeff) const { PxReal fracX, fracZ; const PxU32 vertexIndex = computeCellCoordinates(x, z, fracX, fracZ); return getNormal_2(vertexIndex, fracX, fracZ, xcoeff, ycoeff, zcoeff); } PX_INLINE PxU32 getTriangleIndex(PxReal x, PxReal z) const; PX_INLINE PxU32 getTriangleIndex2(PxU32 cell, PxReal fracX, PxReal fracZ) const; PX_FORCE_INLINE PxU16 getMaterial(PxReal x, PxReal z) const { return getTriangleMaterial(getTriangleIndex(x, z)); } PX_FORCE_INLINE PxReal getMinHeight() const { return mMinHeight; } PX_FORCE_INLINE PxReal getMaxHeight() const { return mMaxHeight; } PX_FORCE_INLINE const Gu::HeightFieldData& getData() const { return mData; } PX_CUDA_CALLABLE PX_FORCE_INLINE void getTriangleVertices(PxU32 triangleIndex, PxU32 row, PxU32 column, PxVec3& v0, PxVec3& v1, PxVec3& v2) const; // checks if current vertex is solid or not bool isSolidVertex(PxU32 vertexIndex, PxU32 row, PxU32 coloumn, PxU16 holeMaterialIndex, bool& nbSolid) const; // PT: TODO: I think we could drop that whole precomputation thing now // if precomputed bitmap define is used, the collision vertex information // is precomputed during create height field and stored as a bit in materialIndex1 PX_PHYSX_COMMON_API bool isCollisionVertexPreca(PxU32 vertexIndex, PxU32 row, PxU32 column, PxU16 holeMaterialIndex) const; void parseTrianglesForCollisionVertices(PxU16 holeMaterialIndex); PX_CUDA_CALLABLE PX_FORCE_INLINE const PxHeightFieldSample& getSample(PxU32 vertexIndex) const { PX_ASSERT(isValidVertex(vertexIndex)); return mData.samples[vertexIndex]; } #ifdef __CUDACC__ PX_CUDA_CALLABLE void setSamplePtr(PxHeightFieldSample* s) { mData.samples = s; } #endif Gu::HeightFieldData mData; PxU32 mSampleStride; PxU32 mNbSamples; // PT: added for platform conversion. Try to remove later. PxReal mMinHeight; PxReal mMaxHeight; PxU32 mModifyCount; void releaseMemory(); virtual ~HeightField(); private: MeshFactory* mMeshFactory; // PT: changed to pointer for serialization }; } // namespace Gu PX_INLINE PxVec3 Gu::HeightField::getVertex(PxU32 vertexIndex) const { const PxU32 row = vertexIndex / mData.columns; const PxU32 column = vertexIndex % mData.columns; // return PxVec3(PxReal(row), getHeight(row * mData.columns + column), PxReal(column)); return PxVec3(PxReal(row), getHeight(vertexIndex), PxReal(column)); } // PT: only called from "isCollisionVertex", should move PX_INLINE bool Gu::HeightField::isConvexVertex(PxU32 vertexIndex, PxU32 row, PxU32 column) const { #ifdef PX_HEIGHTFIELD_DEBUG PX_ASSERT(isValidVertex(vertexIndex)); #endif PX_ASSERT((vertexIndex / mData.columns)==row); PX_ASSERT((vertexIndex % mData.columns)==column); // PxReal h0 = PxReal(2) * getHeight(vertexIndex); PxI32 h0 = getSample(vertexIndex).height; h0 += h0; bool definedInX, definedInZ; PxI32 convexityX, convexityZ; if ((row > 0) && (row < mData.rows - 1)) { // convexityX = h0 - getHeight(vertexIndex + mData.columns) - getHeight(vertexIndex - mData.columns); convexityX = h0 - getSample(vertexIndex + mData.columns).height - getSample(vertexIndex - mData.columns).height; definedInX = true; } else { convexityX = 0; definedInX = false; } if ((column > 0) && (column < mData.columns - 1)) { // convexityZ = h0 - getHeight(vertexIndex + 1) - getHeight(vertexIndex - 1); convexityZ = h0 - getSample(vertexIndex + 1).height - getSample(vertexIndex - 1).height; definedInZ = true; } else { convexityZ = 0; definedInZ = false; } if(definedInX || definedInZ) { // PT: use XOR here // saddle points /* if ((convexityX > 0) && (convexityZ < 0)) return false; if ((convexityX < 0) && (convexityZ > 0)) return false;*/ if(((convexityX ^ convexityZ) & 0x80000000)==0) return false; const PxReal value = PxReal(convexityX + convexityZ); return value > mData.convexEdgeThreshold; } // this has to be one of the two corner vertices return true; } PX_INLINE bool Gu::HeightField::isValidEdge(PxU32 edgeIndex) const { const PxU32 cell = (edgeIndex / 3); const PxU32 row = cell / mData.columns; const PxU32 column = cell % mData.columns; // switch (edgeIndex % 3) switch (edgeIndex - cell*3) { case 0: if (row > mData.rows - 1) return false; if (column >= mData.columns - 1) return false; break; case 1: if (row >= mData.rows - 1) return false; if (column >= mData.columns - 1) return false; break; case 2: if (row >= mData.rows - 1) return false; if (column > mData.columns - 1) return false; break; } return true; } PX_INLINE PxU32 Gu::HeightField::getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2]) const { const PxU32 cell = edgeIndex / 3; const PxU32 row = cell / mData.columns; const PxU32 column = cell % mData.columns; PxU32 count = 0; // switch (edgeIndex % 3) switch (edgeIndex - cell*3) { case 0: if (column < mData.columns - 1) { if (row > 0) { /* if (isZerothVertexShared(cell - mData.columns)) triangleIndices[count++] = ((cell - mData.columns) << 1); else triangleIndices[count++] = ((cell - mData.columns) << 1) + 1;*/ triangleIndices[count++] = ((cell - mData.columns) << 1) + 1 - isZerothVertexShared(cell - mData.columns); } if (row < mData.rows - 1) { /* if (isZerothVertexShared(cell)) triangleIndices[count++] = (cell << 1) + 1; else triangleIndices[count++] = cell << 1;*/ triangleIndices[count++] = (cell << 1) + isZerothVertexShared(cell); } } break; case 1: if ((row < mData.rows - 1) && (column < mData.columns - 1)) { triangleIndices[count++] = cell << 1; triangleIndices[count++] = (cell << 1) + 1; } break; case 2: if (row < mData.rows - 1) { if (column > 0) triangleIndices[count++] = ((cell - 1) << 1) + 1; if (column < mData.columns - 1) triangleIndices[count++] = cell << 1; } break; } return count; } PX_INLINE PxU32 Gu::HeightField::getEdgeTriangleIndices(PxU32 edgeIndex, PxU32 triangleIndices[2], PxU32 cell, PxU32 row, PxU32 column) const { // const PxU32 cell = edgeIndex / 3; // const PxU32 row = cell / mData.columns; // const PxU32 column = cell % mData.columns; PxU32 count = 0; // switch (edgeIndex % 3) switch (edgeIndex - cell*3) { case 0: if (column < mData.columns - 1) { if (row > 0) { /* if (isZerothVertexShared(cell - mData.columns)) triangleIndices[count++] = ((cell - mData.columns) << 1); else triangleIndices[count++] = ((cell - mData.columns) << 1) + 1;*/ triangleIndices[count++] = ((cell - mData.columns) << 1) + 1 - isZerothVertexShared(cell - mData.columns); } if (row < mData.rows - 1) { /* if (isZerothVertexShared(cell)) triangleIndices[count++] = (cell << 1) + 1; else triangleIndices[count++] = cell << 1;*/ triangleIndices[count++] = (cell << 1) + isZerothVertexShared(cell); } } break; case 1: if ((row < mData.rows - 1) && (column < mData.columns - 1)) { triangleIndices[count++] = cell << 1; triangleIndices[count++] = (cell << 1) + 1; } break; case 2: if (row < mData.rows - 1) { if (column > 0) triangleIndices[count++] = ((cell - 1) << 1) + 1; if (column < mData.columns - 1) triangleIndices[count++] = cell << 1; } break; } return count; } PX_INLINE void Gu::HeightField::getEdgeVertexIndices(PxU32 edgeIndex, PxU32& vertexIndex0, PxU32& vertexIndex1) const { const PxU32 cell = edgeIndex / 3; // switch (edgeIndex % 3) switch (edgeIndex - cell*3) { case 0: vertexIndex0 = cell; vertexIndex1 = cell + 1; break; case 1: { /* if (isZerothVertexShared(cell)) { vertexIndex0 = cell; vertexIndex1 = cell + mData.columns + 1; } else { vertexIndex0 = cell + 1; vertexIndex1 = cell + mData.columns; }*/ const bool b = isZerothVertexShared(cell); vertexIndex0 = cell + 1 - b; vertexIndex1 = cell + mData.columns + b; } break; case 2: vertexIndex0 = cell; vertexIndex1 = cell + mData.columns; break; } } PX_INLINE bool Gu::HeightField::isConvexEdge(PxU32 edgeIndex, PxU32 cell, PxU32 row, PxU32 column) const { // const PxU32 cell = edgeIndex / 3; PX_ASSERT(cell == edgeIndex / 3); // const PxU32 row = cell / mData.columns; PX_ASSERT(row == cell / mData.columns); if (row > mData.rows-2) return false; // const PxU32 column = cell % mData.columns; PX_ASSERT(column == cell % mData.columns); if (column > mData.columns-2) return false; // PxReal h0 = 0, h1 = 0, h2 = 0, h3 = 0; // PxReal convexity = 0; PxI32 h0 = 0, h1 = 0, h2 = 0, h3 = 0; PxI32 convexity = 0; // switch (edgeIndex % 3) switch (edgeIndex - cell*3) { case 0: { if (row < 1) return false; /* if(isZerothVertexShared(cell - mData.columns)) { // <------ COL // +----+ 0 R // | / /# O // | / / # W // | / / # | // |/ / # | // + +====1 | // | // | // | // | // | // | // V // // h0 = getHeight(cell - mData.columns); // h1 = getHeight(cell); h0 = getSample(cell - mData.columns).height; h1 = getSample(cell).height; } else { // <------ COL // 0 +----+ R // #\ \ | O // # \ \ | W // # \ \ | | // # \ \| | // 1====+ + | // | // | // | // | // | // | // V // // h0 = getHeight(cell - mData.columns + 1); // h1 = getHeight(cell + 1); h0 = getSample(cell - mData.columns + 1).height; h1 = getSample(cell + 1).height; }*/ const bool b0 = !isZerothVertexShared(cell - mData.columns); h0 = getSample(cell - mData.columns + b0).height; h1 = getSample(cell + b0).height; /* if(isZerothVertexShared(cell)) { // <------ COL // R // O // W // | // | // | // 2====+ 0 | // # / /| | // # / / | | // # / / | | // #/ / | | // 3 +----+ | // V // // h2 = getHeight(cell + 1); // h3 = getHeight(cell + mData.columns + 1); h2 = getSample(cell + 1).height; h3 = getSample(cell + mData.columns + 1).height; } else { // <------ COL // R // O // W // | // | // | // + +====2 | // |\ \ # | // | \ \ # | // | \ \ # | // | \ \# | // +----+ 3 | // V // // h2 = getHeight(cell); // h3 = getHeight(cell + mData.columns); h2 = getSample(cell).height; h3 = getSample(cell + mData.columns).height; }*/ const bool b1 = isZerothVertexShared(cell); h2 = getSample(cell + b1).height; h3 = getSample(cell + mData.columns + b1).height; //convex = (h3-h2) < (h1-h0); convexity = (h1-h0) - (h3-h2); } break; case 1: // h0 = getHeight(cell); // h1 = getHeight(cell + 1); // h2 = getHeight(cell + mData.columns); // h3 = getHeight(cell + mData.columns + 1); h0 = getSample(cell).height; h1 = getSample(cell + 1).height; h2 = getSample(cell + mData.columns).height; h3 = getSample(cell + mData.columns + 1).height; if (isZerothVertexShared(cell)) //convex = (h0 + h3) > (h1 + h2); convexity = (h0 + h3) - (h1 + h2); else //convex = (h2 + h1) > (h0 + h3); convexity = (h2 + h1) - (h0 + h3); break; case 2: { if (column < 1) return false; /* if(isZerothVertexShared(cell-1)) { // <-------------- COL // 1====0 + R // + / /| O // + / / | W // + / / | | // +/ / | | // + +----+ V // // h0 = getHeight(cell - 1); // h1 = getHeight(cell); h0 = getSample(cell - 1).height; h1 = getSample(cell).height; } else { // <-------------- COL // + +----+ R // +\ \ | O // + \ \ | W // + \ \ | | // + \ \| | // 1====0 + V // // h0 = getHeight(cell - 1 + mData.columns); // h1 = getHeight(cell + mData.columns); h0 = getSample(cell - 1 + mData.columns).height; h1 = getSample(cell + mData.columns).height; }*/ const PxU32 offset0 = isZerothVertexShared(cell-1) ? 0 : mData.columns; h0 = getSample(cell - 1 + offset0).height; h1 = getSample(cell + offset0).height; /* if(isZerothVertexShared(cell)) { // <-------------- COL // +----+ + R // | / /+ O // | / / + W // | / / + | // |/ / + | // + 3====2 V // // h2 = getHeight(cell + mData.columns); // h3 = getHeight(cell + mData.columns + 1); h2 = getSample(cell + mData.columns).height; h3 = getSample(cell + mData.columns + 1).height; } else { // <-------------- COL // + 3====2 R // |\ \ + O // | \ \ + W // | \ \ + | // | \ \+ | // +----+ + V // // h2 = getHeight(cell); // h3 = getHeight(cell + 1); h2 = getSample(cell).height; h3 = getSample(cell + 1).height; }*/ const PxU32 offset1 = isZerothVertexShared(cell) ? mData.columns : 0; h2 = getSample(cell + offset1).height; h3 = getSample(cell + offset1 + 1).height; //convex = (h3-h2) < (h1-h0); convexity = (h1-h0) - (h3-h2); } break; } const PxI32 threshold = PxI32(mData.convexEdgeThreshold); return convexity > threshold; } PX_INLINE bool Gu::HeightField::isValidTriangle(PxU32 triangleIndex) const { const PxU32 cell = triangleIndex >> 1; const PxU32 row = cell / mData.columns; if (row >= (mData.rows - 1)) return false; const PxU32 column = cell % mData.columns; if (column >= (mData.columns - 1)) return false; return true; } PX_INLINE void Gu::HeightField::getTriangleVertexIndices(PxU32 triangleIndex, PxU32& vertexIndex0, PxU32& vertexIndex1, PxU32& vertexIndex2) const { const PxU32 cell = triangleIndex >> 1; if (isZerothVertexShared(cell)) { // <---- COL // 0----2 1 R // | 1 / /| O // | / / | W // | / / | | // |/ / 0 | | // 1 2----0 V // if (isFirstTriangle(triangleIndex)) { vertexIndex0 = cell + mData.columns; vertexIndex1 = cell; vertexIndex2 = cell + mData.columns + 1; } else { vertexIndex0 = cell + 1; vertexIndex1 = cell + mData.columns + 1; vertexIndex2 = cell; } } else { // <---- COL // 2 1----0 R // |\ \ 0 | O // | \ \ | W // | \ \ | | // | 1 \ \| | // 0----1 2 V // if (isFirstTriangle(triangleIndex)) { vertexIndex0 = cell; vertexIndex1 = cell + 1; vertexIndex2 = cell + mData.columns; } else { vertexIndex0 = cell + mData.columns + 1; vertexIndex1 = cell + mData.columns; vertexIndex2 = cell + 1; } } } PX_INLINE void Gu::HeightField::getTriangleAdjacencyIndices(PxU32 triangleIndex, PxU32 vertexIndex0, PxU32 vertexIndex1, PxU32 vertexIndex2, PxU32& adjacencyIndex0, PxU32& adjacencyIndex1, PxU32& adjacencyIndex2) const { PX_UNUSED(vertexIndex0); PX_UNUSED(vertexIndex1); PX_UNUSED(vertexIndex2); const PxU32 cell = triangleIndex >> 1; if (isZerothVertexShared(cell)) { // <---- COL // 0----2 1 R // | 1 / /| O // | / / | W // | / / | | // |/ / 0 | | // 1 2----0 V // if (isFirstTriangle(triangleIndex)) { adjacencyIndex0 = 0xFFFFFFFF; adjacencyIndex1 = triangleIndex + 1; adjacencyIndex2 = 0xFFFFFFFF; if((cell % (mData.columns) != 0)) { adjacencyIndex0 = triangleIndex - 1; } if((cell / mData.columns != mData.rows - 2)) { const PxU32 tMod = isZerothVertexShared(cell + mData.columns) ? 1u : 0u; adjacencyIndex2 = ((cell + mData.columns) * 2) + tMod; } } else { adjacencyIndex0 = 0xFFFFFFFF; adjacencyIndex1 = triangleIndex - 1; adjacencyIndex2 = 0xFFFFFFFF; if(cell % (mData.columns) < (mData.columns - 2)) { adjacencyIndex0 = triangleIndex + 1; } if(cell >= mData.columns - 1) { const PxU32 tMod = isZerothVertexShared(cell - mData.columns) ? 0u : 1u; adjacencyIndex2 = ((cell - mData.columns) * 2) + tMod; } } } else { // <---- COL // 2 1----0 R // |\ \ 0 | O // | \ \ | W // | \ \ | | // | 1 \ \| | // 0----1 2 V // if (isFirstTriangle(triangleIndex)) { adjacencyIndex0 = 0xFFFFFFFF; adjacencyIndex1 = triangleIndex + 1; adjacencyIndex2 = 0xFFFFFFFF; if(cell >= mData.columns - 1) { const PxU32 tMod = isZerothVertexShared(cell - mData.columns) ? 0u : 1u; adjacencyIndex0 = ((cell - (mData.columns)) * 2) + tMod; } if((cell % (mData.columns) != 0)) { adjacencyIndex2 = triangleIndex - 1; } } else { adjacencyIndex0 = 0xFFFFFFFF; adjacencyIndex1 = triangleIndex - 1; adjacencyIndex2 = 0xFFFFFFFF; if((cell / mData.columns != mData.rows - 2)) { const PxU32 tMod = isZerothVertexShared(cell + mData.columns) ? 1u : 0u; adjacencyIndex0 = (cell + (mData.columns)) * 2 + tMod; } if(cell % (mData.columns) < (mData.columns - 2)) { adjacencyIndex2 = triangleIndex + 1; } } } } PX_INLINE PxVec3 Gu::HeightField::getTriangleNormalInternal(PxU32 triangleIndex) const { PxU32 v0, v1, v2; getTriangleVertexIndices(triangleIndex, v0, v1, v2); // const PxReal h0 = getHeight(v0); // const PxReal h1 = getHeight(v1); // const PxReal h2 = getHeight(v2); const PxI32 h0 = getSample(v0).height; const PxI32 h1 = getSample(v1).height; const PxI32 h2 = getSample(v2).height; const float thickness = 0.0f; const PxReal coeff = physx::intrinsics::fsel(thickness, -1.0f, 1.0f); // PxVec3 n(0,1,0); const PxU32 cell = triangleIndex >> 1; if (isZerothVertexShared(cell)) { // <---- COL // 0----2 1 R // | 1 / /| O // | / / | W // | / / | | // |/ / 0 | | // 1 2----0 V // if (isFirstTriangle(triangleIndex)) { // n.x = -(h0-h1); // n.z = -(h2-h0); return PxVec3(coeff*PxReal(h1-h0), coeff, coeff*PxReal(h0-h2)); } else { // n.x = -(h1-h0); // n.z = -(h0-h2); return PxVec3(coeff*PxReal(h0-h1), coeff, coeff*PxReal(h2-h0)); } } else { // <---- COL // 2 1----0 R // |\ \ 0 | O // | \ \ | W // | \ \ | | // | 1 \ \| | // 0----1 2 V // if (isFirstTriangle(triangleIndex)) { // n.x = -(h2-h0); // n.z = -(h1-h0); return PxVec3(coeff*PxReal(h0-h2), coeff, coeff*PxReal(h0-h1)); } else { // n.x = -(h0-h2); // n.z = -(h0-h1); return PxVec3(coeff*PxReal(h2-h0), coeff, coeff*PxReal(h1-h0)); } } // return n; } PX_INLINE PxReal Gu::HeightField::getHeightInternal2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ) const { if (isZerothVertexShared(vertexIndex)) { // <----Z---+ // +----+ | // | /| | // | / | X // | / | | // |/ | | // +----+ | // V const PxReal h0 = getHeight(vertexIndex); const PxReal h2 = getHeight(vertexIndex + mData.columns + 1); if (fracZ > fracX) { // <----Z---+ // 1----0 | // | / | // | / X // | / | // |/ | // 2 | // V const PxReal h1 = getHeight(vertexIndex + 1); return h0 + fracZ*(h1-h0) + fracX*(h2-h1); } else { // <----Z---+ // 0 | // /| | // / | X // / | | // / | | // 2----1 | // V const PxReal h1 = getHeight(vertexIndex + mData.columns); return h0 + fracX*(h1-h0) + fracZ*(h2-h1); } } else { // <----Z---+ // +----+ | // |\ | | // | \ | X // | \ | | // | \| | // +----+ | // V const PxReal h2 = getHeight(vertexIndex + mData.columns); const PxReal h1 = getHeight(vertexIndex + 1); if (fracX + fracZ < 1.0f) { // <----Z---+ // 1----0 | // \ | | // \ | X // \ | | // \| | // 2 | // V const PxReal h0 = getHeight(vertexIndex); return h0 + fracZ*(h1-h0) + fracX*(h2-h0); } else { // <----Z---+ // 1 | // |\ | // | \ X // | \ | // | \ | // 0----2 | // V // // Note that we need to flip fracX and fracZ since we are moving the origin const PxReal h0 = getHeight(vertexIndex + mData.columns + 1); return h0 + (1.0f - fracZ)*(h2-h0) + (1.0f - fracX)*(h1-h0); } } } PX_INLINE PxVec3 Gu::HeightField::getNormal_2(PxU32 vertexIndex, PxReal fracX, PxReal fracZ, PxReal xcoeff, PxReal ycoeff, PxReal zcoeff) const { PxVec3 normal; if (isZerothVertexShared(vertexIndex)) { // <----Z---+ // +----+ | // | /| | // | / | X // | / | | // |/ | | // +----+ | // V // const PxReal h0 = getHeight(vertexIndex); // const PxReal h2 = getHeight(vertexIndex + mData.columns + 1); const PxI32 ih0 = getSample(vertexIndex).height; const PxI32 ih2 = getSample(vertexIndex + mData.columns + 1).height; if (fracZ >= fracX) { // <----Z---+ // 1----0 | // | / | // | / X // | / | // |/ | // 2 | // V // const PxReal h0 = getHeight(vertexIndex); // const PxReal h1 = getHeight(vertexIndex + 1); // const PxReal h2 = getHeight(vertexIndex + mData.columns + 1); // normal.set(-(h2-h1), 1.0f, -(h1-h0)); const PxI32 ih1 = getSample(vertexIndex + 1).height; normal = PxVec3(PxReal(ih1 - ih2)*xcoeff, ycoeff, PxReal(ih0 - ih1)*zcoeff); } else { // <----Z---+ // 0 | // /| | // / | X // / | | // / | | // 2----1 | // V // const PxReal h0 = getHeight(vertexIndex); // const PxReal h1 = getHeight(vertexIndex + mData.columns); // const PxReal h2 = getHeight(vertexIndex + mData.columns + 1); // normal.set(-(h1-h0), 1.0f, -(h2-h1)); const PxI32 ih1 = getSample(vertexIndex + mData.columns).height; normal = PxVec3(PxReal(ih0 - ih1)*xcoeff, ycoeff, PxReal(ih1 - ih2)*zcoeff); } } else { // <----Z---+ // +----+ | // |\ | | // | \ | X // | \ | | // | \| | // +----+ | // V const PxI32 ih1 = getSample(vertexIndex + 1).height; const PxI32 ih2 = getSample(vertexIndex + mData.columns).height; if (fracX + fracZ <= PxReal(1)) { // <----Z---+ // 1----0 | // \ | | // \ | X // \ | | // \| | // 2 | // V // const PxReal h0 = getHeight(vertexIndex); // const PxReal h1 = getHeight(vertexIndex + 1); // const PxReal h2 = getHeight(vertexIndex + mData.columns); // normal.set(-(h2-h0), 1.0f, -(h1-h0)); const PxI32 ih0 = getSample(vertexIndex).height; // const PxI32 ih1 = getSample(vertexIndex + 1).height; // const PxI32 ih2 = getSample(vertexIndex + mData.columns).height; normal = PxVec3(PxReal(ih0 - ih2)*xcoeff, ycoeff, PxReal(ih0 - ih1)*zcoeff); } else { // <----Z---+ // 2 | // |\ | // | \ X // | \ | // | \ | // 0----1 | // V // // Note that we need to flip fracX and fracZ since we are moving the origin // const PxReal h2 = getHeight(vertexIndex + 1); // const PxReal h1 = getHeight(vertexIndex + mData.columns); // const PxReal h0 = getHeight(vertexIndex + mData.columns + 1); // normal.set(-(h0-h2), 1.0f, -(h0-h1)); // const PxI32 ih2 = getSample(vertexIndex + 1).height; // const PxI32 ih1 = getSample(vertexIndex + mData.columns).height; const PxI32 ih0 = getSample(vertexIndex + mData.columns + 1).height; // normal.set(PxReal(ih2 - ih0), 1.0f, PxReal(ih1b - ih0)); normal = PxVec3(PxReal(ih1 - ih0)*xcoeff, ycoeff, PxReal(ih2 - ih0)*zcoeff); } } return normal; } PX_INLINE PxU32 Gu::HeightField::getTriangleIndex2(PxU32 cell, PxReal fracX, PxReal fracZ) const { if (isZerothVertexShared(cell)) return (fracZ > fracX) ? (cell << 1) + 1 : (cell << 1); else return (fracX + fracZ > 1) ? (cell << 1) + 1 : (cell << 1); } PX_INLINE PxU32 Gu::HeightField::getTriangleIndex(PxReal x, PxReal z) const { PxReal fracX, fracZ; const PxU32 cell = computeCellCoordinates(x, z, fracX, fracZ); return getTriangleIndex2(cell, fracX, fracZ); } PX_FORCE_INLINE void Gu::HeightField::getTriangleVertices(PxU32 triangleIndex, PxU32 row, PxU32 column, PxVec3& v0, PxVec3& v1, PxVec3& v2) const { PxU32 cell = triangleIndex >> 1; PX_ASSERT(row * getNbColumnsFast() + column == cell); PxReal h0 = getHeight(cell); PxReal h1 = getHeight(cell + 1); PxReal h2 = getHeight(cell + getNbColumnsFast()); PxReal h3 = getHeight(cell + getNbColumnsFast() + 1); if (isFirstTriangle(triangleIndex)) { if (isZerothVertexShared(cell)) { // <---- COL // 1 R // /| O // / | W // / | | // / 0 | | // 2----0 V // v0 = PxVec3(PxReal(row + 1), h2, PxReal(column )); v1 = PxVec3(PxReal(row ), h0, PxReal(column )); v2 = PxVec3(PxReal(row + 1), h3, PxReal(column + 1)); } else { // <---- COL // 1----0 R // \ 0 | O // \ | W // \ | | // \| | // 2 V // v0 = PxVec3(PxReal(row ), h0, PxReal(column )); v1 = PxVec3(PxReal(row ), h1, PxReal(column + 1)); v2 = PxVec3(PxReal(row + 1), h2, PxReal(column )); } } else { if (isZerothVertexShared(cell)) { // <---- COL // 0----2 R // | 1 / O // | / W // | / | // |/ | // 1 V // v0 = PxVec3(PxReal(row ), h1, PxReal(column + 1)); v1 = PxVec3(PxReal(row + 1), h3, PxReal(column + 1)); v2 = PxVec3(PxReal(row ), h0, PxReal(column )); } else { // <---- COL // 2 R // |\ O // | \ W // | \ | // | 1 \ | // 0----1 V // v0 = PxVec3(PxReal(row + 1), h3, PxReal(column + 1)); v1 = PxVec3(PxReal(row + 1), h2, PxReal(column )); v2 = PxVec3(PxReal(row ), h1, PxReal(column + 1)); } } } PX_FORCE_INLINE const Gu::HeightFieldData* _getHFData(const PxHeightFieldGeometry& hfGeom) { return &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData(); } } #endif
39,101
C
30.893964
218
0.550753
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightFieldUtil.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_HEIGHTFIELD_UTIL_H #define GU_HEIGHTFIELD_UTIL_H #include "geometry/PxHeightFieldGeometry.h" #include "geometry/PxTriangle.h" #include "foundation/PxBasicTemplates.h" #include "foundation/PxSIMDHelpers.h" #include "GuHeightField.h" #include "../intersection/GuIntersectionRayTriangle.h" #include "../intersection/GuIntersectionRayBox.h" namespace physx { #define HF_SWEEP_REPORT_BUFFER_SIZE 64 #define HF_OVERLAP_REPORT_BUFFER_SIZE 64 namespace Gu { class OverlapReport; // PT: this is used in the context of sphere-vs-heightfield overlaps PX_FORCE_INLINE PxVec3 getLocalSphereData(PxBounds3& localBounds, const PxTransform& pose0, const PxTransform& pose1, float radius) { const PxVec3 localSphereCenter = pose1.transformInv(pose0.p); const PxVec3 extents(radius); localBounds.minimum = localSphereCenter - extents; localBounds.maximum = localSphereCenter + extents; return localSphereCenter; } PX_FORCE_INLINE PxBounds3 getLocalCapsuleBounds(float radius, float halfHeight) { const PxVec3 extents(halfHeight + radius, radius, radius); return PxBounds3(-extents, extents); } class PX_PHYSX_COMMON_API HeightFieldUtil { public: PxReal mOneOverRowScale; PxReal mOneOverHeightScale; PxReal mOneOverColumnScale; const Gu::HeightField* mHeightField; const PxHeightFieldGeometry* mHfGeom; PX_FORCE_INLINE HeightFieldUtil(const PxHeightFieldGeometry& hfGeom) : mHeightField(static_cast<const Gu::HeightField*>(hfGeom.heightField)), mHfGeom(&hfGeom) { const PxReal absRowScale = PxAbs(mHfGeom->rowScale); const PxReal absColScale = PxAbs(mHfGeom->columnScale); //warning #1931-D on WIIU: sizeof is not a type, variable, or dereferenced pointer expression PX_COMPILE_TIME_ASSERT(sizeof(reinterpret_cast<PxHeightFieldSample*>(0)->height) == 2); //PxReal minHeightPerSample = PX_MIN_HEIGHTFIELD_Y_SCALE; PX_ASSERT(mHfGeom->heightScale >= PX_MIN_HEIGHTFIELD_Y_SCALE); PX_ASSERT(absRowScale >= PX_MIN_HEIGHTFIELD_XZ_SCALE); PX_ASSERT(absColScale >= PX_MIN_HEIGHTFIELD_XZ_SCALE); PX_UNUSED(absRowScale); PX_UNUSED(absColScale); //using physx::intrinsics::fsel; //mOneOverHeightScale = fsel(mHfGeom->heightScale - minHeightPerSample, 1.0f / mHfGeom->heightScale, 1.0f / minHeightPerSample); mOneOverHeightScale = 1.0f / mHfGeom->heightScale; mOneOverRowScale = 1.0f / mHfGeom->rowScale; mOneOverColumnScale = 1.0f / mHfGeom->columnScale; } PX_CUDA_CALLABLE PX_FORCE_INLINE const Gu::HeightField& getHeightField() const { return *mHeightField; } PX_CUDA_CALLABLE PX_FORCE_INLINE const PxHeightFieldGeometry& getHeightFieldGeometry() const { return *mHfGeom; } PX_FORCE_INLINE PxReal getOneOverRowScale() const { return mOneOverRowScale; } PX_FORCE_INLINE PxReal getOneOverHeightScale() const { return mOneOverHeightScale; } PX_FORCE_INLINE PxReal getOneOverColumnScale() const { return mOneOverColumnScale; } void computeLocalBounds(PxBounds3& bounds) const; PX_FORCE_INLINE PxReal getHeightAtShapePoint(PxReal x, PxReal z) const { return mHfGeom->heightScale * mHeightField->getHeightInternal(x * mOneOverRowScale, z * mOneOverColumnScale); } PX_FORCE_INLINE PxVec3 getNormalAtShapePoint(PxReal x, PxReal z) const { return mHeightField->getNormal_(x * mOneOverRowScale, z * mOneOverColumnScale, mOneOverRowScale, mOneOverHeightScale, mOneOverColumnScale); } PxU32 getTriangle(const PxTransform&, PxTriangle& worldTri, PxU32* vertexIndices, PxU32* adjacencyIndices, PxTriangleID triangleIndex, bool worldSpaceTranslation=true, bool worldSpaceRotation=true) const; void overlapAABBTriangles(const PxBounds3& localBounds, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const; PX_FORCE_INLINE void overlapAABBTriangles0to1(const PxTransform& pose0to1, const PxBounds3& bounds0, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const { // PT: TODO: optimize PxBounds3::transformFast //overlapAABBTriangles(PxBounds3::transformFast(pose0to1, bounds0), callback, batchSize); { // PT: below is the equivalent, slightly faster code. Still not optimal but better. // PT: TODO: refactor with GuBounds.cpp const PxMat33Padded basis(pose0to1.q); // PT: TODO: pass c/e directly const PxBounds3 b = PxBounds3::basisExtent(pose0to1.transform(bounds0.getCenter()), basis, bounds0.getExtents()); overlapAABBTriangles(b, callback, batchSize); } } PX_FORCE_INLINE void overlapAABBTriangles(const PxTransform& pose1, const PxBounds3& bounds0, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const { overlapAABBTriangles0to1(pose1.getInverse(), bounds0, callback, batchSize); } PX_FORCE_INLINE void overlapAABBTriangles(const PxTransform& pose0, const PxTransform& pose1, const PxBounds3& bounds0, OverlapReport& callback, PxU32 batchSize=HF_OVERLAP_REPORT_BUFFER_SIZE) const { overlapAABBTriangles0to1(pose1.transformInv(pose0), bounds0, callback, batchSize); } PX_FORCE_INLINE PxVec3 hf2shapen(const PxVec3& v) const { return PxVec3(v.x * mOneOverRowScale, v.y * mOneOverHeightScale, v.z * mOneOverColumnScale); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 shape2hfp(const PxVec3& v) const { return PxVec3(v.x * mOneOverRowScale, v.y * mOneOverHeightScale, v.z * mOneOverColumnScale); } PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec3 hf2shapep(const PxVec3& v) const { return PxVec3(v.x * mHfGeom->rowScale, v.y * mHfGeom->heightScale, v.z * mHfGeom->columnScale); } PX_INLINE PxVec3 hf2worldp(const PxTransform& pose, const PxVec3& v) const { const PxVec3 s = hf2shapep(v); return pose.transform(s); } PX_INLINE PxVec3 hf2worldn(const PxTransform& pose, const PxVec3& v) const { const PxVec3 s = hf2shapen(v); return pose.q.rotate(s); } }; class PX_PHYSX_COMMON_API HeightFieldTraceUtil : public HeightFieldUtil { public: PX_FORCE_INLINE HeightFieldTraceUtil(const PxHeightFieldGeometry& hfGeom) : HeightFieldUtil(hfGeom) {} // floor and ceil don't clamp down exact integers but we want that static PX_FORCE_INLINE PxF32 floorDown(PxF32 x) { PxF32 f = PxFloor(x); return (f == x) ? f-1 : f; } static PX_FORCE_INLINE PxF32 ceilUp (PxF32 x) { PxF32 f = PxCeil (x); return (f == x) ? f+1 : f; } // helper class for testing triangle height and reporting the overlapped triangles template<class T> class OverlapTraceSegment { public: // helper rectangle struct struct OverlapRectangle { PxI32 mMinu; PxI32 mMaxu; PxI32 mMinv; PxI32 mMaxv; void invalidate() { mMinu = 1; mMaxu = -1; mMinv = 1; mMaxv = -1; } }; // helper line struct struct OverlapLine { bool mColumn; PxI32 mLine; PxI32 mMin; PxI32 mMax; void invalidate() { mMin = 1; mMax = -1; } }; public: void operator = (OverlapTraceSegment&) {} OverlapTraceSegment(const HeightFieldUtil& hfUtil,const Gu::HeightField& hf) : mInitialized(false), mHfUtil(hfUtil), mHf(hf), mNbIndices(0) {} PX_FORCE_INLINE bool initialized() const { return mInitialized; } // prepare for iterations, set the expand u|v PX_INLINE void prepare(const PxVec3& aP0, const PxVec3& aP1, const PxVec3& overlapObjectExtent, PxF32& expandu, PxF32& expandv) { // height test bounds mMinY = (PxMin(aP1.y,aP0.y) - overlapObjectExtent.y) * mHfUtil.getOneOverHeightScale(); mMaxY = (PxMax(aP1.y,aP0.y) + overlapObjectExtent.y) * mHfUtil.getOneOverHeightScale(); // sets the clipping variables mMinRow = PxI32(mHf.getMinRow((PxMin(aP1.x,aP0.x) - overlapObjectExtent.x)* mHfUtil.getOneOverRowScale())); mMaxRow = PxI32(mHf.getMaxRow((PxMax(aP1.x,aP0.x) + overlapObjectExtent.x)* mHfUtil.getOneOverRowScale())); mMinColumn = PxI32(mHf.getMinColumn((PxMin(aP1.z,aP0.z) - overlapObjectExtent.z)* mHfUtil.getOneOverColumnScale())); mMaxColumn = PxI32(mHf.getMaxColumn((PxMax(aP1.z,aP0.z) + overlapObjectExtent.z)* mHfUtil.getOneOverColumnScale())); // sets the expanded u|v coordinates expandu = PxCeil(overlapObjectExtent.x*mHfUtil.getOneOverRowScale()); expandv = PxCeil(overlapObjectExtent.z*mHfUtil.getOneOverColumnScale()); // sets the offset that will be overlapped in each axis mOffsetU = PxI32(expandu) + 1; mOffsetV = PxI32(expandv) + 1; } // sets all necessary variables and makes initial rectangle setup and overlap PX_INLINE bool init(const PxI32 ui, const PxI32 vi, const PxI32 nbVi, const PxI32 step_ui, const PxI32 step_vi, T* aCallback) { mInitialized = true; mCallback = aCallback; mNumColumns = nbVi; mStep_ui = step_ui > 0 ? 0 : -1; mStep_vi = step_vi > 0 ? 0 : -1; // sets the rectangles mCurrentRectangle.invalidate(); mPreviousRectangle.mMinu = ui - mOffsetU; mPreviousRectangle.mMaxu = ui + mOffsetU; mPreviousRectangle.mMinv = vi - mOffsetV; mPreviousRectangle.mMaxv = vi + mOffsetV; // visits all cells in given initial rectangle if(!visitCells(mPreviousRectangle)) return false; // reports all overlaps if(!reportOverlaps()) return false; return true; } // u|v changed, check for new rectangle - compare with previous one and parse // the added line, which is a result from the rectangle compare PX_INLINE bool step(const PxI32 ui, const PxI32 vi) { mCurrentRectangle.mMinu = ui - mOffsetU; mCurrentRectangle.mMaxu = ui + mOffsetU; mCurrentRectangle.mMinv = vi - mOffsetV; mCurrentRectangle.mMaxv = vi + mOffsetV; OverlapLine line = OverlapLine(); line.invalidate(); computeRectangleDifference(mCurrentRectangle,mPreviousRectangle,line); if(!visitCells(line)) return false; if(!reportOverlaps()) return false; mPreviousRectangle = mCurrentRectangle; return true; } PX_INLINE void computeRectangleDifference(const OverlapRectangle& currentRectangle, const OverlapRectangle& previousRectangle, OverlapLine& line) { // check if u changes - add the row for visit if(currentRectangle.mMinu != previousRectangle.mMinu) { line.mColumn = false; line.mLine = currentRectangle.mMinu < previousRectangle.mMinu ? currentRectangle.mMinu : currentRectangle.mMaxu; line.mMin = currentRectangle.mMinv; line.mMax = currentRectangle.mMaxv; return; } // check if v changes - add the column for visit if(currentRectangle.mMinv != previousRectangle.mMinv) { line.mColumn = true; line.mLine = currentRectangle.mMinv < previousRectangle.mMinv ? currentRectangle.mMinv : currentRectangle.mMaxv; line.mMin = currentRectangle.mMinu; line.mMax = currentRectangle.mMaxu; } } // visits all cells in given rectangle PX_INLINE bool visitCells(const OverlapRectangle& rectangle) { for(PxI32 ui = rectangle.mMinu + mStep_ui; ui <= rectangle.mMaxu + mStep_ui; ui++) { if(ui < mMinRow) continue; if(ui >= mMaxRow) break; for(PxI32 vi = rectangle.mMinv + mStep_vi; vi <= rectangle.mMaxv + mStep_vi; vi++) { if(vi < mMinColumn) continue; if(vi >= mMaxColumn) break; const PxI32 vertexIndex = ui*mNumColumns + vi; if(!testVertexIndex(PxU32(vertexIndex))) return false; } } return true; } // visits all cells in given line - can be row or column PX_INLINE bool visitCells(const OverlapLine& line) { if(line.mMin > line.mMax) return true; if(line.mColumn) { const PxI32 vi = line.mLine + mStep_vi; // early exit if column is out of hf clip area if(vi < mMinColumn) return true; if(vi >= mMaxColumn) return true; for(PxI32 ui = line.mMin + mStep_ui; ui <= line.mMax + mStep_ui; ui++) { // early exit or continue if row is out of hf clip area if(ui >= mMaxRow) break; // continue if we did not reach the valid area, we can still get there if(ui < mMinRow) continue; // if the cell has not been tested test and report if(!testVertexIndex(PxU32(mNumColumns * ui + vi))) return false; } } else { const PxI32 ui = line.mLine + mStep_ui; // early exit if row is out of hf clip area if(ui < mMinRow) return true; if(ui >= mMaxRow) return true; for(PxI32 vi = line.mMin + mStep_vi; vi <= line.mMax + mStep_vi; vi++) { // early exit or continue if column is out of hf clip area if(vi >= mMaxColumn) break; // continue if we did not reach the valid area, we can still get there if(vi < mMinColumn) continue; // if the cell has not been tested test and report if(!testVertexIndex(PxU32(mNumColumns * ui + vi))) return false; } } return true; } // does height check and if succeeded adds to report PX_INLINE bool testVertexIndex(const PxU32 vertexIndex) { const PxReal h0 = mHf.getHeight(vertexIndex); const PxReal h1 = mHf.getHeight(vertexIndex + 1); const PxReal h2 = mHf.getHeight(vertexIndex + mNumColumns); const PxReal h3 = mHf.getHeight(vertexIndex + mNumColumns + 1); // actual height test, if some height pass we accept the cell if(!((mMaxY < h0 && mMaxY < h1 && mMaxY < h2 && mMaxY < h3) || (mMinY > h0 && mMinY > h1 && mMinY > h2 && mMinY > h3))) { // check if the triangle is not a hole if(mHf.getMaterialIndex0(vertexIndex) != PxHeightFieldMaterial::eHOLE) { if(!addIndex(vertexIndex*2)) return false; } if(mHf.getMaterialIndex1(vertexIndex) != PxHeightFieldMaterial::eHOLE) { if(!addIndex(vertexIndex*2 + 1)) return false; } } return true; } // add triangle index, if we get out of buffer size, report them bool addIndex(PxU32 triangleIndex) { if(mNbIndices == HF_SWEEP_REPORT_BUFFER_SIZE) { if(!reportOverlaps()) return false; } mIndexBuffer[mNbIndices++] = triangleIndex; return true; } PX_FORCE_INLINE bool reportOverlaps() { if(mNbIndices) { if(!mCallback->onEvent(mNbIndices, mIndexBuffer)) return false; mNbIndices = 0; } return true; } private: bool mInitialized; const HeightFieldUtil& mHfUtil; const Gu::HeightField& mHf; T* mCallback; PxI32 mOffsetU; PxI32 mOffsetV; float mMinY; float mMaxY; PxI32 mMinRow; PxI32 mMaxRow; PxI32 mMinColumn; PxI32 mMaxColumn; PxI32 mNumColumns; PxI32 mStep_ui; PxI32 mStep_vi; OverlapRectangle mPreviousRectangle; OverlapRectangle mCurrentRectangle; PxU32 mIndexBuffer[HF_SWEEP_REPORT_BUFFER_SIZE]; PxU32 mNbIndices; }; // If useUnderFaceCalblack is false, traceSegment will report segment/triangle hits via // faceHit(const Gu::HeightFieldUtil& hf, const PxVec3& point, PxU32 triangleIndex) // Otherwise traceSegment will report all triangles the segment passes under via // underFaceHit(const Gu::HeightFieldUtil& hf, const PxVec3& triNormal, const PxVec3& crossedEdge, // PxF32 x, PxF32 z, PxF32 rayHeight, PxU32 triangleIndex) // where x,z is the point of previous intercept in hf coords, rayHeight is at that same point // crossedEdge is the edge vector crossed from last call to underFaceHit, undefined for first call // Note that underFaceHit can be called when a line is above a triangle if it's within AABB for that hf cell // Note that backfaceCull is ignored if useUnderFaceCallback is true // overlapObjectExtent (localSpace) and overlap are used for triangle collecting using an inflated tracesegment // Note that hfLocalBounds are passed as a parameter instead of being computed inside the traceSegment. // The localBounds can be obtained: PxBounds3 hfLocalBounds; hfUtil.computeLocalBounds(hfLocalBounds); and passed as // a parameter. template<class T, bool useUnderFaceCallback, bool overlap> PX_INLINE void traceSegment(const PxVec3& aP0, const PxVec3& rayDir, const float rayLength , T* aCallback, const PxBounds3& hfLocalBounds, bool backfaceCull, const PxVec3* overlapObjectExtent = NULL) const { PxF32 tnear, tfar; if(!Gu::intersectRayAABB2(hfLocalBounds.minimum, hfLocalBounds.maximum, aP0, rayDir, rayLength, tnear, tfar)) return; const PxVec3 p0 = aP0 + rayDir * tnear; const PxVec3 p1 = aP0 + rayDir * tfar; // helper class used for overlap tests OverlapTraceSegment<T> overlapTraceSegment(*this, *mHeightField); // values which expand the HF area PxF32 expandu = 0.0f, expandv = 0.0f; if (overlap) { // setup overlap variables overlapTraceSegment.prepare(aP0,aP0 + rayDir*rayLength,*overlapObjectExtent,expandu,expandv); } // row = x|u, column = z|v const PxF32 rowScale = mHfGeom->rowScale, columnScale = mHfGeom->columnScale, heightScale = mHfGeom->heightScale; const PxI32 nbVi = PxI32(mHeightField->getNbColumnsFast()), nbUi = PxI32(mHeightField->getNbRowsFast()); PX_ASSERT(nbVi > 0 && nbUi > 0); // clampEps is chosen so that we get a reasonable clamp value for 65536*0.9999999f = 65535.992187500000 const PxF32 clampEps = 1e-7f; // shrink u,v to within 1e-7 away from the world bounds // we now clamp uvs to [1e-7, rowLimit-1e-7] to avoid out of range uvs and eliminate related checks in the loop const PxF32 nbUcells = PxF32(nbUi-1)*(1.0f-clampEps), nbVcells = PxF32(nbVi-1)*(1.0f-clampEps); // if u0,v0 is near an integer, shift up or down in direction opposite to du,dv by PxMax(|u,v|*1e-7, 1e-7) // (same direction as du,dv for u1,v1) // we do this to ensure that we get at least one intersection with u or v when near the cell edge to eliminate special cases in the loop // we need to extend the field for the inflated radius, we will now operate even with negative u|v // map p0 from (x, z, y) to (u0, v0, h0) // we need to use the unclamped values, otherwise we change the direction of the traversal const PxF32 uu0 = p0.x * mOneOverRowScale; PxF32 u0 = PxMin(PxMax(uu0, 1e-7f - expandu), nbUcells + expandu); // multiplication rescales the u,v grid steps to 1 const PxF32 uv0 = p0.z * mOneOverColumnScale; PxF32 v0 = PxMin(PxMax(uv0, 1e-7f - expandv), nbVcells + expandv); const PxReal h0 = p0.y; // we don't scale y // map p1 from (x, z, y) to (u1, v1, h1) // we need to use the unclamped values, otherwise we change the direction of the traversal const PxF32 uu1 = p1.x * mOneOverRowScale; const PxF32 uv1 = p1.z * mOneOverColumnScale; const PxReal h1 = p1.y; // we don't scale y PxF32 du = uu1 - uu0, dv = uv1 - uv0; // recompute du, dv from adjusted uvs const PxReal dh = h1 - h0; // grid u&v step is always either 1 or -1, we precompute as both integers and floats to avoid conversions // so step_uif is +/-1.0f, step_ui is +/-1 const PxF32 step_uif = PxSign(du), step_vif = PxSign(dv); const PxI32 step_ui = PxI32(step_uif), step_vi = PxI32(step_vif); // clamp magnitude of du, dv to at least clampEpsilon to avoid special cases when dividing const PxF32 divEpsilon = 1e-10f; if(PxAbs(du) < divEpsilon) du = step_uif * divEpsilon; if(PxAbs(dv) < divEpsilon) dv = step_vif * divEpsilon; const PxVec3 auhP0(aP0.x*mOneOverRowScale, aP0.y, aP0.z*mOneOverColumnScale); const PxVec3 duhv(rayDir.x*rayLength*mOneOverRowScale, rayDir.y*rayLength, rayDir.z*rayLength*mOneOverColumnScale); const PxReal duhvLength = duhv.magnitude(); PxVec3 duhvNormalized = duhv; if(duhvLength > PX_NORMALIZATION_EPSILON) duhvNormalized *= 1.0f/duhvLength; // Math derivation: // points on 2d segment are parametrized as: [u0,v0] + t [du, dv]. We solve for t_u[n], t for nth u-intercept // u0 + t_un du = un // t_un = (un-u0) / du // t_un1 = (un+1-u0) / du ; we use +1 since we rescaled the grid step to 1 // therefore step_tu = t_un - t_un1 = 1/du // seed the initial integer cell coordinates with u0, v0 rounded up or down with standard PxFloor/Ceil behavior // to ensure we have the correct first cell between (ui,vi) and (ui+step_ui,vi+step_vi) PxI32 ui = (du > 0.0f) ? PxI32(PxFloor(u0)) : PxI32(PxCeil(u0)); PxI32 vi = (dv > 0.0f) ? PxI32(PxFloor(v0)) : PxI32(PxCeil(v0)); // find the nearest integer u, v in ray traversal direction and corresponding tu and tv const PxReal uhit0 = du > 0.0f ? ceilUp(u0) : floorDown(u0); const PxReal vhit0 = dv > 0.0f ? ceilUp(v0) : floorDown(v0); // tu, tv can be > 1 but since the loop is structured as do {} while(tMin < tEnd) we still visit the first cell PxF32 last_tu = 0.0f, last_tv = 0.0f; PxReal tu = (uhit0 - uu0) / du; PxReal tv = (vhit0 - uv0) / dv; if(tu < 0.0f) // negative value may happen, as we may have started out of the AABB (since we did enlarge it) tu = PxAbs(clampEps / du); if(tv < 0.0f) // negative value may happen, as we may have started out of the AABB (since we did enlarge it) tv = PxAbs(clampEps / dv); // compute step_tu and step_tv; t steps per grid cell in u and v direction const PxReal step_tu = 1.0f / PxAbs(du), step_tv = 1.0f / PxAbs(dv); // t advances at the same rate for u, v and h therefore we can compute h at u,v grid intercepts #define COMPUTE_H_FROM_T(t) (h0 + (t) * dh) const PxF32 hEpsilon = 1e-4f; PxF32 uif = PxF32(ui), vif = PxF32(vi); // these are used to remap h values to correspond to u,v increasing order PxI32 uflip = 1-step_ui; /*0 or 2*/ PxI32 vflip = (1-step_vi)/2; /*0 or 1*/ // this epsilon is needed to ensure that we include the last [t, t+1] range in the do {} while(t<tEnd) loop // A.B. in case of overlap we do miss actually a line with this epsilon, should it not be +? PxF32 tEnd = 1.0f - 1e-4f; if(overlap) tEnd = 1.0f + 1e-4f; PxF32 tMinUV; const Gu::HeightField& hf = *mHeightField; // seed hLinePrev as h(0) PxReal hLinePrev = COMPUTE_H_FROM_T(0); do { tMinUV = PxMin(tu, tv); // determine where next closest u or v-intercept point is PxF32 hLineNext = COMPUTE_H_FROM_T(tMinUV); // compute the corresponding h // the operating u|v space has been extended by expandu|expandv if inflation is used PX_ASSERT(ui >= 0 - expandu && ui < nbUi + expandu && vi >= 0 - expandv && vi < nbVi + expandv); PX_ASSERT(ui+step_ui >= 0 - expandu && ui+step_ui < nbUi + expandu && vi+step_vi >= 0 - expandv && vi+step_vi < nbVi + expandv); // handle overlap in overlapCallback if(overlap) { if(!overlapTraceSegment.initialized()) { // initial overlap and setup if(!overlapTraceSegment.init(ui,vi,nbVi,step_ui,step_vi,aCallback)) return; } else { // overlap step if(!overlapTraceSegment.step(ui,vi)) return; } } else { const PxU32 colIndex0 = PxU32(nbVi * ui + vi); const PxU32 colIndex1 = PxU32(nbVi * (ui + step_ui) + vi); const PxReal h[4] = { // h[0]=h00, h[1]=h01, h[2]=h10, h[3]=h11 - oriented relative to step_uv hf.getHeight(colIndex0) * heightScale, hf.getHeight(colIndex0 + step_vi) * heightScale, hf.getHeight(colIndex1) * heightScale, hf.getHeight(colIndex1 + step_vi) * heightScale }; PxF32 minH = PxMin(PxMin(h[0], h[1]), PxMin(h[2], h[3])); PxF32 maxH = PxMax(PxMax(h[0], h[1]), PxMax(h[2], h[3])); // how much space in h have we covered from previous to current u or v intercept PxF32 hLineCellRangeMin = PxMin(hLinePrev, hLineNext); PxF32 hLineCellRangeMax = PxMax(hLinePrev, hLineNext); // do a quick overlap test in h, this should be rejecting the vast majority of tests if(!(hLineCellRangeMin-hEpsilon > maxH || hLineCellRangeMax+hEpsilon < minH) || (useUnderFaceCallback && hLineCellRangeMax < maxH)) { // arrange h so that h00 corresponds to min(uif, uif+step_uif) h10 to max et c. // this is only needed for backface culling to work so we know the proper winding order without branches // uflip is 0 or 2, vflip is 0 or 1 (corresponding to positive and negative ui_step and vi_step) const PxF32 h00 = h[0+uflip+vflip]; const PxF32 h01 = h[1+uflip-vflip]; const PxF32 h10 = h[2-uflip+vflip]; const PxF32 h11 = h[3-uflip-vflip]; const PxF32 minuif = PxMin(uif, uif+step_uif); const PxF32 maxuif = PxMax(uif, uif+step_uif); const PxF32 minvif = PxMin(vif, vif+step_vif); const PxF32 maxvif = PxMax(vif, vif+step_vif); const PxVec3 p00(minuif, h00, minvif); const PxVec3 p01(minuif, h01, maxvif); const PxVec3 p10(maxuif, h10, minvif); const PxVec3 p11(maxuif, h11, maxvif); const PxF32 enlargeEpsilon = 0.0001f; const PxVec3* p00a = &p00, *p01a = &p01, *p10a = &p10, *p11a = &p11; PxU32 minui = PxU32(PxMin(ui+step_ui, ui)), minvi = PxU32(PxMin(vi+step_vi, vi)); // row = x|u, column = z|v const PxU32 vertIndex = nbVi * minui + minvi; const PxU32 cellIndex = vertIndex; // this adds a dummy unused cell in the end of each row; was -minui bool isZVS = hf.isZerothVertexShared(vertIndex); if(!isZVS) { // rotate the pointers for flipped edge cells p10a = &p00; p00a = &p01; p01a = &p11; p11a = &p10; } // For triangle index computation, see illustration in Gu::HeightField::getTriangleNormal() // Since row = u, column = v // for zeroth vert shared the 10 index is the corner of the 0-index triangle, and 01 is 1-index // if zeroth vertex is not shared, the 00 index is the corner of 0-index triangle if(!useUnderFaceCallback) { PxReal triT0 = PX_MAX_REAL, triT1 = PX_MAX_REAL; bool hit0 = false, hit1 = false; PxF32 triU0, triV0, triU1, triV1; // PT: TODO: consider testing hole first and skipping ray-tri test. Might be faster. if(Gu::intersectRayTriangle(auhP0, duhvNormalized, *p10a, *p00a, *p11a, triT0, triU0, triV0, backfaceCull, enlargeEpsilon) && triT0 >= 0.0f && triT0 <= duhvLength && (hf.getMaterialIndex0(vertIndex) != PxHeightFieldMaterial::eHOLE)) { hit0 = true; } else triT0 = PX_MAX_REAL; if(Gu::intersectRayTriangle(auhP0, duhvNormalized, *p01a, *p11a, *p00a, triT1, triU1, triV1, backfaceCull, enlargeEpsilon) && triT1 >= 0.0f && triT1 <= duhvLength && (hf.getMaterialIndex1(vertIndex) != PxHeightFieldMaterial::eHOLE)) { hit1 = true; } else triT1 = PX_MAX_REAL; if(hit0 && triT0 <= triT1) { const PxVec3 hitPoint((auhP0.x + duhvNormalized.x*triT0) * rowScale, auhP0.y + duhvNormalized.y * triT0, (auhP0.z + duhvNormalized.z*triT0) * columnScale); if(!aCallback->faceHit(*this, hitPoint, cellIndex*2, triU0, triV0)) return; if(hit1) // possible to hit both triangles in a cell with eMESH_MULTIPLE { PxVec3 hitPoint1((auhP0.x + duhvNormalized.x*triT1) * rowScale, auhP0.y + duhvNormalized.y * triT1, (auhP0.z + duhvNormalized.z*triT1) * columnScale); if(!aCallback->faceHit(*this, hitPoint1, cellIndex*2 + 1, triU1, triV1)) return; } } else if(hit1 && triT1 <= triT0) { PxVec3 hitPoint((auhP0.x + duhvNormalized.x*triT1) * rowScale, auhP0.y + duhvNormalized.y * triT1, (auhP0.z + duhvNormalized.z*triT1) * columnScale); if(!aCallback->faceHit(*this, hitPoint, cellIndex*2 + 1, triU1, triV1)) return; if(hit0) // possible to hit both triangles in a cell with eMESH_MULTIPLE { PxVec3 hitPoint1((auhP0.x + duhvNormalized.x*triT0) * rowScale, auhP0.y + duhvNormalized.y * triT0, (auhP0.z + duhvNormalized.z*triT0) * columnScale); if(!aCallback->faceHit(*this, hitPoint1, cellIndex*2, triU0, triV0)) return; } } } else { // TODO: quite a few optimizations are possible here. edges can be shared, intersectRayTriangle inlined etc // Go to shape space. Height is already in shape space so we only scale x and z const PxVec3 p00s(p00a->x * rowScale, p00a->y, p00a->z * columnScale); const PxVec3 p01s(p01a->x * rowScale, p01a->y, p01a->z * columnScale); const PxVec3 p10s(p10a->x * rowScale, p10a->y, p10a->z * columnScale); const PxVec3 p11s(p11a->x * rowScale, p11a->y, p11a->z * columnScale); PxVec3 triNormals[2] = { (p00s - p10s).cross(p11s - p10s), (p11s - p01s).cross(p00s-p01s) }; triNormals[0] *= PxRecipSqrt(triNormals[0].magnitudeSquared()); triNormals[1] *= PxRecipSqrt(triNormals[1].magnitudeSquared()); // since the heightfield can be mirrored with negative rowScale or columnScale, this assert doesn't hold //PX_ASSERT(triNormals[0].y >= 0.0f && triNormals[1].y >= 0.0f); // at this point we need to compute the edge direction that we crossed // also since we don't DDA the w we need to find u,v for w-intercept (w refers to diagonal adjusted with isZVS) const PxF32 wnu = isZVS ? -1.0f : 1.0f, wnv = 1.0f; // uv-normal to triangle edge that splits the cell const PxF32 wpu = uif + 0.5f * step_uif, wpv = vif + 0.5f * step_vif; // a point on triangle edge that splits the cell // note that (wpu, wpv) is on both edges (for isZVS and non-ZVS cases) which is nice // we clamp tNext to 1 because we still want to issue callbacks even if we stay in one cell // note that tNext can potentially be arbitrarily large for a segment contained within a cell const PxF32 tNext = PxMin(PxMin(tu, tv), 1.0f), tPrev = PxMax(last_tu, last_tv); // compute uvs corresponding to tPrev, tNext const PxF32 unext = u0 + tNext*du, vnext = v0 + tNext*dv; const PxF32 uprev = u0 + tPrev*du, vprev = v0 + tPrev*dv; const PxReal& h00_ = h[0], &h01_ = h[1], &h10_ = h[2]/*, h11_ = h[3]*/; // aliases for step-oriented h // (wpu, wpv) is a point on the diagonal // we compute a dot of ((unext, vnext) - (wpu, wpv), wn) to see on which side of triangle edge we are // if the dot is positive we need to add 1 to triangle index const PxU32 dotPrevGtz = PxU32(((uprev - wpu) * wnu + (vprev - wpv) * wnv) > 0); const PxU32 dotNextGtz = PxU32(((unext - wpu) * wnu + (vnext - wpv) * wnv) > 0); const PxU32 triIndex0 = cellIndex*2 + dotPrevGtz; const PxU32 triIndex1 = cellIndex*2 + dotNextGtz; PxU32 isHole0 = PxU32(hf.getMaterialIndex0(vertIndex) == PxHeightFieldMaterial::eHOLE); PxU32 isHole1 = PxU32(hf.getMaterialIndex1(vertIndex) == PxHeightFieldMaterial::eHOLE); if(triIndex0 > triIndex1) PxSwap<PxU32>(isHole0, isHole1); // TODO: compute height at u,v inside here, change callback param to PxVec3 PxVec3 crossedEdge; if(last_tu > last_tv) // previous intercept was at u, so we use u=const edge crossedEdge = PxVec3(0.0f, h01_-h00_, step_vif * columnScale); else // previous intercept at v, use v=const edge crossedEdge = PxVec3(step_uif * rowScale, h10_-h00_, 0.0f); if(!isHole0 && !aCallback->underFaceHit(*this, triNormals[dotPrevGtz], crossedEdge, uprev * rowScale, vprev * columnScale, COMPUTE_H_FROM_T(tPrev), triIndex0)) return; if(triIndex1 != triIndex0 && !isHole1) // if triIndex0 != triIndex1 that means we cross the triangle edge { // Need to compute tw, the t for ray intersecting the diagonal within the current cell // dot((wnu, wnv), (u0+tw*du, v0+tw*dv)-(wpu, wpv)) = 0 // wnu*(u0+tw*du-wpu) + wnv*(v0+tw*dv-wpv) = 0 // wnu*u0+wnv*v0-wnu*wpu-wnv*wpv + tw*(du*wnu + dv*wnv) = 0 const PxF32 denom = du*wnu + dv*wnv; if(PxAbs(denom) > 1e-6f) { const PxF32 tw = (wnu*(wpu-u0)+wnv*(wpv-v0)) / denom; if(!aCallback->underFaceHit(*this, triNormals[dotNextGtz], p10s-p01s, (u0+tw*du) * rowScale, (v0+tw*dv) * columnScale, COMPUTE_H_FROM_T(tw), triIndex1)) return; } } } } } if(tu < tv) { last_tu = tu; ui += step_ui; // AP: very rare condition, wasn't able to repro but we need this if anyway (DE6565) if(ui+step_ui< (0 - expandu) || ui+step_ui>=(nbUi + expandu)) // should hold true for ui without step from previous iteration break; uif += step_uif; tu += step_tu; } else { last_tv = tv; vi += step_vi; // AP: very rare condition, wasn't able to repro but we need this if anyway (DE6565) if(vi+step_vi< (0 - expandv) || vi+step_vi>=(nbVi + expandv)) // should hold true for vi without step from previous iteration break; vif += step_vif; tv += step_tv; } hLinePrev = hLineNext; } // since min(tu,tv) is the END of the active interval we need to check if PREVIOUS min(tu,tv) was past interval end // since we update tMinUV in the beginning of the loop, at this point it stores the min(last tu,last tv) while (tMinUV < tEnd); #undef COMPUTE_H_FROM_T } }; } // namespace Gu } #endif
34,953
C
40.611905
238
0.675278
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuSweepsHF.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 "GuSweepTests.h" #include "GuHeightFieldUtil.h" #include "GuEntityReport.h" #include "GuVecCapsule.h" #include "GuSweepMTD.h" #include "GuSweepTriangleUtils.h" #include "GuVecBox.h" #include "CmScaling.h" #include "GuSweepCapsuleTriangle.h" #include "GuInternal.h" #include "GuGJKRaycast.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace physx::aos; #include "GuSweepConvexTri.h" #define AbortTraversal false #define ContinueTraversal true #if PX_VC #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif /////////////////////////////////////////////////////////////////////////////// class HeightFieldTraceSegmentSweepHelper { PX_NOCOPY(HeightFieldTraceSegmentSweepHelper) public: HeightFieldTraceSegmentSweepHelper(const HeightFieldTraceUtil& hfUtil, const PxVec3& aabbExtentHfLocalSpace) : mHfUtil(hfUtil), mOverlapObjectExtent(aabbExtentHfLocalSpace) { mHfUtil.computeLocalBounds(mLocalBounds); // extend the bounds mLocalBounds.minimum = mLocalBounds.minimum - aabbExtentHfLocalSpace; mLocalBounds.maximum = mLocalBounds.maximum + aabbExtentHfLocalSpace; } template<class T> PX_INLINE void traceSegment(const PxVec3& aP0, const PxVec3& rayDirNorm, const float rayLength, T* aCallback) const { mHfUtil.traceSegment<T, false, true>(aP0, rayDirNorm, rayLength, aCallback, mLocalBounds, false, &mOverlapObjectExtent); } private: const HeightFieldTraceUtil& mHfUtil; const PxVec3& mOverlapObjectExtent; PxBounds3 mLocalBounds; }; /////////////////////////////////////////////////////////////////////////////// class HeightFieldTraceSegmentReport : public EntityReport { PX_NOCOPY(HeightFieldTraceSegmentReport) public: HeightFieldTraceSegmentReport(const HeightFieldUtil& hfUtil, const PxHitFlags hitFlags) : mHfUtil (hfUtil), mHitFlags (hitFlags), mStatus (false), mInitialOverlap (false), mIsDoubleSided ((hfUtil.getHeightFieldGeometry().heightFieldFlags & PxMeshGeometryFlag::eDOUBLE_SIDED) || (hitFlags & PxHitFlag::eMESH_BOTH_SIDES)), mIsAnyHit (hitFlags & PxHitFlag::eMESH_ANY) { } bool underFaceHit(const Gu::HeightFieldUtil&, const PxVec3&, const PxVec3&, PxF32, PxF32, PxF32, PxU32) { return true; } bool faceHit(const Gu::HeightFieldUtil&, const PxVec3&, PxU32, PxReal, PxReal) { return true; } protected: const HeightFieldUtil& mHfUtil; const PxHitFlags mHitFlags; bool mStatus; bool mInitialOverlap; const bool mIsDoubleSided; const bool mIsAnyHit; }; /////////////////////////////////////////////////////////////////////////////// class CapsuleTraceSegmentReport : public HeightFieldTraceSegmentReport { PX_NOCOPY(CapsuleTraceSegmentReport) public: CapsuleTraceSegmentReport( const HeightFieldUtil& hfUtil, const PxHitFlags hitFlags, const Capsule& inflatedCapsule, const PxVec3& unitDir, PxGeomSweepHit& sweepHit, const PxTransform& pose, PxReal distance) : HeightFieldTraceSegmentReport (hfUtil, hitFlags), mInflatedCapsule (inflatedCapsule), mUnitDir (unitDir), mSweepHit (sweepHit), mPose (pose), mDistance (distance) { mSweepHit.faceIndex = 0xFFFFffff; } virtual bool onEvent(PxU32 nb, const PxU32* indices) { PX_ALIGN_PREFIX(16) PxU8 tribuf[HF_SWEEP_REPORT_BUFFER_SIZE*sizeof(PxTriangle)] PX_ALIGN_SUFFIX(16); PxTriangle* tmpT = reinterpret_cast<PxTriangle*>(tribuf); PX_ASSERT(nb <= HF_SWEEP_REPORT_BUFFER_SIZE); for(PxU32 i=0; i<nb; i++) { const PxU32 triangleIndex = indices[i]; mHfUtil.getTriangle(mPose, tmpT[i], NULL, NULL, triangleIndex, true); } PxGeomSweepHit h; // PT: TODO: ctor! // PT: this one is safe because cullbox is NULL (no need to allocate one more triangle) // PT: TODO: is it ok to pass the initial distance here? PxVec3 bestNormal; const bool status = sweepCapsuleTriangles_Precise(nb, tmpT, mInflatedCapsule, mUnitDir, mDistance, NULL, h, bestNormal, mHitFlags, mIsDoubleSided); if(status && (h.distance <= mSweepHit.distance)) { mSweepHit.faceIndex = indices[h.faceIndex]; mSweepHit.normal = h.normal; mSweepHit.position = h.position; mSweepHit.distance = h.distance; mStatus = true; if(h.distance == 0.0f) { mInitialOverlap = true; return AbortTraversal; } if(mIsAnyHit) return AbortTraversal; } return ContinueTraversal; } bool finalizeHit(PxGeomSweepHit& sweepHit, const PxHeightFieldGeometry& hfGeom, const PxTransform& pose, const Capsule& lss, const Capsule& inflatedCapsule, const PxVec3& unitDir) { if(!mStatus) return false; if(mInitialOverlap) { // PT: TODO: consider using 'setInitialOverlapResults' here sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; if(mHitFlags & PxHitFlag::eMTD) { const Vec3V p0 = V3LoadU(lss.p0); const Vec3V p1 = V3LoadU(lss.p1); const FloatV radius = FLoad(lss.radius); CapsuleV capsuleV; capsuleV.initialize(p0, p1, radius); //calculate MTD const bool hasContacts = computeCapsule_HeightFieldMTD(hfGeom, pose, capsuleV, inflatedCapsule.radius, mIsDoubleSided, sweepHit); //ML: the center of mass is below the surface, we won't have MTD contact generate if(!hasContacts) { sweepHit.distance = 0.0f; sweepHit.normal = -unitDir; } else { sweepHit.flags |= PxHitFlag::ePOSITION; } } else { sweepHit.distance = 0.0f; sweepHit.normal = -unitDir; } } else { sweepHit.flags = PxHitFlag::eNORMAL| PxHitFlag::ePOSITION | PxHitFlag::eFACE_INDEX; } return true; } private: const Capsule& mInflatedCapsule; const PxVec3& mUnitDir; PxGeomSweepHit& mSweepHit; const PxTransform& mPose; const PxReal mDistance; }; bool sweepCapsule_HeightFieldGeom(GU_CAPSULE_SWEEP_FUNC_PARAMS) { PX_UNUSED(threadContext); PX_UNUSED(capsuleGeom_); PX_UNUSED(capsulePose_); PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom); const Capsule inflatedCapsule(lss.p0, lss.p1, lss.radius + inflation); // Compute swept box Box capsuleBox; computeBoxAroundCapsule(inflatedCapsule, capsuleBox); const PxVec3 capsuleAABBExtents = capsuleBox.computeAABBExtent(); const HeightFieldTraceUtil hfUtil(hfGeom); CapsuleTraceSegmentReport myReport(hfUtil, hitFlags, inflatedCapsule, unitDir, sweepHit, pose, distance); sweepHit.distance = PX_MAX_F32; // need hf local space stuff const PxTransform inversePose = pose.getInverse(); const PxVec3 centerLocalSpace = inversePose.transform(capsuleBox.center); const PxVec3 sweepDirLocalSpace = inversePose.rotate(unitDir); const PxVec3 capsuleAABBBExtentHfLocalSpace = PxBounds3::basisExtent(centerLocalSpace, PxMat33Padded(inversePose.q), capsuleAABBExtents).getExtents(); HeightFieldTraceSegmentSweepHelper traceSegmentHelper(hfUtil, capsuleAABBBExtentHfLocalSpace); traceSegmentHelper.traceSegment<CapsuleTraceSegmentReport>(centerLocalSpace, sweepDirLocalSpace, distance, &myReport); return myReport.finalizeHit(sweepHit, hfGeom, pose, lss, inflatedCapsule, unitDir); } /////////////////////////////////////////////////////////////////////////////// class ConvexTraceSegmentReport : public HeightFieldTraceSegmentReport { PX_NOCOPY(ConvexTraceSegmentReport) public: ConvexTraceSegmentReport( const HeightFieldUtil& hfUtil, const ConvexHullData& hull, const PxMeshScale& convexScale, const PxTransform& convexPose, const PxTransform& heightFieldPose, const PxVec3& unitDir, PxReal distance, PxHitFlags hitFlags, PxReal inflation) : HeightFieldTraceSegmentReport (hfUtil, hitFlags), mUnitDir (unitDir), mInflation (inflation) { using namespace aos; mSweepHit.faceIndex = 0xFFFFffff; mSweepHit.distance = distance; const Vec3V worldDir = V3LoadU(unitDir); const FloatV dist = FLoad(distance); const QuatV q0 = QuatVLoadU(&heightFieldPose.q.x); const Vec3V p0 = V3LoadU(&heightFieldPose.p.x); const QuatV q1 = QuatVLoadU(&convexPose.q.x); const Vec3V p1 = V3LoadU(&convexPose.p.x); const PxTransformV meshTransf(p0, q0); const PxTransformV convexTransf(p1, q1); mMeshToConvex = convexTransf.transformInv(meshTransf); mConvexPoseV = convexTransf; mConvexSpaceDir = convexTransf.rotateInv(V3Neg(V3Scale(worldDir, dist))); mDistance = dist; const Vec3V vScale = V3LoadU_SafeReadW(convexScale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat = QuatVLoadU(&convexScale.rotation.x); mMeshSpaceUnitDir = heightFieldPose.rotateInv(unitDir); mConvexHull.initialize(&hull, V3Zero(), vScale, vQuat, convexScale.isIdentity()); } virtual bool onEvent(PxU32 nbEntities, const PxU32* entities) { const PxTransform idt(PxIdentity); for(PxU32 i=0; i<nbEntities; i++) { PxTriangle tri; mHfUtil.getTriangle(idt, tri, NULL, NULL, entities[i], false, false); // First parameter not needed if local space triangle is enough // use mSweepHit.distance as max sweep distance so far, mSweepHit.distance will be clipped by this function if(sweepConvexVsTriangle( tri.verts[0], tri.verts[1], tri.verts[2], mConvexHull, mMeshToConvex, mConvexPoseV, mConvexSpaceDir, mUnitDir, mMeshSpaceUnitDir, mDistance, mSweepHit.distance, mSweepHit, mIsDoubleSided, mInflation, mInitialOverlap, entities[i])) { mStatus = true; if(mIsAnyHit || mSweepHit.distance == 0.0f) return AbortTraversal; } } return ContinueTraversal; } bool finalizeHit(PxGeomSweepHit& sweepHit, const PxHeightFieldGeometry& hfGeom, const PxTransform& pose, const PxConvexMeshGeometry& convexGeom, const PxTransform& convexPose, const PxVec3& unitDir, PxReal inflation) { if(!mStatus) return false; if(mInitialOverlap) { if(mHitFlags & PxHitFlag::eMTD) { const bool hasContacts = computeConvex_HeightFieldMTD(hfGeom, pose, convexGeom, convexPose, inflation, mIsDoubleSided, sweepHit); sweepHit.faceIndex = mSweepHit.faceIndex; sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; if(!hasContacts) { sweepHit.distance = 0.0f; sweepHit.normal = -unitDir; } else { sweepHit.flags |= PxHitFlag::ePOSITION; } } else { setInitialOverlapResults(sweepHit, unitDir, mSweepHit.faceIndex); // hit index must be set to closest for IO } } else { sweepHit = mSweepHit; sweepHit.normal = -sweepHit.normal; sweepHit.normal.normalize(); } return true; } private: PxMatTransformV mMeshToConvex; PxTransformV mConvexPoseV; ConvexHullV mConvexHull; PxGeomSweepHit mSweepHit; Vec3V mConvexSpaceDir; FloatV mDistance; const PxVec3 mUnitDir; PxVec3 mMeshSpaceUnitDir; const PxReal mInflation; }; bool sweepConvex_HeightFieldGeom(GU_CONVEX_SWEEP_FUNC_PARAMS) { PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD); PX_UNUSED(threadContext); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom); const Matrix34FromTransform convexTM(convexPose); const Matrix34FromTransform meshTM(pose); ConvexMesh* convexMesh = static_cast<ConvexMesh*>(convexGeom.convexMesh); const bool idtScaleConvex = convexGeom.scale.isIdentity(); FastVertex2ShapeScaling convexScaling; if(!idtScaleConvex) convexScaling.init(convexGeom.scale); PX_ASSERT(!convexMesh->getLocalBoundsFast().isEmpty()); const PxBounds3 hullAABBLocalSpace = convexMesh->getLocalBoundsFast().transformFast(convexScaling.getVertex2ShapeSkew()); const HeightFieldTraceUtil hfUtil(hfGeom); ConvexTraceSegmentReport entityReport( hfUtil, convexMesh->getHull(), convexGeom.scale, convexPose, pose, -unitDir, distance, hitFlags, inflation); // need hf local space stuff const PxBounds3 hullAABB = PxBounds3::transformFast(convexPose, hullAABBLocalSpace); const PxVec3 aabbExtents = hullAABB.getExtents() + PxVec3(inflation); const PxTransform inversePose = pose.getInverse(); const PxVec3 centerLocalSpace = inversePose.transform(hullAABB.getCenter()); const PxVec3 sweepDirLocalSpace = inversePose.rotate(unitDir); const PxVec3 convexAABBExtentHfLocalSpace = PxBounds3::basisExtent(centerLocalSpace, PxMat33Padded(inversePose.q), aabbExtents).getExtents(); HeightFieldTraceSegmentSweepHelper traceSegmentHelper(hfUtil, convexAABBExtentHfLocalSpace); traceSegmentHelper.traceSegment<ConvexTraceSegmentReport>(centerLocalSpace, sweepDirLocalSpace, distance, &entityReport); return entityReport.finalizeHit(sweepHit, hfGeom, pose, convexGeom, convexPose, unitDir, inflation); } /////////////////////////////////////////////////////////////////////////////// class BoxTraceSegmentReport : public HeightFieldTraceSegmentReport { PX_NOCOPY(BoxTraceSegmentReport) public: BoxTraceSegmentReport( const HeightFieldUtil& hfUtil, const PxHitFlags hitFlags, const PxTransformV& worldToBoxV, const PxTransform& pose, const BoxV& box, const PxVec3& localMotion, PxGeomSweepHit& sweepHit, PxReal inflation) : HeightFieldTraceSegmentReport (hfUtil, hitFlags), mWorldToBoxV (worldToBoxV), mPose (pose), mBox (box), mLocalMotion (localMotion), mSweepHit (sweepHit), mInflation (inflation) { mMinToi = FMax(); mSweepHit.faceIndex = 0xFFFFffff; } virtual bool onEvent(PxU32 nb, const PxU32* indices) { const FloatV zero = FZero(); const Vec3V zeroV = V3Zero(); const Vec3V dir = V3LoadU(mLocalMotion); //FloatV minToi = FMax(); FloatV toi; Vec3V closestA, normal;//closestA and normal is in the local space of box for(PxU32 i=0; i<nb; i++) { const PxU32 triangleIndex = indices[i]; PxTriangle currentTriangle; // in world space mHfUtil.getTriangle(mPose, currentTriangle, NULL, NULL, triangleIndex, true, true); const Vec3V localV0 = V3LoadU(currentTriangle.verts[0]); const Vec3V localV1 = V3LoadU(currentTriangle.verts[1]); const Vec3V localV2 = V3LoadU(currentTriangle.verts[2]); const Vec3V triV0 = mWorldToBoxV.transform(localV0); const Vec3V triV1 = mWorldToBoxV.transform(localV1); const Vec3V triV2 = mWorldToBoxV.transform(localV2); if(!mIsDoubleSided) { const Vec3V triNormal = V3Cross(V3Sub(triV2, triV1),V3Sub(triV0, triV1)); if(FAllGrtrOrEq(V3Dot(triNormal, dir), zero)) continue; } const TriangleV triangle(triV0, triV1, triV2); ////move triangle to box space //const Vec3V localV0 = Vec3V_From_PxVec3(WorldToBox.transform(currentTriangle.verts[0])); //const Vec3V localV1 = Vec3V_From_PxVec3(WorldToBox.transform(currentTriangle.verts[1])); //const Vec3V localV2 = Vec3V_From_PxVec3(WorldToBox.transform(currentTriangle.verts[2])); //TriangleV triangle(localV0, localV1, localV2); const LocalConvex<TriangleV> convexA(triangle); const LocalConvex<BoxV> convexB(mBox); const Vec3V initialSearchDir = V3Sub(triangle.getCenter(), mBox.getCenter()); if(gjkRaycastPenetration<LocalConvex<TriangleV>, LocalConvex<BoxV> >(convexA, convexB, initialSearchDir, zero, zeroV, dir, toi, normal, closestA, mInflation, false)) { mStatus = true; if(FAllGrtr(toi, zero)) { if(FAllGrtr(mMinToi, toi)) { mMinToi = toi; FStore(toi, &mSweepHit.distance); V3StoreU(normal, mSweepHit.normal); V3StoreU(closestA, mSweepHit.position); mSweepHit.faceIndex = triangleIndex; if(mIsAnyHit) return AbortTraversal; } } else { mSweepHit.distance = 0.0f; mSweepHit.faceIndex = triangleIndex; mInitialOverlap = true; return AbortTraversal; } } } return ContinueTraversal; } bool finalizeHit(PxGeomSweepHit& sweepHit, const PxHeightFieldGeometry& hfGeom, const PxTransform& pose, const PxTransform& boxPose_, const Box& box, const PxVec3& unitDir, PxReal distance, PxReal inflation) { if(!mStatus) return false; if(mInitialOverlap) { // PT: TODO: consider using 'setInitialOverlapResults' here sweepHit.flags = PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; if(mHitFlags & PxHitFlag::eMTD) { const bool hasContacts = computeBox_HeightFieldMTD(hfGeom, pose, box, boxPose_, inflation, mIsDoubleSided, sweepHit); //ML: the center of mass is below the surface, we won't have MTD contact generate if(!hasContacts) { sweepHit.distance = 0.0f; sweepHit.normal = -unitDir; } else { sweepHit.flags |= PxHitFlag::ePOSITION; } } else { sweepHit.distance = 0.0f; sweepHit.normal = -unitDir; } } else { PxVec3 n = sweepHit.normal.getNormalized(); if((n.dot(mLocalMotion))>0.0f) n = -n; sweepHit.distance *= distance; // stored as toi [0,1] during computation -> scale sweepHit.normal = boxPose_.rotate(n); sweepHit.position = boxPose_.transform(sweepHit.position); sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; } return true; } private: const PxTransformV& mWorldToBoxV; const PxTransform& mPose; const BoxV& mBox; FloatV mMinToi; const PxVec3 mLocalMotion; PxGeomSweepHit& mSweepHit; const PxReal mInflation; }; bool sweepBox_HeightFieldGeom(GU_BOX_SWEEP_FUNC_PARAMS) { PX_ASSERT(geom.getType() == PxGeometryType::eHEIGHTFIELD); PX_UNUSED(threadContext); PX_UNUSED(boxGeom_); PX_UNUSED(hitFlags); const PxHeightFieldGeometry& hfGeom = static_cast<const PxHeightFieldGeometry&>(geom); const PxVec3 boxAABBExtent = box.computeAABBExtent() + PxVec3(inflation); // Move to AABB space PX_ALIGN_PREFIX(16) PxTransform WorldToBox PX_ALIGN_SUFFIX(16); WorldToBox = boxPose_.getInverse(); const QuatV q1 = QuatVLoadA(&WorldToBox.q.x); const Vec3V p1 = V3LoadA(&WorldToBox.p.x); const PxTransformV WorldToBoxV(p1, q1); const PxVec3 motion = unitDir * distance; const PxVec3 localMotion = WorldToBox.rotate(motion); const BoxV boxV(V3Zero(), V3LoadU(box.extents)); sweepHit.distance = PX_MAX_F32; const HeightFieldTraceUtil hfUtil(hfGeom); BoxTraceSegmentReport myReport(hfUtil, hitFlags, WorldToBoxV, pose, boxV, localMotion, sweepHit, inflation); // need hf local space stuff const PxTransform inversePose = pose.getInverse(); const PxVec3 centerLocalSpace = inversePose.transform(box.center); const PxVec3 sweepDirLocalSpace = inversePose.rotate(unitDir); const PxVec3 boxAABBExtentInHfLocalSpace = PxBounds3::basisExtent(centerLocalSpace, PxMat33Padded(inversePose.q), boxAABBExtent).getExtents(); HeightFieldTraceSegmentSweepHelper traceSegmentHelper(hfUtil, boxAABBExtentInHfLocalSpace); traceSegmentHelper.traceSegment<BoxTraceSegmentReport>(centerLocalSpace, sweepDirLocalSpace, distance, &myReport); return myReport.finalizeHit(sweepHit, hfGeom, pose, boxPose_, box, unitDir, distance, inflation); } ///////////////////////////////////////////////////////////////////////////////
20,671
C++
33.168595
180
0.727638
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightFieldUtil.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxMeshScale.h" #include "GuHeightFieldUtil.h" #include "GuSweepSharedTests.h" #include "GuHeightField.h" #include "GuEntityReport.h" #include "foundation/PxIntrinsics.h" #include "CmScaling.h" using namespace physx; void Gu::HeightFieldUtil::computeLocalBounds(PxBounds3& bounds) const { const PxMeshScale scale(PxVec3(mHfGeom->rowScale, mHfGeom->heightScale, mHfGeom->columnScale), PxQuat(PxIdentity)); const PxMat33 mat33 = Cm::toMat33(scale); bounds.minimum = mat33.transform(mHeightField->getData().mAABB.getMin()); bounds.maximum = mat33.transform(mHeightField->getData().mAABB.getMax()); // PT: HFs will assert in Gu::intersectRayAABB2() if we don't deal with that const float deltaY = GU_MIN_AABB_EXTENT*0.5f - (bounds.maximum.y - bounds.minimum.y); if(deltaY>0.0f) { bounds.maximum.y += deltaY*0.6f; bounds.minimum.y -= deltaY*0.6f; } } static PX_FORCE_INLINE bool reportTriangle(Gu::OverlapReport& callback, PxU32 material, PxU32* PX_RESTRICT indexBuffer, const PxU32 bufferSize, PxU32& indexBufferUsed, PxU32 triangleIndex) { if(material != PxHeightFieldMaterial::eHOLE) { indexBuffer[indexBufferUsed++] = triangleIndex; if(indexBufferUsed >= bufferSize) { if(!callback.reportTouchedTris(indexBufferUsed, indexBuffer)) return false; indexBufferUsed = 0; } } return true; } void Gu::HeightFieldUtil::overlapAABBTriangles(const PxBounds3& bounds, OverlapReport& callback, PxU32 batchSize) const { PX_ASSERT(batchSize<=HF_OVERLAP_REPORT_BUFFER_SIZE); PX_ASSERT(!bounds.isEmpty()); PxBounds3 localBounds = bounds; localBounds.minimum.x *= mOneOverRowScale; localBounds.minimum.y *= mOneOverHeightScale; localBounds.minimum.z *= mOneOverColumnScale; localBounds.maximum.x *= mOneOverRowScale; localBounds.maximum.y *= mOneOverHeightScale; localBounds.maximum.z *= mOneOverColumnScale; if(mHfGeom->rowScale < 0.0f) PxSwap(localBounds.minimum.x, localBounds.maximum.x); if(mHfGeom->columnScale < 0.0f) PxSwap(localBounds.minimum.z, localBounds.maximum.z); // early exit for aabb does not overlap in XZ plane // DO NOT MOVE: since rowScale / columnScale may be negative this has to be done after scaling localBounds const PxU32 nbRows = mHeightField->getNbRowsFast(); const PxU32 nbColumns = mHeightField->getNbColumnsFast(); if(localBounds.minimum.x > float(nbRows - 1)) return; if(localBounds.minimum.z > float(nbColumns - 1)) return; if(localBounds.maximum.x < 0.0f) return; if(localBounds.maximum.z < 0.0f) return; const PxU32 minRow = mHeightField->getMinRow(localBounds.minimum.x); const PxU32 maxRow = mHeightField->getMaxRow(localBounds.maximum.x); const PxU32 minColumn = mHeightField->getMinColumn(localBounds.minimum.z); const PxU32 maxColumn = mHeightField->getMaxColumn(localBounds.maximum.z); const PxU32 deltaColumn = maxColumn - minColumn; const PxU32 maxNbTriangles = 2 * deltaColumn * (maxRow - minRow); if(!maxNbTriangles) return; const PxU32 bufferSize = batchSize<=HF_OVERLAP_REPORT_BUFFER_SIZE ? batchSize : HF_OVERLAP_REPORT_BUFFER_SIZE; PxU32 indexBuffer[HF_OVERLAP_REPORT_BUFFER_SIZE]; PxU32 indexBufferUsed = 0; PxU32 offset = minRow * nbColumns + minColumn; const PxReal miny = localBounds.minimum.y; const PxReal maxy = localBounds.maximum.y; const PxU32 columnStride = nbColumns - deltaColumn; for(PxU32 row=minRow; row<maxRow; row++) { for(PxU32 column=minColumn; column<maxColumn; column++) { const PxReal h0 = mHeightField->getHeight(offset); const PxReal h1 = mHeightField->getHeight(offset + 1); const PxReal h2 = mHeightField->getHeight(offset + nbColumns); const PxReal h3 = mHeightField->getHeight(offset + nbColumns + 1); const bool bmax = maxy < h0 && maxy < h1 && maxy < h2 && maxy < h3; const bool bmin = miny > h0 && miny > h1 && miny > h2 && miny > h3; if(!(bmax || bmin)) { if(!reportTriangle(callback, mHeightField->getMaterialIndex0(offset), indexBuffer, bufferSize, indexBufferUsed, offset << 1)) return; if(!reportTriangle(callback, mHeightField->getMaterialIndex1(offset), indexBuffer, bufferSize, indexBufferUsed, (offset << 1) + 1)) return; } offset++; } offset += columnStride; } if(indexBufferUsed > 0) callback.reportTouchedTris(indexBufferUsed, indexBuffer); } PxU32 Gu::HeightFieldUtil::getTriangle(const PxTransform& pose, PxTriangle& worldTri, PxU32* _vertexIndices, PxU32* adjacencyIndices, PxTriangleID triangleIndex, bool worldSpaceTranslation, bool worldSpaceRotation) const { #if PX_CHECKED if (!mHeightField->isValidTriangle(triangleIndex)) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "HeightFieldShape::getTriangle: Invalid triangle index!"); return 0; } #endif PxVec3 handedness(1.0f); // Vector to invert normal coordinates according to the heightfield scales bool wrongHanded = false; if (mHfGeom->columnScale < 0) { wrongHanded = !wrongHanded; handedness.z = -1.0f; } if (mHfGeom->rowScale < 0) { wrongHanded = !wrongHanded; handedness.x = -1.0f; } /* if (0) // ptchernev: Iterating over triangles becomes a pain. { if (mHeightField.getTriangleMaterial(triangleIndex) == mHfGeom.holeMaterialIndex) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "HeightFieldShape::getTriangle: Non-existing triangle (triangle has hole material)!"); return 0; } }*/ PxU32 vertexIndices[3]; mHeightField->getTriangleVertexIndices(triangleIndex, vertexIndices[0], vertexIndices[1+wrongHanded], vertexIndices[2-wrongHanded]); if(adjacencyIndices) { mHeightField->getTriangleAdjacencyIndices( triangleIndex, vertexIndices[0], vertexIndices[1+wrongHanded], vertexIndices[2-wrongHanded], adjacencyIndices[wrongHanded ? 2 : 0], adjacencyIndices[1], adjacencyIndices[wrongHanded ? 0 : 2]); } if(_vertexIndices) { _vertexIndices[0] = vertexIndices[0]; _vertexIndices[1] = vertexIndices[1]; _vertexIndices[2] = vertexIndices[2]; } if (worldSpaceRotation) { if (worldSpaceTranslation) { for (PxU32 vi = 0; vi < 3; vi++) worldTri.verts[vi] = hf2worldp(pose, mHeightField->getVertex(vertexIndices[vi])); } else { for (PxU32 vi = 0; vi < 3; vi++) { // TTP 2390 // local space here is rotated (but not translated) world space worldTri.verts[vi] = pose.q.rotate(hf2shapep(mHeightField->getVertex(vertexIndices[vi]))); } } } else { const PxVec3 offset = worldSpaceTranslation ? pose.p : PxVec3(0.0f); for (PxU32 vi = 0; vi < 3; vi++) worldTri.verts[vi] = hf2shapep(mHeightField->getVertex(vertexIndices[vi])) + offset; } return PxU32(mHeightField->getTriangleMaterial(triangleIndex) != PxHeightFieldMaterial::eHOLE); }
8,423
C++
35.626087
188
0.739404
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/hf/GuHeightField.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 "GuHeightField.h" #include "GuMeshFactory.h" #include "CmSerialize.h" #include "foundation/PxBitMap.h" using namespace physx; using namespace Gu; using namespace Cm; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HeightField::HeightField(MeshFactory* factory) : PxHeightField(PxConcreteType::eHEIGHTFIELD, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mSampleStride (0) , mNbSamples (0) , mMinHeight (0.0f) , mMaxHeight (0.0f) , mModifyCount (0) , mMeshFactory (factory) { mData.format = PxHeightFieldFormat::eS16_TM; mData.rows = 0; mData.columns = 0; mData.convexEdgeThreshold = 0; mData.flags = PxHeightFieldFlags(); mData.samples = NULL; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HeightField::HeightField(MeshFactory* factory, HeightFieldData& data) : PxHeightField(PxConcreteType::eHEIGHTFIELD, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE) , mSampleStride (0) , mNbSamples (0) , mMinHeight (0.0f) , mMaxHeight (0.0f) , mModifyCount (0) , mMeshFactory (factory) { mData = data; data.samples = NULL; // set to null so that we don't release the memory } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HeightField::~HeightField() { releaseMemory(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void HeightField::onRefCountZero() { ::onRefCountZero(this, mMeshFactory, false, "PxHeightField::release: double deletion detected!"); } void HeightField::exportExtraData(PxSerializationContext& stream) { // PT: warning, order matters for the converter. Needs to export the base stuff first const PxU32 size = mData.rows * mData.columns * sizeof(PxHeightFieldSample); stream.alignData(PX_SERIAL_ALIGN); // PT: generic align within the generic allocator stream.writeData(mData.samples, size); } void HeightField::importExtraData(PxDeserializationContext& context) { mData.samples = context.readExtraData<PxHeightFieldSample, PX_SERIAL_ALIGN>(mData.rows * mData.columns); } HeightField* HeightField::createObject(PxU8*& address, PxDeserializationContext& context) { HeightField* obj = PX_PLACEMENT_NEW(address, HeightField(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(HeightField); obj->importExtraData(context); obj->resolveReferences(context); return obj; } void HeightField::release() { RefCountable_decRefCount(*this); } void HeightField::acquireReference() { RefCountable_incRefCount(*this); } PxU32 HeightField::getReferenceCount() const { return RefCountable_getRefCount(*this); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool HeightField::modifySamples(PxI32 startCol, PxI32 startRow, const PxHeightFieldDesc& desc, bool shrinkBounds) { const PxU32 nbCols = getNbColumns(); const PxU32 nbRows = getNbRows(); PX_CHECK_AND_RETURN_NULL(desc.format == mData.format, "Gu::HeightField::modifySamples: desc.format mismatch"); //PX_CHECK_AND_RETURN_NULL(startCol + desc.nbColumns <= nbCols, // "Gu::HeightField::modifySamples: startCol + nbColumns out of range"); //PX_CHECK_AND_RETURN_NULL(startRow + desc.nbRows <= nbRows, // "Gu::HeightField::modifySamples: startRow + nbRows out of range"); //PX_CHECK_AND_RETURN_NULL(desc.samples.stride == mSampleStride, "Gu::HeightField::modifySamples: desc.samples.stride mismatch"); // by default bounds don't shrink since the whole point of this function is to avoid modifying the whole HF // unless shrinkBounds is specified. then the bounds will be fully recomputed later PxReal minHeight = mMinHeight; PxReal maxHeight = mMaxHeight; PxU32 hiRow = PxMin(PxU32(PxMax(0, startRow + PxI32(desc.nbRows))), nbRows); PxU32 hiCol = PxMin(PxU32(PxMax(0, startCol + PxI32(desc.nbColumns))), nbCols); for (PxU32 row = PxU32(PxMax(startRow, 0)); row < hiRow; row++) { for (PxU32 col = PxU32(PxMax(startCol, 0)); col < hiCol; col++) { const PxU32 vertexIndex = col + row*nbCols; PxHeightFieldSample* targetSample = &mData.samples[vertexIndex]; // update target sample from source sample const PxHeightFieldSample& sourceSample = (reinterpret_cast<const PxHeightFieldSample*>(desc.samples.data))[col - startCol + (row - startRow) * desc.nbColumns]; *targetSample = sourceSample; if(isCollisionVertexPreca(vertexIndex, row, col, PxHeightFieldMaterial::eHOLE)) targetSample->materialIndex1.setBit(); else targetSample->materialIndex1.clearBit(); // grow (but not shrink) the height extents const PxReal h = getHeight(vertexIndex); minHeight = physx::intrinsics::selectMin(h, minHeight); maxHeight = physx::intrinsics::selectMax(h, maxHeight); } } if (shrinkBounds) { // do a full recompute on vertical bounds to allow shrinking minHeight = PX_MAX_REAL; maxHeight = -PX_MAX_REAL; // have to recompute the min&max from scratch... for (PxU32 vertexIndex = 0; vertexIndex < nbRows * nbCols; vertexIndex ++) { // update height extents const PxReal h = getHeight(vertexIndex); minHeight = physx::intrinsics::selectMin(h, minHeight); maxHeight = physx::intrinsics::selectMax(h, maxHeight); } } mMinHeight = minHeight; mMaxHeight = maxHeight; // update local space aabb CenterExtents& bounds = mData.mAABB; bounds.mCenter.y = (maxHeight + minHeight)*0.5f; bounds.mExtents.y = (maxHeight - minHeight)*0.5f; mModifyCount++; return true; } bool HeightField::load(PxInputStream& stream) { // release old memory releaseMemory(); // Import header PxU32 version; bool endian; if(!readHeader('H', 'F', 'H', 'F', version, endian, stream)) return false; // load mData mData.rows = readDword(endian, stream); mData.columns = readDword(endian, stream); if(version>=2) { mData.rowLimit = readDword(endian, stream); mData.colLimit = readDword(endian, stream); mData.nbColumns = readDword(endian, stream); } else { mData.rowLimit = PxU32(readFloat(endian, stream)); mData.colLimit = PxU32(readFloat(endian, stream)); mData.nbColumns = PxU32(readFloat(endian, stream)); } const float thickness = readFloat(endian, stream); PX_UNUSED(thickness); mData.convexEdgeThreshold = readFloat(endian, stream); PxU16 flags = readWord(endian, stream); mData.flags = PxHeightFieldFlags(flags); PxU32 format = readDword(endian, stream); mData.format = PxHeightFieldFormat::Enum(format); PxBounds3 minMaxBounds; minMaxBounds.minimum.x = readFloat(endian, stream); minMaxBounds.minimum.y = readFloat(endian, stream); minMaxBounds.minimum.z = readFloat(endian, stream); minMaxBounds.maximum.x = readFloat(endian, stream); minMaxBounds.maximum.y = readFloat(endian, stream); minMaxBounds.maximum.z = readFloat(endian, stream); mData.mAABB = CenterExtents(minMaxBounds); mSampleStride = readDword(endian, stream); mNbSamples = readDword(endian, stream); mMinHeight = readFloat(endian, stream); mMaxHeight = readFloat(endian, stream); // allocate height samples mData.samples = NULL; const PxU32 nbVerts = mData.rows * mData.columns; if (nbVerts > 0) { mData.samples = PX_ALLOCATE(PxHeightFieldSample, nbVerts, "PxHeightFieldSample"); if (mData.samples == NULL) return PxGetFoundation().error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "Gu::HeightField::load: PX_ALLOC failed!"); stream.read(mData.samples, mNbSamples*sizeof(PxHeightFieldSample)); if (endian) for(PxU32 i = 0; i < mNbSamples; i++) { PxHeightFieldSample& s = mData.samples[i]; PX_ASSERT(sizeof(PxU16) == sizeof(s.height)); flip(s.height); } } return true; } bool HeightField::loadFromDesc(const PxHeightFieldDesc& desc) { // verify descriptor PX_CHECK_AND_RETURN_NULL(desc.isValid(), "Gu::HeightField::loadFromDesc: desc.isValid() failed!"); // release old memory releaseMemory(); // copy trivial data mData.format = desc.format; mData.rows = desc.nbRows; mData.columns = desc.nbColumns; mData.convexEdgeThreshold = desc.convexEdgeThreshold; mData.flags = desc.flags; mSampleStride = desc.samples.stride; mData.rowLimit = mData.rows - 2; mData.colLimit = mData.columns - 2; mData.nbColumns = desc.nbColumns; // allocate and copy height samples // compute extents too mData.samples = NULL; const PxU32 nbVerts = desc.nbRows * desc.nbColumns; mMinHeight = PX_MAX_REAL; mMaxHeight = -PX_MAX_REAL; if(nbVerts > 0) { mData.samples = PX_ALLOCATE(PxHeightFieldSample, nbVerts, "PxHeightFieldSample"); if(!mData.samples) return PxGetFoundation().error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "Gu::HeightField::load: PX_ALLOC failed!"); const PxU8* PX_RESTRICT src = reinterpret_cast<const PxU8*>(desc.samples.data); PxHeightFieldSample* PX_RESTRICT dst = mData.samples; PxI16 minHeight = PX_MAX_I16; PxI16 maxHeight = PX_MIN_I16; for(PxU32 i=0;i<nbVerts;i++) { const PxHeightFieldSample& sample = *reinterpret_cast<const PxHeightFieldSample*>(src); *dst++ = sample; const PxI16 height = sample.height; minHeight = height < minHeight ? height : minHeight; maxHeight = height > maxHeight ? height : maxHeight; src += desc.samples.stride; } mMinHeight = PxReal(minHeight); mMaxHeight = PxReal(maxHeight); } PX_ASSERT(mMaxHeight >= mMinHeight); parseTrianglesForCollisionVertices(PxHeightFieldMaterial::eHOLE); // PT: "mNbSamples" only used by binary converter mNbSamples = mData.rows * mData.columns; //Compute local space aabb. PxBounds3 bounds; bounds.minimum.y = getMinHeight(); bounds.maximum.y = getMaxHeight(); bounds.minimum.x = 0; bounds.maximum.x = PxReal(getNbRowsFast() - 1); bounds.minimum.z = 0; bounds.maximum.z = PxReal(getNbColumnsFast() - 1); mData.mAABB=bounds; return true; } bool HeightField::save(PxOutputStream& stream, bool endian) { // write header if(!writeHeader('H', 'F', 'H', 'F', PX_HEIGHTFIELD_VERSION, endian, stream)) return false; const Gu::HeightFieldData& hfData = getData(); // write mData members writeDword(hfData.rows, endian, stream); writeDword(hfData.columns, endian, stream); writeDword(hfData.rowLimit, endian, stream); writeDword(hfData.colLimit, endian, stream); writeDword(hfData.nbColumns, endian, stream); writeFloat(0.0f, endian, stream); // thickness writeFloat(hfData.convexEdgeThreshold, endian, stream); writeWord(hfData.flags, endian, stream); writeDword(hfData.format, endian, stream); writeFloat(hfData.mAABB.getMin(0), endian, stream); writeFloat(hfData.mAABB.getMin(1), endian, stream); writeFloat(hfData.mAABB.getMin(2), endian, stream); writeFloat(hfData.mAABB.getMax(0), endian, stream); writeFloat(hfData.mAABB.getMax(1), endian, stream); writeFloat(hfData.mAABB.getMax(2), endian, stream); // write this-> members writeDword(mSampleStride, endian, stream); writeDword(mNbSamples, endian, stream); writeFloat(mMinHeight, endian, stream); writeFloat(mMaxHeight, endian, stream); // write samples for(PxU32 i=0; i<mNbSamples; i++) { const PxHeightFieldSample& s = hfData.samples[i]; writeWord(PxU16(s.height), endian, stream); stream.write(&s.materialIndex0, sizeof(s.materialIndex0)); stream.write(&s.materialIndex1, sizeof(s.materialIndex1)); } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PxU32 HeightField::saveCells(void* destBuffer, PxU32 destBufferSize) const { PxU32 n = mData.columns * mData.rows * sizeof(PxHeightFieldSample); if (n > destBufferSize) n = destBufferSize; PxMemCopy(destBuffer, mData.samples, n); return n; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void HeightField::releaseMemory() { if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { PX_FREE(mData.samples); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace { struct EdgeData { PxU32 edgeIndex; PxU32 cell; PxU32 row; PxU32 column; }; } // PT: TODO: use those faster functions everywhere static PxU32 getVertexEdgeIndices(const HeightField& heightfield, PxU32 vertexIndex, PxU32 row, PxU32 column, EdgeData edgeIndices[8]) { const PxU32 nbColumns = heightfield.getData().columns; const PxU32 nbRows = heightfield.getData().rows; PX_ASSERT((vertexIndex / nbColumns)==row); PX_ASSERT((vertexIndex % nbColumns)==column); PxU32 count = 0; if (row > 0) { // edgeIndices[count++] = 3 * (vertexIndex - nbColumns) + 2; const PxU32 cell = vertexIndex - nbColumns; edgeIndices[count].edgeIndex = 3 * cell + 2; edgeIndices[count].cell = cell; edgeIndices[count].row = row-1; edgeIndices[count].column = column; count++; } if (column < nbColumns-1) { if (row > 0) { if (!heightfield.isZerothVertexShared(vertexIndex - nbColumns)) { // edgeIndices[count++] = 3 * (vertexIndex - nbColumns) + 1; const PxU32 cell = vertexIndex - nbColumns; edgeIndices[count].edgeIndex = 3 * cell + 1; edgeIndices[count].cell = cell; edgeIndices[count].row = row-1; edgeIndices[count].column = column; count++; } } // edgeIndices[count++] = 3 * vertexIndex; edgeIndices[count].edgeIndex = 3 * vertexIndex; edgeIndices[count].cell = vertexIndex; edgeIndices[count].row = row; edgeIndices[count].column = column; count++; if (row < nbRows - 1) { if (heightfield.isZerothVertexShared(vertexIndex)) { // edgeIndices[count++] = 3 * vertexIndex + 1; edgeIndices[count].edgeIndex = 3 * vertexIndex + 1; edgeIndices[count].cell = vertexIndex; edgeIndices[count].row = row; edgeIndices[count].column = column; count++; } } } if (row < nbRows - 1) { // edgeIndices[count++] = 3 * vertexIndex + 2; edgeIndices[count].edgeIndex = 3 * vertexIndex + 2; edgeIndices[count].cell = vertexIndex; edgeIndices[count].row = row; edgeIndices[count].column = column; count++; } if (column > 0) { if (row < nbRows - 1) { if (!heightfield.isZerothVertexShared(vertexIndex - 1)) { // edgeIndices[count++] = 3 * (vertexIndex - 1) + 1; const PxU32 cell = vertexIndex - 1; edgeIndices[count].edgeIndex = 3 * cell + 1; edgeIndices[count].cell = cell; edgeIndices[count].row = row; edgeIndices[count].column = column-1; count++; } } // edgeIndices[count++] = 3 * (vertexIndex - 1); const PxU32 cell = vertexIndex - 1; edgeIndices[count].edgeIndex = 3 * cell; edgeIndices[count].cell = cell; edgeIndices[count].row = row; edgeIndices[count].column = column-1; count++; if (row > 0) { if (heightfield.isZerothVertexShared(vertexIndex - nbColumns - 1)) { // edgeIndices[count++] = 3 * (vertexIndex - nbColumns - 1) + 1; const PxU32 cell1 = vertexIndex - nbColumns - 1; edgeIndices[count].edgeIndex = 3 * cell1 + 1; edgeIndices[count].cell = cell1; edgeIndices[count].row = row-1; edgeIndices[count].column = column-1; count++; } } } return count; } static PxU32 getEdgeTriangleIndices(const HeightField& heightfield, const EdgeData& edgeData, PxU32* PX_RESTRICT triangleIndices) { const PxU32 nbColumns = heightfield.getData().columns; const PxU32 nbRows = heightfield.getData().rows; const PxU32 edgeIndex = edgeData.edgeIndex; const PxU32 cell = edgeData.cell; const PxU32 row = edgeData.row; const PxU32 column = edgeData.column; PX_ASSERT(cell==edgeIndex / 3); PX_ASSERT(row==cell / nbColumns); PX_ASSERT(column==cell % nbColumns); PxU32 count = 0; switch (edgeIndex - cell*3) { case 0: if (column < nbColumns - 1) { if (row > 0) { if (heightfield.isZerothVertexShared(cell - nbColumns)) triangleIndices[count++] = ((cell - nbColumns) << 1); else triangleIndices[count++] = ((cell - nbColumns) << 1) + 1; } if (row < nbRows - 1) { if (heightfield.isZerothVertexShared(cell)) triangleIndices[count++] = (cell << 1) + 1; else triangleIndices[count++] = cell << 1; } } break; case 1: if ((row < nbRows - 1) && (column < nbColumns - 1)) { triangleIndices[count++] = cell << 1; triangleIndices[count++] = (cell << 1) + 1; } break; case 2: if (row < nbRows - 1) { if (column > 0) { triangleIndices[count++] = ((cell - 1) << 1) + 1; } if (column < nbColumns - 1) { triangleIndices[count++] = cell << 1; } } break; } return count; } PX_FORCE_INLINE PxU32 anyHole(PxU32 doubleMatIndex, PxU16 holeMaterialIndex) { return PxU32((doubleMatIndex & 0xFFFF) == holeMaterialIndex) | (PxU32(doubleMatIndex >> 16) == holeMaterialIndex); } void HeightField::parseTrianglesForCollisionVertices(PxU16 holeMaterialIndex) { const PxU32 nbColumns = getNbColumnsFast(); const PxU32 nbRows = getNbRowsFast(); PxBitMap rowHoles[2]; rowHoles[0].resizeAndClear(nbColumns + 1); rowHoles[1].resizeAndClear(nbColumns + 1); for (PxU32 iCol = 0; iCol < nbColumns; iCol++) { if (anyHole(getMaterialIndex01(iCol), holeMaterialIndex)) { rowHoles[0].set(iCol); rowHoles[0].set(iCol + 1); } PxU32 vertIndex = iCol; if(isCollisionVertexPreca(vertIndex, 0, iCol, holeMaterialIndex)) mData.samples[vertIndex].materialIndex1.setBit(); else mData.samples[vertIndex].materialIndex1.clearBit(); } PxU32 nextRow = 1, currentRow = 0; for (PxU32 iRow = 1; iRow < nbRows; iRow++) { PxU32 rowOffset = iRow*nbColumns; for (PxU32 iCol = 0; iCol < nbColumns; iCol++) { const PxU32 vertIndex = rowOffset + iCol; // column index plus current row offset (vertex/cell index) if(anyHole(getMaterialIndex01(vertIndex), holeMaterialIndex)) { rowHoles[currentRow].set(iCol); rowHoles[currentRow].set(iCol + 1); rowHoles[nextRow].set(iCol); rowHoles[nextRow].set(iCol + 1); } if ((iCol == 0) || (iCol == nbColumns - 1) || (iRow == nbRows - 1) || rowHoles[currentRow].test(iCol)) { if(isCollisionVertexPreca(vertIndex, iRow, iCol, holeMaterialIndex)) mData.samples[vertIndex].materialIndex1.setBit(); else mData.samples[vertIndex].materialIndex1.clearBit(); } else { if (isConvexVertex(vertIndex, iRow, iCol)) mData.samples[vertIndex].materialIndex1.setBit(); } } rowHoles[currentRow].clear(); // swap prevRow and prevPrevRow nextRow ^= 1; currentRow ^= 1; } } bool HeightField::isSolidVertex(PxU32 vertexIndex, PxU32 row, PxU32 column, PxU16 holeMaterialIndex, bool& nbSolid) const { // check if solid and boundary // retrieve edge indices for current vertexIndex EdgeData edgeIndices[8]; const PxU32 edgeCount = ::getVertexEdgeIndices(*this, vertexIndex, row, column, edgeIndices); PxU32 faceCounts[8]; PxU32 faceIndices[2 * 8]; PxU32* dst = faceIndices; for (PxU32 i = 0; i < edgeCount; i++) { faceCounts[i] = ::getEdgeTriangleIndices(*this, edgeIndices[i], dst); dst += 2; } nbSolid = false; const PxU32* currentfaceIndices = faceIndices; // parallel array of pairs of face indices per edge index for (PxU32 i = 0; i < edgeCount; i++) { if (faceCounts[i] > 1) { const PxU16& material0 = getTriangleMaterial(currentfaceIndices[0]); const PxU16& material1 = getTriangleMaterial(currentfaceIndices[1]); // ptchernev TODO: this is a bit arbitrary if (material0 != holeMaterialIndex) { nbSolid = true; if (material1 == holeMaterialIndex) return true; // edge between solid and hole => return true } if (material1 != holeMaterialIndex) { nbSolid = true; if (material0 == holeMaterialIndex) return true; // edge between hole and solid => return true } } else { if (getTriangleMaterial(currentfaceIndices[0]) != holeMaterialIndex) return true; } currentfaceIndices += 2; // 2 face indices per edge } return false; } bool HeightField::isCollisionVertexPreca(PxU32 vertexIndex, PxU32 row, PxU32 column, PxU16 holeMaterialIndex) const { #ifdef PX_HEIGHTFIELD_DEBUG PX_ASSERT(isValidVertex(vertexIndex)); #endif PX_ASSERT((vertexIndex / getNbColumnsFast()) == row); PX_ASSERT((vertexIndex % getNbColumnsFast()) == column); // check boundary conditions - boundary edges shouldn't produce collision with eNO_BOUNDARY_EDGES flag if(mData.flags & PxHeightFieldFlag::eNO_BOUNDARY_EDGES) if ((row == 0) || (column == 0) || (row >= mData.rows-1) || (column >= mData.columns-1)) return false; bool nbSolid; if(isSolidVertex(vertexIndex, row, column, holeMaterialIndex, nbSolid)) return true; // return true if it is boundary or solid and convex return (nbSolid && isConvexVertex(vertexIndex, row, column)); } // AP: this naming is confusing and inconsistent with return value. the function appears to compute vertex coord rather than cell coords // it would most likely be better to stay in cell coords instead, since fractional vertex coords just do not make any sense PxU32 HeightField::computeCellCoordinates(PxReal x, PxReal z, PxReal& fracX, PxReal& fracZ) const { namespace i = physx::intrinsics; x = i::selectMax(x, 0.0f); z = i::selectMax(z, 0.0f); #if 0 // validation code for scaled clamping epsilon computation for (PxReal ii = 1.0f; ii < 100000.0f; ii+=1.0f) { PX_UNUSED(ii); PX_ASSERT(PxFloor(ii+(1-1e-7f*ii)) == ii); } #endif const PxF32 epsx = 1.0f - PxAbs(x+1.0f) * 1e-6f; // epsilon needs to scale with values of x,z... const PxF32 epsz = 1.0f - PxAbs(z+1.0f) * 1e-6f; PxF32 x1 = i::selectMin(x, float(mData.rowLimit)+epsx); PxF32 z1 = i::selectMin(z, float(mData.colLimit)+epsz); x = PxFloor(x1); fracX = x1 - x; z = PxFloor(z1); fracZ = z1 - z; PX_ASSERT(x >= 0.0f && x < PxF32(mData.rows)); PX_ASSERT(z >= 0.0f && z < PxF32(mData.columns)); const PxU32 vertexIndex = PxU32(x) * mData.nbColumns + PxU32(z); PX_ASSERT(vertexIndex < mData.rows*mData.columns); return vertexIndex; }
24,425
C++
31.874832
199
0.658956
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactBoxConvex.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 "geomutils/PxContactBuffer.h" #include "GuGJKPenetration.h" #include "GuEPA.h" #include "GuVecBox.h" #include "GuVecConvexHull.h" #include "GuVecConvexHullNoScale.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" #define PCM_BOX_HULL_DEBUG 0 using namespace physx; using namespace Gu; using namespace aos; static bool fullContactsGenerationBoxConvex(const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxTransformV& transf0, const PxTransformV& transf1, PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer, PersistentContactManifold& manifold, Vec3VArg normal, const Vec3VArg closestA, const Vec3VArg closestB, const FloatVArg contactDist, bool idtScale, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength) { PolygonalData polyData0; const BoxV& box = relativeConvex->getConvex<BoxV>(); const ConvexHullV& convexHull = localConvex->getConvex<ConvexHullV>(); PxVec3 halfExtents; V3StoreU(box.extents, halfExtents); PCMPolygonalBox polyBox0(halfExtents); polyBox0.getPolygonalData(&polyData0); polyData0.mPolygonVertexRefs = gPCMBoxPolygonData; PolygonalData polyData1; getPCMConvexData(convexHull, idtScale, polyData1); const Mat33V identity = M33Identity(); SupportLocalImpl<BoxV> map0(box, transf0, identity, identity, true); PX_ALIGN(16, PxU8 buff1[sizeof(SupportLocalImpl<ConvexHullV>)]); SupportLocal* map1 = (idtScale ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff1, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull), transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)) : static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff1, SupportLocalImpl<ConvexHullV>)(convexHull, transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale))); PxU32 numContacts = 0; if(generateFullContactManifold(polyData0, polyData1, &map0, map1, manifoldContacts, numContacts, contactDist, normal, closestA, closestB, box.getMarginF(), convexHull.getMarginF(), doOverlapTest, renderOutput, toleranceLength)) { if (numContacts > 0) { //reduce contacts manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif const Vec3V worldNormal = manifold.getWorldNormal(transf1); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist); } else { //if doOverlapTest is true, which means GJK/EPA degenerate so we won't have any contact in the manifoldContacts array if (!doOverlapTest) { const Vec3V worldNormal = manifold.getWorldNormal(transf1); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist); } } return true; } return false; } static bool generateOrProcessContactsBoxConvex( const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxTransformV& transf0, const PxTransformV& transf1, const PxMatTransformV& aToB, GjkStatus status, GjkOutput& output, PersistentContactManifold& manifold, PxContactBuffer& contactBuffer, PxU32 initialContacts, const FloatV minMargin, const FloatV contactDist, bool idtScale, PxReal toleranceLength, PxRenderOutput* renderOutput) { if (status == GJK_NON_INTERSECT) { return false; } else { PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); const Vec3V localNor = manifold.mNumContacts ? manifold.getLocalNormal() : V3Zero(); const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f)); //addGJKEPAContacts will increase the number of contacts in manifold. If status == EPA_CONTACT, we need to run epa algorithm and generate closest points, normal and //pentration. If epa doesn't degenerate, we will store the contacts information in the manifold. Otherwise, we will return true to do the fallback test const bool doOverlapTest = addGJKEPAContacts(relativeConvex, localConvex, aToB, status, manifoldContacts, replaceBreakingThreshold, FLoad(toleranceLength), output, manifold); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif //ML: after we refresh the contacts(newContacts) and generate a GJK/EPA contacts(we will store that in the manifold), if the number of contacts is still less than the original contacts, //which means we lose too mang contacts and we should regenerate all the contacts in the current configuration //Also, we need to look at the existing contacts, if the existing contacts has very different normal than the GJK/EPA contacts, //which means we should throw away the existing contacts and do full contact gen const bool fullContactGen = FAllGrtr(FLoad(0.707106781f), V3Dot(localNor, output.normal)) || (manifold.mNumContacts < initialContacts); if (fullContactGen || doOverlapTest) { return fullContactsGenerationBoxConvex(relativeConvex, localConvex, transf0, transf1, manifoldContacts, contactBuffer, manifold, output.normal, output.closestA, output.closestB, contactDist, idtScale, doOverlapTest, renderOutput, toleranceLength); } else { const Vec3V newLocalNor = V3Add(localNor, output.normal); const Vec3V worldNormal = V3Normalize(transf1.rotate(newLocalNor)); //const Vec3V worldNormal = transf1.rotate(normal); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist); return true; } } } bool Gu::pcmContactBoxConvex(GU_CONTACT_METHOD_ARGS) { PX_ASSERT(transform1.q.isSane()); PX_ASSERT(transform0.q.isSane()); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); PersistentContactManifold& manifold = cache.getManifold(); const ConvexHullData* hullData = _getHullData(shapeConvex); PxPrefetchLine(hullData); const FloatV contactDist = FLoad(params.mContactDistance); const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const PxTransformV transf0 = loadTransformA(transform0); const PxTransformV transf1 = loadTransformA(transform1); const PxTransformV curRTrans(transf1.transformInv(transf0)); const PxMatTransformV aToB(curRTrans); const PxReal toleranceLength = params.mToleranceLength; const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength); const FloatV boxMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength); #if PCM_BOX_HULL_DEBUG const PxVec3* verts = hullData->getHullVertices(); for (PxU32 i = 0; i < hullData->mNbPolygons; ++i) { const HullPolygonData& polygon = hullData->mPolygons[i]; const PxU8* inds = hullData->getVertexData8() + polygon.mVRef8; Vec3V* points = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*polygon.mNbVerts, 16)); for (PxU32 j = 0; j < polygon.mNbVerts; ++j) { points[j] = V3LoadU_SafeReadW(verts[inds[j]]); } PersistentContactManifold::drawPolygon(*renderOutput, transf1, points, (PxU32)polygon.mNbVerts, 0x00ff0000); } #endif const FloatV minMargin = FMin(convexMargin, boxMargin);//FMin(boxMargin, convexMargin); const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f)); const PxU32 initialContacts = manifold.mNumContacts; manifold.refreshContactPoints(aToB, projectBreakingThreshold, contactDist); const Vec3V extents = V3Mul(V3LoadU(hullData->mInternal.mExtents), vScale); const FloatV radiusA = V3Length(boxExtents); const FloatV radiusB = V3Length(extents); //After the refresh contact points, the numcontacts in the manifold will be changed const bool bLostContacts = (manifold.mNumContacts != initialContacts); if(bLostContacts || manifold.invalidate_BoxConvex(curRTrans, transf0.q, transf1.q, minMargin, radiusA, radiusB)) { manifold.setRelativeTransform(curRTrans, transf0.q, transf1.q); GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT; const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const bool idtScale = shapeConvex.scale.isIdentity(); const ConvexHullV convexHull(hullData, V3LoadU(hullData->mCenterOfMass), vScale, vQuat, idtScale); const BoxV box(V3Zero(), boxExtents); GjkOutput output; const RelativeConvex<BoxV> relativeConvex(box, aToB); if(idtScale) { const LocalConvex<ConvexHullNoScaleV> localConvex(static_cast<const ConvexHullNoScaleV&>(convexHull)); status = gjkPenetration<RelativeConvex<BoxV>, LocalConvex<ConvexHullNoScaleV> >(relativeConvex, localConvex, aToB.p, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); return generateOrProcessContactsBoxConvex(&relativeConvex, &localConvex, transf0, transf1, aToB, status, output, manifold, contactBuffer, initialContacts, minMargin, contactDist, idtScale, toleranceLength, renderOutput); } else { const LocalConvex<ConvexHullV> localConvex(convexHull); status = gjkPenetration<RelativeConvex<BoxV>, LocalConvex<ConvexHullV> >(relativeConvex, localConvex, aToB.p, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); return generateOrProcessContactsBoxConvex(&relativeConvex, &localConvex, transf0, transf1, aToB, status, output, manifold, contactBuffer, initialContacts, minMargin, contactDist, idtScale, toleranceLength, renderOutput); } } else if(manifold.getNumContacts()>0) { const Vec3V worldNormal = manifold.getWorldNormal(transf1); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } return false; }
11,634
C++
44.272373
247
0.776947
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleMesh.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 "GuVecTriangle.h" #include "GuContactMethodImpl.h" #include "GuPCMContactConvexCommon.h" #include "GuInternal.h" #include "GuPCMContactMeshCallback.h" #include "GuBarycentricCoordinates.h" #include "GuBox.h" using namespace physx; using namespace Gu; using namespace aos; namespace { struct PCMCapsuleVsMeshContactGenerationCallback : PCMMeshContactGenerationCallback< PCMCapsuleVsMeshContactGenerationCallback > { PCMCapsuleVsMeshContactGenerationCallback& operator=(const PCMCapsuleVsMeshContactGenerationCallback&); PCMCapsuleVsMeshContactGeneration mGeneration; PCMCapsuleVsMeshContactGenerationCallback( const CapsuleV& capsule, const FloatVArg contactDist, const FloatVArg replaceBreakingThreshold, const PxTransformV& sphereTransform, const PxTransformV& meshTransform, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, const PxU8* extraTriData, const Cm::FastVertex2ShapeScaling& meshScaling, bool idtMeshScale, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, PxRenderOutput* renderOutput = NULL ) : PCMMeshContactGenerationCallback<PCMCapsuleVsMeshContactGenerationCallback>(meshScaling, extraTriData, idtMeshScale), mGeneration(capsule, contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer, deferredContacts, renderOutput) { } PX_FORCE_INLINE bool doTest(const PxVec3&, const PxVec3&, const PxVec3&) { return true; } template<PxU32 CacheSize> void processTriangleCache(TriangleCache<CacheSize>& cache) { mGeneration.processTriangleCache<CacheSize, PCMCapsuleVsMeshContactGeneration>(cache); } }; } bool Gu::pcmContactCapsuleMesh(GU_CONTACT_METHOD_ARGS) { MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); //gRenderOutPut = cache.mRenderOutput; const FloatV capsuleRadius = FLoad(shapeCapsule.radius); const FloatV contactDist = FLoad(params.mContactDistance); const PxTransformV capsuleTransform = loadTransformA(transform0);//capsule transform const PxTransformV meshTransform = loadTransformA(transform1);//triangleMesh const PxTransformV curTransform = meshTransform.transformInv(capsuleTransform); // We must be in local space to use the cache if(multiManifold.invalidate(curTransform, capsuleRadius, FLoad(0.02f))) { const FloatV replaceBreakingThreshold = FMul(capsuleRadius, FLoad(0.001f)); //const FloatV capsuleHalfHeight = FloatV_From_F32(shapeCapsule.halfHeight); Cm::FastVertex2ShapeScaling meshScaling; const bool idtMeshScale = shapeMesh.scale.isIdentity(); if(!idtMeshScale) meshScaling.init(shapeMesh.scale); // Capsule data const PxVec3 tmp = getCapsuleHalfHeightVector(transform0, shapeCapsule); const Segment worldCapsule(transform0.p + tmp, transform0.p - tmp); const Segment meshCapsule( // Capsule in mesh space transform1.transformInv(worldCapsule.p0), transform1.transformInv(worldCapsule.p1)); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; const PxVec3 capsuleCenterInMesh = transform1.transformInv(transform0.p); const PxVec3 capsuleDirInMesh = transform1.rotateInv(tmp); const CapsuleV capsule(V3LoadU(capsuleCenterInMesh), V3LoadU(capsuleDirInMesh), capsuleRadius); // We must be in local space to use the cache const Capsule queryCapsule(meshCapsule, inflatedRadius); const TriangleMesh* meshData = _getMeshData(shapeMesh); multiManifold.mNumManifolds = 0; multiManifold.setRelativeTransform(curTransform); const PxU8* PX_RESTRICT extraData = meshData->getExtraTrigData(); // mesh scale is not baked into cached verts PCMCapsuleVsMeshContactGenerationCallback callback( capsule, contactDist, replaceBreakingThreshold, capsuleTransform, meshTransform, multiManifold, contactBuffer, extraData, meshScaling, idtMeshScale, NULL, renderOutput); //bound the capsule in shape space by an OBB: Box queryBox; queryBox.create(queryCapsule); //apply the skew transform to the box: if(!idtMeshScale) meshScaling.transformQueryBounds(queryBox.center, queryBox.extents, queryBox.rot); Midphase::intersectOBB(meshData, queryBox, callback, true); callback.flushCache(); callback.mGeneration.processContacts(GU_CAPSULE_MANIFOLD_CACHE_SIZE, false); } else { const PxMatTransformV aToB(curTransform); const FloatV projectBreakingThreshold = FMul(capsuleRadius, FLoad(0.05f)); const FloatV refereshDistance = FAdd(capsuleRadius, contactDist); //multiManifold.refreshManifold(aToB, projectBreakingThreshold, contactDist); multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance); } //multiManifold.drawManifold(*gRenderOutPut, capsuleTransform, meshTransform); return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, capsuleTransform, meshTransform, capsuleRadius); } void Gu::PCMCapsuleVsMeshContactGeneration::generateEE(const Vec3VArg p, const Vec3VArg q, const FloatVArg sqInflatedRadius, const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg a, const Vec3VArg b, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { const FloatV zero = FZero(); const Vec3V ab = V3Sub(b, a); const Vec3V n = V3Cross(ab, normal); const FloatV d = V3Dot(n, a); const FloatV np = V3Dot(n, p); const FloatV nq = V3Dot(n,q); const FloatV signP = FSub(np, d); const FloatV signQ = FSub(nq, d); const FloatV temp = FMul(signP, signQ); if(FAllGrtr(temp, zero)) return;//If both points in the same side as the plane, no intersect points // if colliding edge (p3,p4) and plane are parallel return no collision const Vec3V pq = V3Sub(q, p); const FloatV npq= V3Dot(n, pq); if(FAllEq(npq, zero)) return; const FloatV one = FOne(); //calculate the intersect point in the segment pq const FloatV segTValue = FDiv(FSub(d, np), npq); const Vec3V localPointA = V3ScaleAdd(pq, segTValue, p); //calculate a normal perpendicular to ray localPointA + normal, 2D segment segment intersection const Vec3V perNormal = V3Cross(normal, pq); const Vec3V ap = V3Sub(localPointA, a); const FloatV nom = V3Dot(perNormal, ap); const FloatV denom = V3Dot(perNormal, ab); //const FloatV tValue = FClamp(FDiv(nom, denom), zero, FOne()); const FloatV tValue = FDiv(nom, denom); const BoolV con = BAnd(FIsGrtrOrEq(one, tValue), FIsGrtrOrEq(tValue, zero)); if(BAllEqFFFF(con)) return; //const Vec3V localPointB = V3ScaleAdd(ab, tValue, a); v = V3Sub(localPointA, localPointB); v = V3NegScaleSub(ab, tValue, tap) const Vec3V v = V3NegScaleSub(ab, tValue, ap); const FloatV sqDist = V3Dot(v, v); if(FAllGrtr(sqInflatedRadius, sqDist)) { const Vec3V localPointB = V3Sub(localPointA, v); const FloatV signedDist = V3Dot(v, normal); manifoldContacts[numContacts].mLocalPointA = localPointA; manifoldContacts[numContacts].mLocalPointB = localPointB; manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), signedDist); manifoldContacts[numContacts++].mFaceIndex = triangleIndex; } } void Gu::PCMCapsuleVsMeshContactGeneration::generateEEContacts(const Vec3VArg a, const Vec3VArg b, const Vec3VArg c, const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg p, const Vec3VArg q, const FloatVArg sqInflatedRadius, PxU32 previousNumContacts, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { if((numContacts - previousNumContacts) < 2) generateEE(p, q, sqInflatedRadius, normal, triangleIndex, a, b, manifoldContacts, numContacts); if((numContacts - previousNumContacts) < 2) generateEE(p, q, sqInflatedRadius, normal, triangleIndex, b, c, manifoldContacts, numContacts); if((numContacts - previousNumContacts) < 2) generateEE(p, q, sqInflatedRadius, normal, triangleIndex, a, c, manifoldContacts, numContacts); } void Gu::PCMCapsuleVsMeshContactGeneration::generateEEMTD( const Vec3VArg p, const Vec3VArg q, const FloatVArg inflatedRadius, const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg a, const Vec3VArg b, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { const FloatV zero = FZero(); const Vec3V ab = V3Sub(b, a); const Vec3V n = V3Cross(ab, normal); const FloatV d = V3Dot(n, a); const FloatV np = V3Dot(n, p); const FloatV nq = V3Dot(n,q); const FloatV signP = FSub(np, d); const FloatV signQ = FSub(nq, d); const FloatV temp = FMul(signP, signQ); if(FAllGrtr(temp, zero)) return;//If both points in the same side as the plane, no intersect points // if colliding edge (p3,p4) and plane are parallel return no collision const Vec3V pq = V3Sub(q, p); const FloatV npq= V3Dot(n, pq); if(FAllEq(npq, zero)) return; //calculate the intersect point in the segment pq const FloatV segTValue = FDiv(FSub(d, np), npq); const Vec3V localPointA = V3ScaleAdd(pq, segTValue, p); //calculate a normal perpendicular to ray localPointA + normal, 2D segment segment intersection const Vec3V perNormal = V3Cross(normal, pq); const Vec3V ap = V3Sub(localPointA, a); const FloatV nom = V3Dot(perNormal, ap); const FloatV denom = V3Dot(perNormal, ab); const FloatV tValue = FClamp(FDiv(nom, denom), zero, FOne()); const Vec3V v = V3NegScaleSub(ab, tValue, ap); const FloatV signedDist = V3Dot(v, normal); if(FAllGrtr(inflatedRadius, signedDist)) { const Vec3V localPointB = V3Sub(localPointA, v); manifoldContacts[numContacts].mLocalPointA = localPointA; manifoldContacts[numContacts].mLocalPointB = localPointB; manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), signedDist); manifoldContacts[numContacts++].mFaceIndex = triangleIndex; } } void Gu::PCMCapsuleVsMeshContactGeneration::generateEEContactsMTD( const Vec3VArg a, const Vec3VArg b, const Vec3VArg c, const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg p, const Vec3VArg q, const FloatVArg inflatedRadius, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { generateEEMTD(p, q, inflatedRadius, normal, triangleIndex, a, b, manifoldContacts, numContacts); generateEEMTD(p, q, inflatedRadius, normal, triangleIndex, b, c, manifoldContacts, numContacts); generateEEMTD(p, q, inflatedRadius, normal, triangleIndex, a, c, manifoldContacts, numContacts); } void Gu::PCMCapsuleVsMeshContactGeneration::generateContacts(const Vec3VArg a, const Vec3VArg b, const Vec3VArg c, const Vec3VArg planeNormal, const Vec3VArg normal, PxU32 triangleIndex, const Vec3VArg p, const Vec3VArg q, const FloatVArg inflatedRadius, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V ap = V3Sub(p, a); const Vec3V aq = V3Sub(q, a); //This is used to calculate the barycentric coordinate const FloatV d00 = V3Dot(ab, ab); const FloatV d01 = V3Dot(ab, ac); const FloatV d11 = V3Dot(ac, ac); const FloatV zero = FZero(); const FloatV largeValue = FLoad(1e+20f); const FloatV tDenom = FSub(FMul(d00, d11), FMul(d01, d01)); const FloatV bdenom = FSel(FIsGrtr(tDenom, zero), FRecip(tDenom), largeValue); //compute the intersect point of p and triangle plane abc const FloatV inomp = V3Dot(planeNormal, V3Neg(ap)); const FloatV ideom = V3Dot(planeNormal, normal); const FloatV ipt = FSel(FIsGrtr(ideom, zero), FNeg(FDiv(inomp, ideom)), largeValue); const Vec3V closestP31 = V3NegScaleSub(normal, ipt, p); const Vec3V closestP30 = p; //Compute the barycentric coordinate for project point of q const Vec3V pV20 = V3Sub(closestP31, a); const FloatV pD20 = V3Dot(pV20, ab); const FloatV pD21 = V3Dot(pV20, ac); const FloatV v0 = FMul(FSub(FMul(d11, pD20), FMul(d01, pD21)), bdenom); const FloatV w0 = FMul(FSub(FMul(d00, pD21), FMul(d01, pD20)), bdenom); //check closestP3 is inside the triangle const BoolV con0 = isValidTriangleBarycentricCoord(v0, w0); const BoolV tempCon0 = BAnd(con0, FIsGrtr(inflatedRadius, ipt)); if(BAllEqTTTT(tempCon0)) { manifoldContacts[numContacts].mLocalPointA = closestP30;//transform to B space, it will get convert to A space later manifoldContacts[numContacts].mLocalPointB = closestP31; manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), ipt); manifoldContacts[numContacts++].mFaceIndex = triangleIndex; } const FloatV inomq = V3Dot(planeNormal, V3Neg(aq)); const FloatV iqt = FSel(FIsGrtr(ideom, FZero()), FNeg(FDiv(inomq, ideom)), FLoad(1e+20f)); const Vec3V closestP41 = V3NegScaleSub(normal, iqt, q); const Vec3V closestP40 = q; //Compute the barycentric coordinate for project point of q const Vec3V qV20 = V3Sub(closestP41, a); const FloatV qD20 = V3Dot(qV20, ab); const FloatV qD21 = V3Dot(qV20, ac); const FloatV v1 = FMul(FSub(FMul(d11, qD20), FMul(d01, qD21)), bdenom); const FloatV w1 = FMul(FSub(FMul(d00, qD21), FMul(d01, qD20)), bdenom); const BoolV con1 = isValidTriangleBarycentricCoord(v1, w1); const BoolV tempCon1 = BAnd(con1, FIsGrtr(inflatedRadius, iqt)); if(BAllEqTTTT(tempCon1)) { manifoldContacts[numContacts].mLocalPointA = closestP40; manifoldContacts[numContacts].mLocalPointB = closestP41; manifoldContacts[numContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), iqt); manifoldContacts[numContacts++].mFaceIndex = triangleIndex; } } static PX_FORCE_INLINE Vec4V pcmDistanceSegmentSegmentSquared4(const Vec3VArg p, const Vec3VArg d0, const Vec3VArg p02, const Vec3VArg d02, const Vec3VArg p12, const Vec3VArg d12, const Vec3VArg p22, const Vec3VArg d22, const Vec3VArg p32, const Vec3VArg d32, Vec4V& s, Vec4V& t) { const Vec4V zero = V4Zero(); const Vec4V one = V4One(); const Vec4V eps = V4Eps(); const Vec4V half = V4Splat(FHalf()); const Vec4V d0X = V4Splat(V3GetX(d0)); const Vec4V d0Y = V4Splat(V3GetY(d0)); const Vec4V d0Z = V4Splat(V3GetZ(d0)); const Vec4V pX = V4Splat(V3GetX(p)); const Vec4V pY = V4Splat(V3GetY(p)); const Vec4V pZ = V4Splat(V3GetZ(p)); Vec4V d024 = Vec4V_From_Vec3V(d02); Vec4V d124 = Vec4V_From_Vec3V(d12); Vec4V d224 = Vec4V_From_Vec3V(d22); Vec4V d324 = Vec4V_From_Vec3V(d32); Vec4V p024 = Vec4V_From_Vec3V(p02); Vec4V p124 = Vec4V_From_Vec3V(p12); Vec4V p224 = Vec4V_From_Vec3V(p22); Vec4V p324 = Vec4V_From_Vec3V(p32); Vec4V d0123X, d0123Y, d0123Z; Vec4V p0123X, p0123Y, p0123Z; PX_TRANSPOSE_44_34(d024, d124, d224, d324, d0123X, d0123Y, d0123Z); PX_TRANSPOSE_44_34(p024, p124, p224, p324, p0123X, p0123Y, p0123Z); const Vec4V rX = V4Sub(pX, p0123X); const Vec4V rY = V4Sub(pY, p0123Y); const Vec4V rZ = V4Sub(pZ, p0123Z); //TODO - store this in a transposed state and avoid so many dot products? const FloatV dd = V3Dot(d0, d0); const Vec4V e = V4MulAdd(d0123Z, d0123Z, V4MulAdd(d0123X, d0123X, V4Mul(d0123Y, d0123Y))); const Vec4V b = V4MulAdd(d0Z, d0123Z, V4MulAdd(d0X, d0123X, V4Mul(d0Y, d0123Y))); const Vec4V c = V4MulAdd(d0Z, rZ, V4MulAdd(d0X, rX, V4Mul(d0Y, rY))); const Vec4V f = V4MulAdd(d0123Z, rZ, V4MulAdd(d0123X, rX, V4Mul(d0123Y, rY))); const Vec4V a(V4Splat(dd)); const Vec4V aRecip(V4Recip(a)); const Vec4V eRecip(V4Recip(e)); //if segments not parallell, compute closest point on two segments and clamp to segment1 const Vec4V denom = V4Sub(V4Mul(a, e), V4Mul(b, b)); const Vec4V temp = V4Sub(V4Mul(b, f), V4Mul(c, e)); //const Vec4V s0 = V4Clamp(V4Div(temp, denom), zero, one); //In PS3, 0(temp)/0(denom) will produce QNaN and V4Clamp can't clamp the value to zero and one. In PC, 0/0 will produce inf and V4Clamp clamp the value to be one. //Therefore, we need to add the select code to protect against this case const Vec4V value = V4Sel(V4IsEq(denom, zero), one, V4Div(temp, denom)); const Vec4V s0 = V4Clamp(value, zero, one); //test whether segments are parallel const BoolV con2 = V4IsGrtrOrEq(eps, denom); const Vec4V sTmp = V4Sel(con2, half, s0); //compute point on segment2 closest to segment1 //const Vec4V tTmp = V4Mul(V4Add(V4Mul(b, sTmp), f), eRecip); const Vec4V tTmp = V4Sel(V4IsEq(e, zero), one, V4Mul(V4Add(V4Mul(b, sTmp), f), eRecip)); //if t is in [zero, one], done. otherwise clamp t const Vec4V t2 = V4Clamp(tTmp, zero, one); //recompute s for the new value //const Vec4V comp = V4Mul(V4Sub(V4Mul(b,t2), c), aRecip); const Vec4V comp = V4Sel(V4IsEq(a, zero), one, V4Mul(V4Sub(V4Mul(b,t2), c), aRecip)); const Vec4V s2 = V4Clamp(comp, zero, one); s = s2; t = t2; const Vec4V closest1X = V4MulAdd(d0X, s2, pX); const Vec4V closest1Y = V4MulAdd(d0Y, s2, pY); const Vec4V closest1Z = V4MulAdd(d0Z, s2, pZ); const Vec4V closest2X = V4MulAdd(d0123X, t2, p0123X); const Vec4V closest2Y = V4MulAdd(d0123Y, t2, p0123Y); const Vec4V closest2Z = V4MulAdd(d0123Z, t2, p0123Z); const Vec4V vvX = V4Sub(closest1X, closest2X); const Vec4V vvY = V4Sub(closest1Y, closest2Y); const Vec4V vvZ = V4Sub(closest1Z, closest2Z); const Vec4V vd = V4MulAdd(vvX, vvX, V4MulAdd(vvY, vvY, V4Mul(vvZ, vvZ))); return vd; } // t is the barycenteric coordinate of a segment // u is the barycenteric coordinate of a triangle // v is the barycenteric coordinate of a triangle static FloatV pcmDistanceSegmentTriangleSquared(const Vec3VArg p, const Vec3VArg q, const Vec3VArg a, const Vec3VArg b, const Vec3VArg c, FloatV& t, FloatV& u, FloatV& v) { const FloatV one = FOne(); const FloatV zero = FZero(); const Vec3V pq = V3Sub(q, p); const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V bc = V3Sub(c, b); const Vec3V ap = V3Sub(p, a); const Vec3V aq = V3Sub(q, a); const Vec3V n = V3Normalize(V3Cross(ab, ac)); // normalize vector const Vec4V combinedDot = V3Dot4(ab, ab, ab, ac, ac, ac, ap, n); const FloatV d00 = V4GetX(combinedDot); const FloatV d01 = V4GetY(combinedDot); const FloatV d11 = V4GetZ(combinedDot); const FloatV dist3 = V4GetW(combinedDot); // PT: the new version is copied from Gu::distanceSegmentTriangleSquared const FloatV tDenom = FSub(FMul(d00, d11), FMul(d01, d01)); const FloatV bdenom = FSel(FIsGrtr(tDenom, zero), FRecip(tDenom), zero); const FloatV sqDist3 = FMul(dist3, dist3); //compute the closest point of q and triangle plane abc const FloatV dist4 = V3Dot(aq, n); const FloatV sqDist4 = FMul(dist4, dist4); const FloatV dMul = FMul(dist3, dist4); const BoolV con = FIsGrtr(zero, dMul); if(BAllEqTTTT(con)) { //compute the intersect point const FloatV nom = FNeg(V3Dot(n, ap)); const FloatV denom = FRecip(V3Dot(n, pq)); const FloatV t0 = FMul(nom, denom); const Vec3V ip = V3ScaleAdd(pq, t0, p);//V3Add(p, V3Scale(pq, t)); const Vec3V v2 = V3Sub(ip, a); const FloatV d20 = V3Dot(v2, ab); const FloatV d21 = V3Dot(v2, ac); const FloatV v0 = FMul(FNegScaleSub(d01, d21, FMul(d11, d20)), bdenom); const FloatV w0 = FMul(FNegScaleSub(d01, d20, FMul(d00, d21)), bdenom); const BoolV con0 = isValidTriangleBarycentricCoord(v0, w0); if(BAllEqTTTT(con0)) { t = t0; u = v0; v = w0; return zero; } } const Vec3V closestP31 = V3NegScaleSub(n, dist3, p);//V3Sub(p, V3Scale(n, dist3)); const Vec3V closestP41 = V3NegScaleSub(n, dist4, q);// V3Sub(q, V3Scale(n, dist4)); //Compute the barycentric coordinate for project point of q const Vec3V pV20 = V3Sub(closestP31, a); const Vec3V qV20 = V3Sub(closestP41, a); const Vec4V pD2 = V3Dot4(pV20, ab, pV20, ac, qV20, ab, qV20, ac); const Vec4V pD2Swizzle = V4PermYXWZ(pD2); const Vec4V d11d00 = V4UnpackXY(V4Splat(d11), V4Splat(d00)); const Vec4V v0w0v1w1 = V4Scale(V4NegMulSub(V4Splat(d01), pD2Swizzle, V4Mul(d11d00, pD2)), bdenom); const FloatV v0 = V4GetX(v0w0v1w1); const FloatV w0 = V4GetY(v0w0v1w1); const FloatV v1 = V4GetZ(v0w0v1w1); const FloatV w1 = V4GetW(v0w0v1w1); const BoolV _con = isValidTriangleBarycentricCoord2(v0w0v1w1); const BoolV con0 = BGetX(_con); const BoolV con1 = BGetY(_con); const BoolV cond2 = BAnd(con0, con1); if(BAllEqTTTT(cond2)) { // both p and q project points are interior point const BoolV d2 = FIsGrtr(sqDist4, sqDist3); t = FSel(d2, zero, one); u = FSel(d2, v0, v1); v = FSel(d2, w0, w1); return FSel(d2, sqDist3, sqDist4); } else { Vec4V t40, t41; const Vec4V sqDist44 = pcmDistanceSegmentSegmentSquared4(p,pq,a,ab, b,bc, a,ac, a,ab, t40, t41); const FloatV t00 = V4GetX(t40); const FloatV t10 = V4GetY(t40); const FloatV t20 = V4GetZ(t40); const FloatV t01 = V4GetX(t41); const FloatV t11 = V4GetY(t41); const FloatV t21 = V4GetZ(t41); //edge ab const FloatV u01 = t01; const FloatV v01 = zero; //edge bc const FloatV u11 = FSub(one, t11); const FloatV v11 = t11; //edge ac const FloatV u21 = zero; const FloatV v21 = t21; const FloatV sqDist0(V4GetX(sqDist44)); const FloatV sqDist1(V4GetY(sqDist44)); const FloatV sqDist2(V4GetZ(sqDist44)); const BoolV con2 = BAnd(FIsGrtr(sqDist1, sqDist0), FIsGrtr(sqDist2, sqDist0)); const BoolV con3 = FIsGrtr(sqDist2, sqDist1); const FloatV sqDistPE = FSel(con2, sqDist0, FSel(con3, sqDist1, sqDist2)); const FloatV uEdge = FSel(con2, u01, FSel(con3, u11, u21)); const FloatV vEdge = FSel(con2, v01, FSel(con3, v11, v21)); const FloatV tSeg = FSel(con2, t00, FSel(con3, t10, t20)); if(BAllEqTTTT(con0)) { //p's project point is an interior point const BoolV d2 = FIsGrtr(sqDistPE, sqDist3); t = FSel(d2, zero, tSeg); u = FSel(d2, v0, uEdge); v = FSel(d2, w0, vEdge); return FSel(d2, sqDist3, sqDistPE); } else if(BAllEqTTTT(con1)) { //q's project point is an interior point const BoolV d2 = FIsGrtr(sqDistPE, sqDist4); t = FSel(d2, one, tSeg); u = FSel(d2, v1, uEdge); v = FSel(d2, w1, vEdge); return FSel(d2, sqDist4, sqDistPE); } else { t = tSeg; u = uEdge; v = vEdge; return sqDistPE; } } } static bool selectNormal(const FloatVArg u, FloatVArg v, PxU8 data) { const FloatV zero = FLoad(1e-6f); const FloatV one = FLoad(0.999999f); // Analysis if(FAllGrtr(zero, u)) { if(FAllGrtr(zero, v)) { // Vertex 0 if(!(data & (ETD_CONVEX_EDGE_01|ETD_CONVEX_EDGE_20))) return true; } else if(FAllGrtr(v, one)) { // Vertex 2 if(!(data & (ETD_CONVEX_EDGE_12|ETD_CONVEX_EDGE_20))) return true; } else { // Edge 0-2 if(!(data & ETD_CONVEX_EDGE_20)) return true; } } else if(FAllGrtr(u,one)) { if(FAllGrtr(zero, v)) { // Vertex 1 if(!(data & (ETD_CONVEX_EDGE_01|ETD_CONVEX_EDGE_12))) return true; } } else { if(FAllGrtr(zero, v)) { // Edge 0-1 if(!(data & ETD_CONVEX_EDGE_01)) return true; } else { const FloatV threshold = FLoad(0.9999f); const FloatV temp = FAdd(u, v); if(FAllGrtrOrEq(temp, threshold)) { // Edge 1-2 if(!(data & ETD_CONVEX_EDGE_12)) return true; } else { // Face return true; } } } return false; } bool Gu::PCMCapsuleVsMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds) { PX_UNUSED(vertInds); const FloatV zero = FZero(); const Vec3V p0 = V3LoadU(verts[0]); const Vec3V p1 = V3LoadU(verts[1]); const Vec3V p2 = V3LoadU(verts[2]); const Vec3V p10 = V3Sub(p1, p0); const Vec3V p20 = V3Sub(p2, p0); const Vec3V n = V3Normalize(V3Cross(p10, p20));//(p1 - p0).cross(p2 - p0).getNormalized(); const FloatV d = V3Dot(p0, n);//d = -p0.dot(n); const FloatV dist = FSub(V3Dot(mCapsule.getCenter(), n), d);//p.dot(n) + d; // Backface culling if(FAllGrtr(zero, dist)) return false; FloatV t, u, v; const FloatV sqDist = pcmDistanceSegmentTriangleSquared(mCapsule.p0, mCapsule.p1, p0, p1, p2, t, u, v); if(FAllGrtr(mSqInflatedRadius, sqDist)) { Vec3V patchNormalInTriangle; if(selectNormal(u, v, triFlags)) { patchNormalInTriangle = n; } else { if(FAllEq(sqDist, zero)) { //segment intersect with the triangle patchNormalInTriangle = n; } else { const Vec3V pq = V3Sub(mCapsule.p1, mCapsule.p0); const Vec3V pointOnSegment = V3ScaleAdd(pq, t, mCapsule.p0); const FloatV w = FSub(FOne(), FAdd(u, v)); const Vec3V pointOnTriangle = V3ScaleAdd(p0, w, V3ScaleAdd(p1, u, V3Scale(p2, v))); patchNormalInTriangle = V3Normalize(V3Sub(pointOnSegment, pointOnTriangle)); } } const PxU32 previousNumContacts = mNumContacts; generateContacts(p0, p1, p2, n, patchNormalInTriangle, triangleIndex, mCapsule.p0, mCapsule.p1, mInflatedRadius, mManifoldContacts, mNumContacts); //ML: this need to use the sqInflatedRadius to avoid some bad contacts generateEEContacts(p0, p1, p2, patchNormalInTriangle, triangleIndex, mCapsule.p0, mCapsule.p1, mSqInflatedRadius, previousNumContacts, mManifoldContacts, mNumContacts); PxU32 numContacts = mNumContacts - previousNumContacts; PX_ASSERT(numContacts <= 2); if(numContacts > 0) { FloatV maxPen = FMax(); for(PxU32 i = previousNumContacts; i<mNumContacts; ++i) { const FloatV pen = V4GetW(mManifoldContacts[i].mLocalNormalPen); mManifoldContacts[i].mLocalPointA = mMeshToConvex.transform(mManifoldContacts[i].mLocalPointA); maxPen = FMin(maxPen, pen); } for(PxU32 i = previousNumContacts; i<mNumContacts; ++i) { Vec3V contact0 = mManifoldContacts[i].mLocalPointB; for(PxU32 j=i+1; j<mNumContacts; ++j) { Vec3V contact1 = mManifoldContacts[j].mLocalPointB; Vec3V dif = V3Sub(contact1, contact0); FloatV d1 = V3Dot(dif, dif); if(FAllGrtr(mSqReplaceBreakingThreshold, d1)) { mManifoldContacts[j] = mManifoldContacts[mNumContacts-1]; mNumContacts--; j--; } } } PX_ASSERT(mNumContactPatch <PCM_MAX_CONTACTPATCH_SIZE); addManifoldPointToPatch(patchNormalInTriangle, maxPen, previousNumContacts); PX_ASSERT(mNumContactPatch <PCM_MAX_CONTACTPATCH_SIZE); if(mNumContacts >= 16) { PX_ASSERT(mNumContacts <= 64); processContacts(GU_CAPSULE_MANIFOLD_CACHE_SIZE); } } } return true; } bool Gu::PCMCapsuleVsMeshContactGeneration::processTriangle(const TriangleV& triangleV, PxU32 triangleIndex, const CapsuleV& capsule, const FloatVArg inflatedRadius, const PxU8 trigFlag, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { const FloatV zero = FZero(); const Vec3V p0 = triangleV.verts[0]; const Vec3V p1 = triangleV.verts[1]; const Vec3V p2 = triangleV.verts[2]; const Vec3V n = triangleV.normal(); const FloatV sqInflatedRadius = FMul(inflatedRadius, inflatedRadius); FloatV t, u, v; const FloatV sqDist = pcmDistanceSegmentTriangleSquared(capsule.p0, capsule.p1, p0, p1, p2, t, u, v); if(FAllGrtr(sqInflatedRadius, sqDist)) { Vec3V patchNormalInTriangle; if(selectNormal(u, v, trigFlag)) { patchNormalInTriangle = n; } else { if(FAllEq(sqDist, zero)) { //segment intersect with the triangle patchNormalInTriangle = n; } else { const Vec3V pq = V3Sub(capsule.p1, capsule.p0); const Vec3V pointOnSegment = V3ScaleAdd(pq, t, capsule.p0); const FloatV w = FSub(FOne(), FAdd(u, v)); const Vec3V pointOnTriangle = V3ScaleAdd(p0, w, V3ScaleAdd(p1, u, V3Scale(p2, v))); patchNormalInTriangle = V3Normalize(V3Sub(pointOnSegment, pointOnTriangle)); } } generateContacts(p0, p1, p2, n, patchNormalInTriangle, triangleIndex, capsule.p0, capsule.p1, inflatedRadius, manifoldContacts, numContacts); generateEEContactsMTD(p0, p1, p2, patchNormalInTriangle, triangleIndex, capsule.p0, capsule.p1, inflatedRadius, manifoldContacts, numContacts); } return true; } // PT: below is just for internal testing PX_PHYSX_COMMON_API FloatV pcmDistanceSegmentTriangleSquaredExported( const Vec3VArg p, const Vec3VArg q, const Vec3VArg a, const Vec3VArg b, const Vec3VArg c, FloatV& t, FloatV& u, FloatV& v) { return pcmDistanceSegmentTriangleSquared(p, q, a, b, c, t, u, v); }
30,025
C++
34.241784
186
0.718768
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleConvex.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 "geomutils/PxContactBuffer.h" #include "GuGJKPenetration.h" #include "GuEPA.h" #include "GuVecCapsule.h" #include "GuVecConvexHull.h" #include "GuVecConvexHullNoScale.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" using namespace physx; using namespace Gu; using namespace aos; static bool fullContactsGenerationCapsuleConvex(const CapsuleV& capsule, const ConvexHullV& convexHull, const PxMatTransformV& aToB, const PxTransformV& transf0,const PxTransformV& transf1, PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer, bool idtScale, PersistentContactManifold& manifold, Vec3VArg normal, const Vec3VArg closest, PxReal tolerance, const FloatVArg contactDist, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength) { PX_UNUSED(renderOutput); PolygonalData polyData; getPCMConvexData(convexHull,idtScale, polyData); PX_ALIGN(16, PxU8 buff[sizeof(SupportLocalImpl<ConvexHullV>)]); SupportLocal* map = (idtScale ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull), transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)) : static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullV>)(convexHull, transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale))); PxU32 numContacts = 0; if(!generateFullContactManifold(capsule, polyData, map, aToB, manifoldContacts, numContacts, contactDist, normal, closest, tolerance, doOverlapTest, toleranceLength)) return false; if (numContacts > 0) { manifold.addBatchManifoldContacts2(manifoldContacts, numContacts); //transform normal into the world space normal = transf1.rotate(normal); manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsule.radius, contactDist); } else { if (!doOverlapTest) { normal = transf1.rotate(normal); manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsule.radius, contactDist); } } #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } bool Gu::pcmContactCapsuleConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_ASSERT(transform1.q.isSane()); PX_ASSERT(transform0.q.isSane()); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); PersistentContactManifold& manifold = cache.getManifold(); const ConvexHullData* hullData = _getHullData(shapeConvex); PxPrefetchLine(hullData); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const FloatV contactDist = FLoad(params.mContactDistance); const FloatV capsuleHalfHeight = FLoad(shapeCapsule.halfHeight); const FloatV capsuleRadius = FLoad(shapeCapsule.radius); //Transfer A into the local space of B const PxTransformV transf0 = loadTransformA(transform0); const PxTransformV transf1 = loadTransformA(transform1); const PxTransformV curRTrans(transf1.transformInv(transf0)); const PxMatTransformV aToB(curRTrans); const PxReal toleranceLength = params.mToleranceLength; const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength); const FloatV capsuleMinMargin = CalculateCapsuleMinMargin(capsuleRadius); const FloatV minMargin = FMin(convexMargin, capsuleMinMargin); const PxU32 initialContacts = manifold.mNumContacts; const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(1.25f)); const FloatV refreshDist = FAdd(contactDist, capsuleRadius); manifold.refreshContactPoints(aToB, projectBreakingThreshold, refreshDist); //ML: after refreshContactPoints, we might lose some contacts const bool bLostContacts = (manifold.mNumContacts != initialContacts); GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT; if(bLostContacts || manifold.invalidate_SphereCapsule(curRTrans, minMargin)) { const bool idtScale = shapeConvex.scale.isIdentity(); manifold.setRelativeTransform(curRTrans); const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const ConvexHullV convexHull(hullData, V3LoadU(hullData->mCenterOfMass), vScale, vQuat, idtScale); //transform capsule(a) into the local space of convexHull(b) const CapsuleV capsule(aToB.p, aToB.rotate(V3Scale(V3UnitX(), capsuleHalfHeight)), capsuleRadius); GjkOutput output; const LocalConvex<CapsuleV> convexA(capsule); const Vec3V initialSearchDir = V3Sub(capsule.getCenter(), convexHull.getCenter()); if(idtScale) { const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull)); status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullNoScaleV> >(convexA, convexB, initialSearchDir, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); } else { const LocalConvex<ConvexHullV> convexB(convexHull); status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullV> >(convexA, convexB, initialSearchDir, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); } PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); bool doOverlapTest = false; if(status == GJK_NON_INTERSECT) { return false; } else if(status == GJK_DEGENERATE) { return fullContactsGenerationCapsuleConvex(capsule, convexHull, aToB, transf0, transf1, manifoldContacts, contactBuffer, idtScale, manifold, output.normal, output.closestB, convexHull.getMarginF(), contactDist, true, renderOutput, toleranceLength); } else { const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f)); if(status == GJK_CONTACT) { const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); //Add contact to contact stream manifoldContacts[0].mLocalPointA = localPointA; manifoldContacts[0].mLocalPointB = output.closestB; manifoldContacts[0].mLocalNormalPen = localNormalPen; //Add contact to manifold manifold.addManifoldPoint2(localPointA, output.closestB, localNormalPen, replaceBreakingThreshold); } else { PX_ASSERT(status == EPA_CONTACT); if(idtScale) { const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull)); status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, FLoad(toleranceLength), output); } else { const LocalConvex<ConvexHullV> convexB(convexHull); status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, FLoad(toleranceLength), output); } if(status == EPA_CONTACT) { const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); //Add contact to contact stream manifoldContacts[0].mLocalPointA = localPointA; manifoldContacts[0].mLocalPointB = output.closestB; manifoldContacts[0].mLocalNormalPen = localNormalPen; //Add contact to manifold manifold.addManifoldPoint2(localPointA, output.closestB, localNormalPen, replaceBreakingThreshold); } else { doOverlapTest = true; } } if(initialContacts == 0 || bLostContacts || doOverlapTest) { return fullContactsGenerationCapsuleConvex(capsule, convexHull, aToB, transf0, transf1, manifoldContacts, contactBuffer, idtScale, manifold, output.normal, output.closestB, convexHull.getMarginF(), contactDist, doOverlapTest, renderOutput, toleranceLength); } else { //This contact is either come from GJK or EPA const Vec3V normal = transf1.rotate(output.normal); manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsuleRadius, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } } } else if (manifold.getNumContacts() > 0) { const Vec3V normal = manifold.getWorldNormal(transf1); manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsuleRadius, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } return false; }
10,406
C++
42.3625
245
0.769652
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereBox.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 "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuVecSphere.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGenUtil.h" using namespace physx; bool Gu::pcmContactSphereBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); using namespace aos; // Get actual shape data const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); //const PsTransformV transf0(transform0); const Vec3V sphereOrigin = V3LoadA(&transform0.p.x); //const PsTransformV transf1(transform1); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV radius = FLoad(shapeSphere.radius); const PxTransformV transf1(p1, q1); const FloatV cDist = FLoad(params.mContactDistance); const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); //translate sphere center into the box space const Vec3V sphereCenter = transf1.transformInv(sphereOrigin); const Vec3V nBoxExtents = V3Neg(boxExtents); //const FloatV radSq = FMul(radius, radius); const FloatV inflatedSum = FAdd(radius, cDist); const FloatV sqInflatedSum = FMul(inflatedSum, inflatedSum); const Vec3V p = V3Clamp(sphereCenter, nBoxExtents, boxExtents); const Vec3V v = V3Sub(sphereCenter, p); const FloatV lengthSq = V3Dot(v, v); PX_ASSERT(contactBuffer.count < PxContactBuffer::MAX_CONTACTS); if(FAllGrtr(sqInflatedSum, lengthSq))//intersect { //check whether the spherCenter is inside the box const BoolV bInsideBox = V3IsGrtrOrEq(boxExtents, V3Abs(sphereCenter)); // PT: TODO: ??? revisit this, why do we have both BAllEqTTTT and BAllTrue3? if(BAllEqTTTT(BAllTrue3(bInsideBox)))//sphere center inside the box { //Pick directions and sign const Vec3V absP = V3Abs(p); const Vec3V distToSurface = V3Sub(boxExtents, absP);//dist from embedded center to box surface along 3 dimensions. const FloatV x = V3GetX(distToSurface); const FloatV y = V3GetY(distToSurface); const FloatV z = V3GetZ(distToSurface); const Vec3V xV = V3Splat(x); const Vec3V zV = V3Splat(z); //find smallest element of distToSurface const BoolV con0 = BAllTrue3(V3IsGrtrOrEq(distToSurface, zV)); const BoolV con1 = BAllTrue3(V3IsGrtrOrEq(distToSurface, xV)); const Vec3V sign = V3Sign(p); const Vec3V tmpX = V3Mul(V3UnitX(), sign); const Vec3V tmpY = V3Mul(V3UnitY(), sign); const Vec3V tmpZ = V3Mul(V3UnitZ(), sign); const Vec3V locNorm = V3Sel(con0, tmpZ, V3Sel(con1, tmpX, tmpY));////local coords contact normal const FloatV dist = FNeg(FSel(con0, z, FSel(con1, x, y))); //separation so far is just the embedding of the center point; we still have to push out all of the radius. const Vec3V normal = transf1.rotate(locNorm); const FloatV penetration = FSub(dist, radius); const Vec3V point = V3Sub(sphereOrigin , V3Scale(normal, dist)); outputSimplePCMContact(contactBuffer, point, normal, penetration); } else { //get the closest point from the center to the box surface const FloatV recipLength = FRsqrt(lengthSq); const FloatV length = FRecip(recipLength); const Vec3V locNorm = V3Scale(v, recipLength); const FloatV penetration = FSub(length, radius); const Vec3V normal = transf1.rotate(locNorm); const Vec3V point = transf1.transform(p); outputSimplePCMContact(contactBuffer, point, normal, penetration); } return true; } return false; }
5,191
C++
38.333333
117
0.746484
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPersistentContactManifold.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef Gu_PERSISTENTCONTACTMANIFOLD_H #define Gu_PERSISTENTCONTACTMANIFOLD_H #include "common/PxPhysXCommonConfig.h" #include "foundation/PxUnionCast.h" #include "foundation/PxMemory.h" #include "foundation/PxVecTransform.h" #define PCM_LOW_LEVEL_DEBUG 0 namespace physx { #define VISUALIZE_PERSISTENT_CONTACT 1 //This is for primitives vs primitives #define GU_MANIFOLD_CACHE_SIZE 4 //These are for primitives vs mesh #define GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE 5 #define GU_SINGLE_MANIFOLD_CACHE_SIZE 6 #define GU_SPHERE_MANIFOLD_CACHE_SIZE 1 #define GU_CAPSULE_MANIFOLD_CACHE_SIZE 3 #define GU_MAX_MANIFOLD_SIZE 6 // PT: max nb of manifolds (e.g. for multi-manifolds), NOT the max size of a single manifold #define GU_MESH_CONTACT_REDUCTION_THRESHOLD 16 #define GU_MANIFOLD_INVALID_INDEX 0xffffffff //ML: this is used to compared with the shape's margin to decide the final tolerance used in the manifold to validate the existing contacts. //In the case of big shape and relatively speaking small triangles in the mesh, we need to take a smaller margin. This helps because the PCM //recycling thresholds are proportionate to margin so it makes it less likely to discard previous contacts due to separation #define GU_PCM_MESH_MANIFOLD_EPSILON 0.05f class PxRenderOutput; class PxContactBuffer; namespace Gu { struct GjkOutput; extern const PxF32 invalidateThresholds[5]; extern const PxF32 invalidateQuatThresholds[5]; extern const PxF32 invalidateThresholds2[3]; extern const PxF32 invalidateQuatThresholds2[3]; aos::Mat33V findRotationMatrixFromZAxis(const aos::Vec3VArg to); //This contact is used in the primitives vs primitives contact gen class PersistentContact { public: PersistentContact() { } PersistentContact(aos::Vec3V _localPointA, aos::Vec3V _localPointB, aos::Vec4V _localNormalPen) : mLocalPointA(_localPointA), mLocalPointB(_localPointB), mLocalNormalPen(_localNormalPen) { } aos::Vec3V mLocalPointA; aos::Vec3V mLocalPointB; aos::Vec4V mLocalNormalPen; // the (x, y, z) is the local normal, and the w is the penetration depth }; //This contact is used in the mesh contact gen to store an extra variable class MeshPersistentContact : public PersistentContact { public: PxU32 mFaceIndex; }; //This contact is used in the compress stream buffer(NpCacheStreamPair in the PxcNpThreadContext) to store the data we need PX_ALIGN_PREFIX(16) class CachedMeshPersistentContact { public: PxVec3 mLocalPointA; //16 byte aligned PxU32 mFaceIndex; //face index PxVec3 mLocalPointB; //16 byte aligned PxU32 mPad; //pad PxVec3 mLocalNormal; //16 byte aligned PxReal mPen; //penetration }PX_ALIGN_SUFFIX(16); #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 //This class is used to store the start and end index of the mesh persistent contacts in an array. struct PCMContactPatch { public: PCMContactPatch() { mNextPatch = NULL; mEndPatch = NULL; mRoot = this; mPatchMaxPen = aos::FMax(); } aos::Vec3V mPatchNormal; PCMContactPatch* mNextPatch;//store the next patch pointer in the patch list PCMContactPatch* mEndPatch;//store the last patch pointer in the patch list PCMContactPatch* mRoot;//if this is the start of the patch list which has very similar patch normal, the root will be itself aos::FloatV mPatchMaxPen;//store the deepest penetration of the whole patch PxU32 mStartIndex;//store the start index of the manifold contacts in the manifold contacts stream PxU32 mEndIndex;//store the end index of the manifold contacts in the manifold contacts stream PxU32 mTotalSize;//if this is the root, the total size will store the total number of manifold contacts in the whole patch list }; #if PX_VC #pragma warning(pop) #endif //ML: this is needed because it seems NEON doesn't force the alignment on SIMD type, which cause some of the PCM unit tests fail PX_ALIGN_PREFIX(16) class PersistentContactManifold { public: PersistentContactManifold(PersistentContact* contactPointsBuff, PxU8 capacity): mNumContacts(0), mCapacity(capacity), mNumWarmStartPoints(0), mContactPoints(contactPointsBuff) { using namespace physx::aos; mRelativeTransform.invalidate(); mQuatA = QuatIdentity(); mQuatB = QuatIdentity(); } PX_FORCE_INLINE PxU32 getNumContacts() const { return mNumContacts;} PX_FORCE_INLINE bool isEmpty() const { return mNumContacts==0; } PX_FORCE_INLINE PersistentContact& getContactPoint(const PxU32 index) { PX_ASSERT(index < GU_MANIFOLD_CACHE_SIZE); return mContactPoints[index]; } PX_FORCE_INLINE aos::FloatV maxTransformdelta(const aos::PxTransformV& curTransform) const { using namespace aos; const Vec4V p0 = Vec4V_From_Vec3V(mRelativeTransform.p); const Vec4V q0 = mRelativeTransform.q; const Vec4V p1 = Vec4V_From_Vec3V(curTransform.p); const Vec4V q1 = curTransform.q; const Vec4V dp = V4Abs(V4Sub(p1, p0)); const Vec4V dq = V4Abs(V4Sub(q1, q0)); const Vec4V max0 = V4Max(dp, dq); //need to work out max from a single vector... return V4ExtractMax(max0); } PX_FORCE_INLINE aos::Vec4V maxTransformdelta2(const aos::PxTransformV& curTransform) const { using namespace aos; const Vec4V p0 = Vec4V_From_Vec3V(mRelativeTransform.p); const Vec4V q0 = mRelativeTransform.q; const Vec4V p1 = Vec4V_From_Vec3V(curTransform.p); const Vec4V q1 = curTransform.q; const Vec4V dp = V4Abs(V4Sub(p1, p0)); const Vec4V dq = V4Abs(V4Sub(q1, q0)); const Vec4V max0 = V4Max(dp, dq); //need to work out max from a single vector... return max0; } PX_FORCE_INLINE aos::FloatV maxTransformPositionDelta(const aos::Vec3V& curP) const { using namespace aos; const Vec3V deltaP = V3Sub(curP, mRelativeTransform.p); const Vec4V delta = Vec4V_From_Vec3V(V3Abs(deltaP)); //need to work out max from a single vector... return V4ExtractMax(delta); } PX_FORCE_INLINE aos::FloatV maxTransformQuatDelta(const aos::QuatV& curQ) const { using namespace aos; const Vec4V deltaQ = V4Sub(curQ, mRelativeTransform.q); const Vec4V delta = V4Abs(deltaQ); //need to work out max from a single vector... return V4ExtractMax(delta); } PX_FORCE_INLINE void setRelativeTransform(const aos::PxTransformV& transform) { mRelativeTransform = transform; } PX_FORCE_INLINE void setRelativeTransform(const aos::PxTransformV& transform, const aos::QuatV quatA, const aos::QuatV quatB) { mRelativeTransform = transform; mQuatA = quatA; mQuatB = quatB; } //This is used for the box/convexhull vs box/convexhull contact gen to decide whether the relative movement of a pair of objects are //small enough. In this case, we can skip the collision detection all together PX_FORCE_INLINE PxU32 invalidate_BoxConvex(const aos::PxTransformV& curRTrans, const aos::QuatV& quatA, const aos::QuatV& quatB, const aos::FloatVArg minMargin, const aos::FloatVArg radiusA, const aos::FloatVArg radiusB) const { using namespace aos; PX_ASSERT(mNumContacts <= GU_MANIFOLD_CACHE_SIZE); const FloatV ratio = FLoad(invalidateThresholds[mNumContacts]); const FloatV thresholdP = FMul(minMargin, ratio); const FloatV deltaP = maxTransformPositionDelta(curRTrans.p); const FloatV thresholdQ = FLoad(invalidateQuatThresholds[mNumContacts]); const FloatV deltaQA = QuatDot(quatA, mQuatA); const FloatV deltaQB = QuatDot(quatB, mQuatB); const BoolV con0 = BOr(FIsGrtr(deltaP, thresholdP), BOr(FIsGrtr(thresholdQ, deltaQA), FIsGrtr(thresholdQ, deltaQB))); PxU32 generateContacts = BAllEqTTTT(con0); if (!generateContacts) { PxReal dqA, dqB; FStore(deltaQA, &dqA); FStore(deltaQB, &dqB); const PxReal aRadian = dqA < 1.0f ? PxAcos(dqA) : 0.f; const FloatV travelDistA = FMul(FLoad(aRadian), radiusA); const PxReal bRadian = dqB < 1.0f ? PxAcos(dqB) : 0.f; const FloatV travelDistB = FMul(FLoad(bRadian), radiusB); const BoolV con = BOr(FIsGrtr(travelDistA, thresholdP), FIsGrtr(travelDistB, thresholdP)); generateContacts = BAllEqTTTT(con); } return generateContacts; } //This is used for the sphere/capsule vs other primitives contact gen to decide whether the relative movement of a pair of objects are //small enough. In this case, we can skip the collision detection all together PX_FORCE_INLINE PxU32 invalidate_SphereCapsule(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin) const { using namespace aos; PX_ASSERT(mNumContacts <= 2); const FloatV ratio = FLoad(invalidateThresholds2[mNumContacts]); const FloatV thresholdP = FMul(minMargin, ratio); const FloatV deltaP = maxTransformPositionDelta(curRTrans.p); const FloatV thresholdQ = FLoad(invalidateQuatThresholds2[mNumContacts]); const FloatV deltaQ = QuatDot(curRTrans.q, mRelativeTransform.q); const BoolV con = BOr(FIsGrtr(deltaP, thresholdP), FIsGrtr(thresholdQ, deltaQ)); return BAllEqTTTT(con); } //This is used for plane contact gen to decide whether the relative movement of a pair of objects are small enough. In this case, //we can skip the collision detection all together PX_FORCE_INLINE PxU32 invalidate_PrimitivesPlane(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin, const aos::FloatVArg ratio) const { using namespace aos; const FloatV thresholdP = FMul(minMargin, ratio); const FloatV deltaP = maxTransformPositionDelta(curRTrans.p); const FloatV thresholdQ = FLoad(0.99996f);//about 0.5 degree const FloatV deltaQ = QuatDot(curRTrans.q, mRelativeTransform.q); const BoolV con = BOr(FIsGrtr(deltaP, thresholdP), FIsGrtr(thresholdQ, deltaQ)); return BAllEqTTTT(con); } PX_FORCE_INLINE void removeContactPoint(PxU32 index) { mNumContacts--; mContactPoints[index] = mContactPoints[mNumContacts]; } /*bool validContactDistance(const PersistentContact& pt, const aos::FloatVArg breakingThreshold) const { using namespace aos; const FloatV dist = V4GetW(pt.mLocalNormalPen); return FAllGrtr(breakingThreshold, dist) != 0; }*/ PX_FORCE_INLINE void clearManifold() { mNumWarmStartPoints = 0; mNumContacts = 0; mRelativeTransform.invalidate(); } PX_FORCE_INLINE void initialize() { clearManifold(); } //This function is used to replace the existing contact with the newly created contact if their distance are within some threshold bool replaceManifoldPoint(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalPen, const aos::FloatVArg replaceBreakingThreshold); //This function is to add a point(in box/convexhull contact gen) to the exising manifold. If the number of manifold is more than 4, we need to do contact reduction PxU32 addManifoldPoint(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalAPen, const aos::FloatVArg replaceBreakingThreshold); //This function is to add a point(in capsule contact gen) to the exising manifold. If the number of manifold is more than 4, we need to do contact reduction PxU32 addManifoldPoint2(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalAPen, const aos::FloatVArg replaceBreakingThreshold);//max two points of contacts //This function is used in box-plane contact gen to add the plane contacts to the manifold void addBatchManifoldContactsCluster(const PersistentContact* manifoldPoints, PxU32 numPoints); //This function is used in the capsule full manifold contact genenation(maximum 2 points). void addBatchManifoldContacts2(const PersistentContact* manifoldPoints, PxU32 numPoints);//max two points of contacts //This function is used in the box/convexhull full manifold contact generation(maximum 4 points). void addBatchManifoldContacts(const PersistentContact* manifoldPoints, PxU32 numPoints, PxReal toleranceLength); //This function is using the cluster algorithm to reduce contacts void reduceBatchContactsCluster(const PersistentContact* manifoldPoints, PxU32 numPoints); //This function is called by addBatchManifoldContacts2 to reduce the manifold contacts to 2 points; void reduceBatchContacts2(const PersistentContact* manifoldPoints, PxU32 numPoints); //This function is called by addBatchManifoldContacts to reduce the manifold contacts to 4 points void reduceBatchContacts(const PersistentContact* manifoldPoints, PxU32 numPoints, PxReal toleranceLength); //This function is used for incremental manifold contact reduction for box/convexhull PxU32 reduceContactsForPCM(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalPen); //This function is used for incremental manifold contact reduction for capsule PxU32 reduceContactSegment(const aos::Vec3VArg localPointA, const aos::Vec3VArg localPointB, const aos::Vec4VArg localNormalPen); // This function recalculate the contacts in the manifold based on the current relative transform between a pair of objects. If the recalculated contacts are within some threshold, // we will keep the contacts; Otherwise, we will remove the contacts. void refreshContactPoints(const aos::PxMatTransformV& relTra, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg contactOffset); //This function is just used in boxbox contact gen for fast transform void addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::Vec3VArg normal, const aos::PxMatTransformV& transf1); //This function is for adding box/convexhull manifold contacts to the contact buffer void addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::Vec3VArg normal, const aos::PxTransformV& transf1, const aos::FloatVArg contactOffset); //This function is for adding sphere/capsule manifold contacts to the contact buffer void addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::Vec3VArg normal, const aos::Vec3VArg projectionNormal, const aos::PxTransformV& transf0, const aos::FloatVArg radius, const aos::FloatVArg contactOffset); //get the average normal in the manifold in world space aos::Vec3V getWorldNormal(const aos::PxTransformV& trB) const; //get the average normal in the manifold in local B object space aos::Vec3V getLocalNormal() const; void recordWarmStart(PxU8* aIndices, PxU8* bIndices, PxU8& nbWarmStartPoints); void setWarmStart(const PxU8* aIndices, const PxU8* bIndices, const PxU8 nbWarmStartPoints); void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const; void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB, const aos::FloatVArg radius) const; void drawManifold(const PersistentContact& m, PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const; static void drawPoint(PxRenderOutput& out, const aos::Vec3VArg p, const PxF32 size, PxU32 color = 0x0000ff00); static void drawLine(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, PxU32 color = 0xff00ffff); static void drawTriangle(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2, PxU32 color = 0xffff0000); static void drawTetrahedron(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3, PxU32 color = 0xffff0000); static void drawPolygon(PxRenderOutput& out, const aos::PxTransformV& transform, const aos::Vec3V* points, PxU32 numVerts, PxU32 color = 0xff00ffff); static void drawPolygon(PxRenderOutput& out, const aos::PxMatTransformV& transform, const aos::Vec3V* points, PxU32 numVerts, PxU32 color = 0xff00ffff); aos::PxTransformV mRelativeTransform;//aToB aos::QuatV mQuatA; aos::QuatV mQuatB; PxU8 mNumContacts; PxU8 mCapacity; PxU8 mNumWarmStartPoints; PxU8 mAIndice[4]; PxU8 mBIndice[4]; PersistentContact* mContactPoints; } PX_ALIGN_SUFFIX(16); PX_ALIGN_PREFIX(16) class LargePersistentContactManifold : public PersistentContactManifold { public: LargePersistentContactManifold() : PersistentContactManifold(mContactPointsBuff, GU_MANIFOLD_CACHE_SIZE) { } PersistentContact mContactPointsBuff[GU_MANIFOLD_CACHE_SIZE]; }PX_ALIGN_SUFFIX(16); PX_ALIGN_PREFIX(16) class SpherePersistentContactManifold : public PersistentContactManifold { public: SpherePersistentContactManifold() : PersistentContactManifold(mContactPointsBuff, GU_SPHERE_MANIFOLD_CACHE_SIZE) { } PersistentContact mContactPointsBuff[GU_SPHERE_MANIFOLD_CACHE_SIZE]; }PX_ALIGN_SUFFIX(16); PX_ALIGN_PREFIX(16) class SinglePersistentContactManifold { public: SinglePersistentContactManifold(): mNumContacts(0) { } PX_FORCE_INLINE PxU32 getNumContacts() const { return mNumContacts;} PX_FORCE_INLINE bool isEmpty() const { return mNumContacts==0; } PX_FORCE_INLINE MeshPersistentContact& getContactPoint(const PxU32 index) { PX_ASSERT(index < GU_SINGLE_MANIFOLD_CACHE_SIZE); return mContactPoints[index]; } PX_FORCE_INLINE void removeContactPoint (PxU32 index) { mNumContacts--; mContactPoints[index] = mContactPoints[mNumContacts]; } PX_FORCE_INLINE void clearManifold() { mNumContacts = 0; } PX_FORCE_INLINE void initialize() { clearManifold(); } PX_FORCE_INLINE aos::Vec3V getWorldNormal(const aos::PxTransformV& trB) const { using namespace aos; Vec4V nPen = mContactPoints[0].mLocalNormalPen; for(PxU32 i=1; i<mNumContacts; ++i) { nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen); } const Vec3V n = Vec3V_From_Vec4V(nPen); return V3Normalize(trB.rotate(n)); } PX_FORCE_INLINE aos::Vec3V getLocalNormal() const { using namespace aos; Vec4V nPen = mContactPoints[0].mLocalNormalPen; for(PxU32 i=1; i<mNumContacts; ++i) { nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen); } return V3Normalize(Vec3V_From_Vec4V(nPen)); } //This function reduces the manifold contact list in a patch for box/convexhull vs mesh aos::FloatV reduceBatchContactsConvex(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch); //This function reduces the manifold contact list in a patch for sphere vs mesh aos::FloatV reduceBatchContactsSphere(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch); //This function reduces the manifold contact list in a patch for capsuel vs mesh aos::FloatV reduceBatchContactsCapsule(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch); //This function adds the manifold contact list in a patch for box/convexhull vs mesh aos::FloatV addBatchManifoldContactsConvex(const MeshPersistentContact* manifoldContact, PxU32 numContacts, PCMContactPatch& patch, const aos::FloatVArg replaceBreakingThreshold); //This function adds the manifold contact list in a patch for sphere vs mesh aos::FloatV addBatchManifoldContactsSphere(const MeshPersistentContact* manifoldContact, PxU32 numContacts, PCMContactPatch& patch, const aos::FloatVArg replaceBreakingThreshold); //This function adds the manifold contact list in a patch for capsule vs mesh aos::FloatV addBatchManifoldContactsCapsule(const MeshPersistentContact* manifoldContact, PxU32 numContacts, PCMContactPatch& patch, const aos::FloatVArg replaceBreakingThreshold); //This is used for in the addContactsToPatch for convex mesh contact gen. static PxU32 reduceContacts(MeshPersistentContact* manifoldContactExt, PxU32 numContacts); //This function is to recalculate the contacts based on the relative transform between a pair of objects aos::FloatV refreshContactPoints(const aos::PxMatTransformV& relTra, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg contactOffset); void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const; MeshPersistentContact mContactPoints[GU_SINGLE_MANIFOLD_CACHE_SIZE];//384 bytes PxU32 mNumContacts;//400 bytes } PX_ALIGN_SUFFIX(16); //This is a structure used to cache a multi-persistent-manifold in the cache stream struct MultiPersistentManifoldHeader { aos::PxTransformV mRelativeTransform;//aToB PxU32 mNumManifolds; PxU32 pad[3]; }; struct SingleManifoldHeader { PxU32 mNumContacts; PxU32 pad[3]; }; #if PX_VC #pragma warning(push) #pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class #endif PX_ALIGN_PREFIX(16) class PX_PHYSX_COMMON_API MultiplePersistentContactManifold { public: MultiplePersistentContactManifold():mNumManifolds(0), mNumTotalContacts(0) { mRelativeTransform.invalidate(); } PX_FORCE_INLINE void setRelativeTransform(const aos::PxTransformV& transform) { mRelativeTransform = transform; } PX_FORCE_INLINE aos::FloatV maxTransformPositionDelta(const aos::Vec3V& curP) const { using namespace aos; const Vec3V deltaP = V3Sub(curP, mRelativeTransform.p); const Vec4V delta = Vec4V_From_Vec3V(V3Abs(deltaP)); //need to work out max from a single vector... return V4ExtractMax(delta); } PX_FORCE_INLINE aos::FloatV maxTransformQuatDelta(const aos::QuatV& curQ) const { using namespace aos; const Vec4V deltaQ = V4Sub(curQ, mRelativeTransform.q); const Vec4V delta = V4Abs(deltaQ); //need to work out max from a single vector... return V4ExtractMax(delta); } PX_FORCE_INLINE PxU32 invalidate(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin, const aos::FloatVArg ratio) const { using namespace aos; const FloatV thresholdP = FMul(minMargin, ratio); const FloatV deltaP = maxTransformPositionDelta(curRTrans.p); const FloatV thresholdQ = FLoad(0.9998f);//about 1 degree const FloatV deltaQ = QuatDot(curRTrans.q, mRelativeTransform.q); const BoolV con = BOr(FIsGrtr(deltaP, thresholdP), FIsGrtr(thresholdQ, deltaQ)); return BAllEqTTTT(con); } PX_FORCE_INLINE PxU32 invalidate(const aos::PxTransformV& curRTrans, const aos::FloatVArg minMargin) const { using namespace aos; return invalidate(curRTrans, minMargin, FLoad(0.2f)); } // This function work out the contact patch connectivity. If two patches's normal are within 5 degree, we would link these two patches together and reset the total size. PX_FORCE_INLINE void refineContactPatchConnective(PCMContactPatch** contactPatch, PxU32 numContactPatch, MeshPersistentContact* manifoldContacts, const aos::FloatVArg acceptanceEpsilon) const { PX_UNUSED(manifoldContacts); using namespace aos; //work out the contact patch connectivity, the patchNormal should be in the local space of mesh for(PxU32 i=0; i<numContactPatch; ++i) { PCMContactPatch* patch = contactPatch[i]; patch->mRoot = patch; patch->mEndPatch = patch; patch->mTotalSize = patch->mEndIndex - patch->mStartIndex; patch->mNextPatch = NULL; for(PxU32 j=i; j>0; --j) { PCMContactPatch* other = contactPatch[j-1]; const FloatV d = V3Dot(patch->mPatchNormal, other->mRoot->mPatchNormal); if(FAllGrtrOrEq(d, acceptanceEpsilon))//less than 5 degree { other->mNextPatch = patch; other->mRoot->mEndPatch = patch; patch->mRoot = other->mRoot; other->mRoot->mTotalSize += patch->mEndIndex - patch->mStartIndex; break; } } } } // This function uses to reduce the manifold contacts which are in different connected patchs but are within replace breaking threshold PX_FORCE_INLINE PxU32 reduceManifoldContactsInDifferentPatches(PCMContactPatch** contactPatch, PxU32 numContactPatch, MeshPersistentContact* manifoldContacts, PxU32 numContacts, const aos::FloatVArg sqReplaceBreaking) const { using namespace aos; for(PxU32 i=0; i<numContactPatch; ++i) { PCMContactPatch* currentPatch = contactPatch[i]; //this make sure the patch is the root before we do the contact reduction, otherwise, we will do duplicate work if(currentPatch->mRoot == currentPatch) { while(currentPatch) { PCMContactPatch* nextPatch = currentPatch->mNextPatch; if(nextPatch) { for(PxU32 k = currentPatch->mStartIndex; k<currentPatch->mEndIndex; ++k) { for(PxU32 l = nextPatch->mStartIndex; l < nextPatch->mEndIndex; ++l) { Vec3V dif = V3Sub(manifoldContacts[l].mLocalPointB, manifoldContacts[k].mLocalPointB); FloatV d = V3Dot(dif, dif); if(FAllGrtr(sqReplaceBreaking, d)) { //if two manifold contacts are within threshold, we will get rid of the manifold contacts in the other contact patch manifoldContacts[l] = manifoldContacts[nextPatch->mEndIndex-1]; nextPatch->mEndIndex--; numContacts--; l--; } } } } currentPatch = nextPatch; } } } return numContacts; } // This function is for the multiple manifold loop through each individual single manifold to recalculate the contacts based on the relative transform between a pair of objects PX_FORCE_INLINE void refreshManifold(const aos::PxMatTransformV& relTra, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg contactDist) { using namespace aos; //refresh manifold contacts for(PxU32 i=0; i<mNumManifolds; ++i) { const PxU8 ind = mManifoldIndices[i]; PX_ASSERT(mManifoldIndices[i] < GU_MAX_MANIFOLD_SIZE); const PxU32 nextInd = PxMin(i, mNumManifolds-2u)+1; PxPrefetchLine(&mManifolds[mManifoldIndices[nextInd]]); PxPrefetchLine(&mManifolds[mManifoldIndices[nextInd]],128); PxPrefetchLine(&mManifolds[mManifoldIndices[nextInd]],256); const FloatV _maxPen = mManifolds[ind].refreshContactPoints(relTra, projectBreakingThreshold, contactDist); if(mManifolds[ind].isEmpty()) { //swap the index with the next manifolds const PxU8 index = mManifoldIndices[--mNumManifolds]; mManifoldIndices[mNumManifolds] = ind; mManifoldIndices[i] = index; i--; } else { FStore(_maxPen, &mMaxPen[ind]); } } } PX_FORCE_INLINE void initialize() { mNumManifolds = 0; mNumTotalContacts = 0; mRelativeTransform.invalidate(); for(PxU8 i=0; i<GU_MAX_MANIFOLD_SIZE; ++i) { mManifolds[i].initialize(); mManifoldIndices[i] = i; } } PX_FORCE_INLINE void clearManifold() { for(PxU8 i=0; i<mNumManifolds; ++i) { mManifolds[i].clearManifold(); } mNumManifolds = 0; mNumTotalContacts = 0; mRelativeTransform.invalidate(); } PX_FORCE_INLINE const SinglePersistentContactManifold* getManifold(PxU32 index) const { PX_ASSERT(index < GU_MAX_MANIFOLD_SIZE); return &mManifolds[mManifoldIndices[index]]; } PX_FORCE_INLINE SinglePersistentContactManifold* getManifold(PxU32 index) { PX_ASSERT(index < GU_MAX_MANIFOLD_SIZE); return &mManifolds[mManifoldIndices[index]]; } PX_FORCE_INLINE SinglePersistentContactManifold* getEmptyManifold() { if(mNumManifolds < GU_MAX_MANIFOLD_SIZE) return &mManifolds[mManifoldIndices[mNumManifolds]]; return NULL; } //This function adds the manifold contacts with different patches into the corresponding single persistent contact manifold void addManifoldContactPoints(MeshPersistentContact* manifoldContact, PxU32 numManifoldContacts, PCMContactPatch** contactPatch, PxU32 numPatch, const aos::FloatVArg sqReplaceBreakingThreshold, const aos::FloatVArg acceptanceEpsilon, PxU8 maxContactsPerManifold); //This function adds the box/convexhull manifold contacts to the contact buffer bool addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::PxTransformV& transf1); //This function adds the sphere/capsule manifold contacts to the contact buffer bool addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const aos::PxTransformV& trA, const aos::PxTransformV& trB, const aos::FloatVArg radius); void drawManifold(PxRenderOutput& out, const aos::PxTransformV& trA, const aos::PxTransformV& trB) const; //Code to load from a buffer and store to a buffer. void fromBuffer(PxU8* PX_RESTRICT buffer); void toBuffer(PxU8* PX_RESTRICT buffer) const; static void drawLine(PxRenderOutput& out, const aos::Vec3VArg p0, const aos::Vec3VArg p1, PxU32 color = 0xff00ffff); static void drawLine(PxRenderOutput& out, const PxVec3 p0, const PxVec3 p1, PxU32 color = 0xff00ffff); static void drawPoint(PxRenderOutput& out, const aos::Vec3VArg p, const PxF32 size, PxU32 color = 0x00ff0000); static void drawPolygon(PxRenderOutput& out, const aos::PxTransformV& transform, aos::Vec3V* points, PxU32 numVerts, PxU32 color = 0xff00ffff); aos::PxTransformV mRelativeTransform;//aToB PxF32 mMaxPen[GU_MAX_MANIFOLD_SIZE]; PxU8 mManifoldIndices[GU_MAX_MANIFOLD_SIZE]; PxU8 mNumManifolds; PxU8 mNumTotalContacts; SinglePersistentContactManifold mManifolds[GU_MAX_MANIFOLD_SIZE]; } PX_ALIGN_SUFFIX(16); #if PX_VC #pragma warning(pop) #endif // This function calculates the average normal in the manifold in world space PX_FORCE_INLINE aos::Vec3V PersistentContactManifold::getWorldNormal(const aos::PxTransformV& trB) const { using namespace aos; Vec4V nPen = mContactPoints[0].mLocalNormalPen; for(PxU32 i=1; i<mNumContacts; ++i) { nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen); } const Vec3V n = Vec3V_From_Vec4V(nPen); const FloatV sqLength = V3Dot(n, n); const Vec3V nn = V3Sel(FIsGrtr(sqLength, FEps()), n, Vec3V_From_Vec4V(mContactPoints[0].mLocalNormalPen)); return V3Normalize(trB.rotate(nn)); } // This function calculates the average normal in the manifold in local B space PX_FORCE_INLINE aos::Vec3V PersistentContactManifold::getLocalNormal() const { using namespace aos; Vec4V nPen = mContactPoints[0].mLocalNormalPen; for(PxU32 i=1; i<mNumContacts; ++i) { nPen = V4Add(nPen, mContactPoints[i].mLocalNormalPen); } return V3Normalize(Vec3V_From_Vec4V(nPen)); } // This function recalculates the contacts in the manifold based on the current relative transform between a pair of objects. If the recalculated contacts are within some threshold, // we will keep the contacts; Otherwise, we will remove the contacts. PX_FORCE_INLINE void PersistentContactManifold::refreshContactPoints(const aos::PxMatTransformV& aToB, const aos::FloatVArg projectBreakingThreshold, const aos::FloatVArg /*contactOffset*/) { using namespace aos; const FloatV sqProjectBreakingThreshold = FMul(projectBreakingThreshold, projectBreakingThreshold); // first refresh worldspace positions and distance for (PxU32 i=mNumContacts; i > 0; --i) { PersistentContact& manifoldPoint = mContactPoints[i-1]; const Vec3V localAInB = aToB.transform( manifoldPoint.mLocalPointA ); // from a to b const Vec3V localBInB = manifoldPoint.mLocalPointB; const Vec3V v = V3Sub(localAInB, localBInB); const Vec3V localNormal = Vec3V_From_Vec4V(manifoldPoint.mLocalNormalPen); // normal in b space const FloatV dist = V3Dot(v, localNormal); const Vec3V projectedPoint = V3NegScaleSub(localNormal, dist, localAInB);//manifoldPoint.worldPointA - manifoldPoint.worldPointB * manifoldPoint.m_distance1; const Vec3V projectedDifference = V3Sub(localBInB, projectedPoint); const FloatV distance2d = V3Dot(projectedDifference, projectedDifference); //const BoolV con = BOr(FIsGrtr(dist, contactOffset), FIsGrtr(distance2d, sqProjectBreakingThreshold)); const BoolV con = FIsGrtr(distance2d, sqProjectBreakingThreshold); if(BAllEqTTTT(con)) { removeContactPoint(i-1); } else { manifoldPoint.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), dist); } } } #define PX_CP_TO_PCP(contactPoint) (reinterpret_cast<PersistentContact*>(contactPoint)) //this is used in the normal pcm contact gen #define PX_CP_TO_MPCP(contactPoint) (reinterpret_cast<MeshPersistentContact*>(contactPoint))//this is used in the mesh pcm contact gen void addManifoldPoint(PersistentContact* manifoldContacts, PersistentContactManifold& manifold, GjkOutput& output, const aos::PxMatTransformV& aToB, const aos::FloatV replaceBreakingThreshold); }//Gu }//physx #endif
33,657
C
39.896719
238
0.767894
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenSphereCapsule.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 "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" #include "common/PxRenderOutput.h" #include "GuPCMContactGenUtil.h" #include "foundation/PxVecMath.h" #include "foundation/PxAlloca.h" #include "GuVecCapsule.h" #include "GuVecBox.h" using namespace physx; using namespace Gu; using namespace aos; //ML: this function is shared by the sphere/capsule vs convex hulls full contact gen, capsule in the local space of polyData static bool testPolyDataAxis(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& separatingAxis) { FloatV _minOverlap = FMax();//minOverlap; FloatV min0, max0; FloatV min1, max1; Vec3V tempAxis = V3UnitY(); //capsule in the local space of polyData for(PxU32 i=0; i<polyData.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData.mPolygons[i]; const Vec3V minVert = V3LoadU_SafeReadW(polyData.mVerts[polygon.mMinIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const FloatV planeDist = FLoad(polygon.mPlane.d); const Vec3V vertexSpacePlaneNormal = V3LoadU_SafeReadW(polygon.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class //transform plane n to shape space const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(map->shape2Vertex, vertexSpacePlaneNormal); const FloatV magnitude = FRecip(V3Length(shapeSpacePlaneNormal)); //normalize shape space normal const Vec3V planeN = V3Scale(shapeSpacePlaneNormal, magnitude); //ML::use this to avoid LHS min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude); max0 = FMul(FNeg(planeDist), magnitude); const FloatV tempMin = V3Dot(capsule.p0, planeN); const FloatV tempMax = V3Dot(capsule.p1, planeN); min1 = FMin(tempMin, tempMax); max1 = FMax(tempMin, tempMax); min1 = FSub(min1, capsule.radius); max1 = FAdd(max1, capsule.radius); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); if(FAllGrtr(_minOverlap, tempOverlap)) { _minOverlap = tempOverlap; tempAxis = planeN; } } separatingAxis = tempAxis; minOverlap = _minOverlap; return true; } //ML: this function is shared by sphere/capsule. Point a and direction d need to be in the local space of polyData static bool intersectRayPolyhedron(const Vec3VArg a, const Vec3VArg dir, const PolygonalData& polyData, FloatV& tEnter, FloatV& tExit) { const FloatV zero = FZero(); const FloatV eps = FLoad(1e-7f); FloatV tFirst = zero; FloatV tLast= FMax(); for(PxU32 k=0; k<polyData.mNbPolygons; ++k) { const HullPolygonData& data = polyData.mPolygons[k]; const Vec3V n = V3LoadU_SafeReadW(data.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class FloatV d = FLoad(data.mPlane.d); const FloatV denominator = V3Dot(n, dir); const FloatV distToPlane = FAdd(V3Dot(n, a), d); if(FAllGrtr(eps, FAbs(denominator))) { if(FAllGrtr(distToPlane, zero)) return false; } else { FloatV tTemp = FNeg(FDiv(distToPlane, denominator)); //ML: denominator < 0 means the ray is entering halfspace; denominator > 0 means the ray is exiting halfspace const BoolV con = FIsGrtr(zero, denominator); const BoolV con0 = FIsGrtr(tTemp, tFirst); const BoolV con1 = FIsGrtr(tLast, tTemp); tFirst = FSel(BAnd(con, con0), tTemp, tFirst); tLast = FSel(BAndNot(con1, con), tTemp, tLast); } if(FAllGrtr(tFirst, tLast)) return false; } //calculate the intersect p in the local space tEnter = tFirst; tExit = tLast; return true; } //Precompute the convex data // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ static bool testSATCapsulePoly(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& separatingAxis) { FloatV _minOverlap = FMax();//minOverlap; FloatV min0, max0; FloatV min1, max1; Vec3V tempAxis = V3UnitY(); const FloatV eps = FEps(); //ML: project capsule to polydata axis if(!testPolyDataAxis(capsule, polyData, map, contactDist, _minOverlap, tempAxis)) return false; const Vec3V capsuleAxis = V3Sub(capsule.p1, capsule.p0); for(PxU32 i=0;i<polyData.mNbPolygons;i++) { const HullPolygonData& polygon = polyData.mPolygons[i]; const PxU8* inds1 = polyData.mPolygonVertexRefs + polygon.mVRef8; for(PxU32 lStart = 0, lEnd =PxU32(polygon.mNbVerts-1); lStart<polygon.mNbVerts; lEnd = lStart++) { //in the vertex space const Vec3V p10 = V3LoadU_SafeReadW(polyData.mVerts[inds1[lStart]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const Vec3V p11 = V3LoadU_SafeReadW(polyData.mVerts[inds1[lEnd]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const Vec3V vertexSpaceV = V3Sub(p11, p10); //transform v to shape space const Vec3V shapeSpaceV = M33TrnspsMulV3(map->shape2Vertex, vertexSpaceV); const Vec3V dir = V3Cross(capsuleAxis, shapeSpaceV); const FloatV lenSq = V3Dot(dir, dir); if(FAllGrtr(eps, lenSq)) continue; const Vec3V normal = V3ScaleInv(dir, FSqrt(lenSq)); map->doSupport(normal, min0, max0); const FloatV tempMin = V3Dot(capsule.p0, normal); const FloatV tempMax = V3Dot(capsule.p1, normal); min1 = FMin(tempMin, tempMax); max1 = FMax(tempMin, tempMax); min1 = FSub(min1, capsule.radius); max1 = FAdd(max1, capsule.radius); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); if(FAllGrtr(_minOverlap, tempOverlap)) { _minOverlap = tempOverlap; tempAxis = normal; } } } separatingAxis = tempAxis; minOverlap = _minOverlap; return true; } static void generatedCapsuleBoxFaceContacts(const CapsuleV& capsule, const PolygonalData& polyData, const HullPolygonData& referencePolygon, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, const Vec3VArg normal) { const FloatV radius = FAdd(capsule.radius, contactDist); //calculate the intersect point of ray to plane const Vec3V planeNormal = V3Normalize(M33TrnspsMulV3(map->shape2Vertex, V3LoadU(referencePolygon.mPlane.n))); const PxU8* inds = polyData.mPolygonVertexRefs + referencePolygon.mVRef8; const Vec3V a = M33MulV3(map->vertex2Shape, V3LoadU_SafeReadW(polyData.mVerts[inds[0]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData const FloatV denom0 = V3Dot(planeNormal, V3Sub(capsule.p0, a)); const FloatV denom1 = V3Dot(planeNormal, V3Sub(capsule.p1, a)); const FloatV projPlaneN = V3Dot(planeNormal, normal); const FloatV numer = FSel(FIsGrtr(projPlaneN, FZero()), FRecip(projPlaneN), FZero()); const FloatV t0 = FMul(denom0, numer); const FloatV t1 = FMul(denom1, numer); const BoolV con0 = FIsGrtrOrEq(radius, t0); const BoolV con1 = FIsGrtrOrEq(radius, t1); if(BAllEqTTTT(BOr(con0, con1))) { const Mat33V rot = findRotationMatrixFromZAxis(planeNormal); Vec3V* points0In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16)); map->populateVerts(inds, referencePolygon.mNbVerts, polyData.mVerts, points0In0); Vec3V rPolygonMin = V3Splat(FMax()); Vec3V rPolygonMax = V3Neg(rPolygonMin); for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { points0In0[i] = M33MulV3(rot, points0In0[i]); rPolygonMin = V3Min(rPolygonMin, points0In0[i]); rPolygonMax = V3Max(rPolygonMax, points0In0[i]); } if(BAllEqTTTT(con0)) { //add contact const Vec3V proj = V3NegScaleSub(normal, t0, capsule.p0);//V3ScaleAdd(t0, normal, capsule.p0); //transform proj0 to 2D const Vec3V point = M33MulV3(rot, proj); if(contains(points0In0, referencePolygon.mNbVerts, point, rPolygonMin, rPolygonMax)) { manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p0); manifoldContacts[numContacts].mLocalPointB = proj; manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), t0); } } if(BAllEqTTTT(con1)) { const Vec3V proj = V3NegScaleSub(normal, t1, capsule.p1);//V3ScaleAdd(t1, normal, capsule.p1); //transform proj0 to 2D const Vec3V point = M33MulV3(rot, proj); if(contains(points0In0, referencePolygon.mNbVerts, point, rPolygonMin, rPolygonMax)) { manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p1); manifoldContacts[numContacts].mLocalPointB = proj; manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal),t1); } } } } static void generatedFaceContacts(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, const Vec3VArg normal) { const FloatV zero = FZero(); FloatV tEnter = zero, tExit = zero; const FloatV inflatedRadius = FAdd(capsule.radius, contactDist); const Vec3V dir = V3Neg(normal); const Vec3V vertexSpaceDir = M33MulV3(map->shape2Vertex, dir); const Vec3V p0 = M33MulV3(map->shape2Vertex, capsule.p0); if(intersectRayPolyhedron(p0, vertexSpaceDir, polyData, tEnter, tExit) && FAllGrtrOrEq(inflatedRadius, tEnter)) { manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p0); manifoldContacts[numContacts].mLocalPointB = V3ScaleAdd(dir, tEnter, capsule.p0); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), tEnter); } const Vec3V p1 = M33MulV3(map->shape2Vertex, capsule.p1); if(intersectRayPolyhedron(p1, vertexSpaceDir, polyData, tEnter, tExit) && FAllGrtrOrEq(inflatedRadius, tEnter)) { manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(capsule.p1); manifoldContacts[numContacts].mLocalPointB = V3ScaleAdd(dir, tEnter, capsule.p1); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), tEnter); } } static void generateEE(const Vec3VArg p, const Vec3VArg q, const Vec3VArg normal, const Vec3VArg a, const Vec3VArg b, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg inflatedRadius) { const FloatV zero = FZero(); const FloatV expandedRatio = FLoad(0.005f); const Vec3V ab = V3Sub(b, a); const Vec3V n = V3Cross(ab, normal); const FloatV d = V3Dot(n, a); const FloatV np = V3Dot(n, p); const FloatV nq = V3Dot(n,q); const FloatV signP = FSub(np, d); const FloatV signQ = FSub(nq, d); const FloatV temp = FMul(signP, signQ); if(FAllGrtr(temp, zero)) return;//If both points in the same side as the plane, no intersect points // if colliding edge (p3,p4) and plane are parallel return no collision const Vec3V pq = V3Sub(q, p); const FloatV npq = V3Dot(n, pq); if(FAllEq(npq, zero)) return; //calculate the intersect point in the segment pq with plane n(x - a). const FloatV segTValue = FDiv(FSub(d, np), npq); const Vec3V localPointA = V3ScaleAdd(pq, segTValue, p); //ML: ab, localPointA and normal is in the same plane, so that we can do 2D segment segment intersection //calculate a normal perpendicular to ray localPointA + normal*t, then do 2D segment segment intersection const Vec3V perNormal = V3Cross(normal, pq); const Vec3V ap = V3Sub(localPointA, a); const FloatV nom = V3Dot(perNormal, ap); const FloatV denom = V3Dot(perNormal, ab); const FloatV tValue = FDiv(nom, denom); const FloatV max = FAdd(FOne(), expandedRatio); const FloatV min = FSub(zero, expandedRatio); if(FAllGrtr(tValue, max) || FAllGrtr(min, tValue)) return; const Vec3V v = V3NegScaleSub(ab, tValue, ap); const FloatV signedDist = V3Dot(v, normal); if(FAllGrtrOrEq(inflatedRadius, signedDist)) { const Vec3V localPointB = V3Sub(localPointA, v); manifoldContacts[numContacts].mLocalPointA = aToB.transformInv(localPointA); manifoldContacts[numContacts].mLocalPointB = localPointB; manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), signedDist); } } static void generatedContactsEEContacts(const CapsuleV& capsule, const PolygonalData& polyData, const HullPolygonData& referencePolygon, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, const Vec3VArg contactNormal) { const PxU8* inds = polyData.mPolygonVertexRefs + referencePolygon.mVRef8; Vec3V* points0In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16)); //Transform all the verts from vertex space to shape space map->populateVerts(inds, referencePolygon.mNbVerts, polyData.mVerts, points0In0); const FloatV inflatedRadius = FAdd(capsule.radius, contactDist); for (PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++) { generateEE(capsule.p0, capsule.p1, contactNormal,points0In0[rStart], points0In0[rEnd], aToB, manifoldContacts, numContacts, inflatedRadius); } } bool Gu::generateCapsuleBoxFullContactManifold(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& normal, const Vec3VArg closest, PxReal margin, bool doOverlapTest, PxReal toleranceScale, PxRenderOutput* renderOutput) { PX_UNUSED(renderOutput); const PxU32 originalContacts = numContacts; const HullPolygonData* referencePolygon = NULL; if(doOverlapTest) { FloatV minOverlap; //overwrite the normal if(!testSATCapsulePoly(capsule, polyData, map, contactDist, minOverlap, normal)) return false; referencePolygon = &polyData.mPolygons[getPolygonIndex(polyData, map, V3Neg(normal))]; } else { const PxReal lowerEps = toleranceScale * PCM_WITNESS_POINT_LOWER_EPS; const PxReal upperEps = toleranceScale * PCM_WITNESS_POINT_UPPER_EPS; const PxReal tolerance = PxClamp(margin, lowerEps, upperEps); const PxU32 featureIndex = getWitnessPolygonIndex(polyData, map, V3Neg(normal), closest, tolerance); referencePolygon = &polyData.mPolygons[featureIndex]; } #if PCM_LOW_LEVEL_DEBUG const PxU8* inds = polyData.mPolygonVertexRefs + referencePolygon->mVRef8; Vec3V* pointsInRef = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon->mNbVerts, 16)); map->populateVerts(inds, referencePolygon->mNbVerts, polyData.mVerts, pointsInRef); PersistentContactManifold::drawPolygon(*renderOutput, map->transform, pointsInRef, referencePolygon->mNbVerts, 0x00ff0000); #endif generatedCapsuleBoxFaceContacts(capsule, polyData, *referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, normal); const PxU32 faceContacts = numContacts - originalContacts; if(faceContacts < 2) { generatedContactsEEContacts(capsule, polyData, *referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, normal); } return true; } //capsule is in the local space of polyData bool Gu::generateFullContactManifold(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, const PxMatTransformV& aToB, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& normal, const Vec3VArg closest, PxReal margin, bool doOverlapTest, PxReal toleranceLength) { const PxU32 originalContacts = numContacts; Vec3V tNormal = normal; if(doOverlapTest) { FloatV minOverlap; //overwrite the normal with the sperating axis if(!testSATCapsulePoly(capsule, polyData, map, contactDist, minOverlap, tNormal)) return false; generatedFaceContacts(capsule, polyData, map, aToB, manifoldContacts, numContacts, contactDist, tNormal); const PxU32 faceContacts = numContacts - originalContacts; if(faceContacts < 2) { const HullPolygonData& referencePolygon = polyData.mPolygons[getPolygonIndex(polyData, map, V3Neg(tNormal))]; generatedContactsEEContacts(capsule, polyData,referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, tNormal); } } else { generatedFaceContacts(capsule, polyData, map, aToB, manifoldContacts, numContacts, contactDist, tNormal); const PxU32 faceContacts = numContacts - originalContacts; if(faceContacts < 2) { const PxReal lowerEps = toleranceLength * PCM_WITNESS_POINT_LOWER_EPS; const PxReal upperEps = toleranceLength * PCM_WITNESS_POINT_UPPER_EPS; const PxReal tolerance = PxClamp(margin, lowerEps, upperEps); const PxU32 featureIndex = getWitnessPolygonIndex(polyData, map, V3Neg(tNormal), closest, tolerance); const HullPolygonData& referencePolygon = polyData.mPolygons[featureIndex]; generatedContactsEEContacts(capsule, polyData,referencePolygon, map, aToB, manifoldContacts, numContacts, contactDist, tNormal); } } normal = tNormal; return true; } //sphere is in the local space of polyData, we treate sphere as capsule bool Gu::generateSphereFullContactManifold(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& normal, bool doOverlapTest) { if(doOverlapTest) { FloatV minOverlap; //overwrite the normal with the sperating axis if(!testPolyDataAxis(capsule, polyData, map, contactDist, minOverlap, normal)) return false; } const FloatV zero = FZero(); FloatV tEnter = zero, tExit = zero; const FloatV inflatedRadius = FAdd(capsule.radius, contactDist); const Vec3V dir = V3Neg(normal); const Vec3V vertexSpaceDir = M33MulV3(map->shape2Vertex, dir); const Vec3V p0 = M33MulV3(map->shape2Vertex, capsule.p0); if(intersectRayPolyhedron(p0, vertexSpaceDir, polyData, tEnter, tExit) && FAllGrtrOrEq(inflatedRadius, tEnter)) { //ML: for sphere, the contact point A is always zeroV in its local space manifoldContacts[numContacts].mLocalPointA = V3Zero(); manifoldContacts[numContacts].mLocalPointB = V3ScaleAdd(dir, tEnter, capsule.p0); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(normal), tEnter); } return true; } //capsule is in the shape space of polyData bool Gu::computeMTD(const CapsuleV& capsule, const PolygonalData& polyData, const SupportLocal* map, FloatV& penDepth, Vec3V& normal) { const FloatV contactDist = FZero(); Vec3V separatingAxis; FloatV minOverlap; if(!testSATCapsulePoly(capsule, polyData, map, contactDist, minOverlap, separatingAxis)) return false; //transform normal in to the worl space normal = map->transform.rotate(separatingAxis); penDepth = minOverlap; return true; }
20,676
C++
39.306043
252
0.746905
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereMesh.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/PxSort.h" #include "GuContactMethodImpl.h" #include "GuPCMContactConvexCommon.h" #include "GuPCMContactMeshCallback.h" #include "GuFeatureCode.h" #include "GuBox.h" using namespace physx; using namespace Gu; using namespace aos; namespace { struct PCMSphereVsMeshContactGenerationCallback : PCMMeshContactGenerationCallback< PCMSphereVsMeshContactGenerationCallback > { PCMSphereVsMeshContactGeneration mGeneration; PCMSphereVsMeshContactGenerationCallback( const Vec3VArg sphereCenter, const FloatVArg sphereRadius, const FloatVArg contactDist, const FloatVArg replaceBreakingThreshold, const PxTransformV& sphereTransform, const PxTransformV& meshTransform, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, const PxU8* extraTriData, const Cm::FastVertex2ShapeScaling& meshScaling, bool idtMeshScale, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, PxRenderOutput* renderOutput = NULL ) : PCMMeshContactGenerationCallback<PCMSphereVsMeshContactGenerationCallback>(meshScaling, extraTriData, idtMeshScale), mGeneration(sphereCenter, sphereRadius, contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer, deferredContacts, renderOutput) { } PX_FORCE_INLINE bool doTest(const PxVec3&, const PxVec3&, const PxVec3&) { return true; } template<PxU32 CacheSize> void processTriangleCache(TriangleCache<CacheSize>& cache) { mGeneration.processTriangleCache<CacheSize, PCMSphereVsMeshContactGeneration>(cache); } }; } bool Gu::pcmContactSphereMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&transform0.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV sphereRadius = FLoad(shapeSphere.radius); const FloatV contactDist = FLoad(params.mContactDistance); const PxTransformV sphereTransform(p0, q0);//sphere transform const PxTransformV meshTransform(p1, q1);//triangleMesh const PxTransformV curTransform = meshTransform.transformInv(sphereTransform); // We must be in local space to use the cache if(multiManifold.invalidate(curTransform, sphereRadius, FLoad(0.02f))) { const FloatV replaceBreakingThreshold = FMul(sphereRadius, FLoad(0.001f)); const PxVec3 sphereCenterShape1Space = transform1.transformInv(transform0.p); PxReal inflatedRadius = shapeSphere.radius + params.mContactDistance; const Vec3V sphereCenter = V3LoadU(sphereCenterShape1Space); const TriangleMesh* meshData = _getMeshData(shapeMesh); Cm::FastVertex2ShapeScaling meshScaling; // PT: TODO: get rid of default ctor :( const bool idtMeshScale = shapeMesh.scale.isIdentity(); if(!idtMeshScale) meshScaling.init(shapeMesh.scale); multiManifold.mNumManifolds = 0; multiManifold.setRelativeTransform(curTransform); PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts; const PxU8* PX_RESTRICT extraData = meshData->getExtraTrigData(); // mesh scale is not baked into cached verts PCMSphereVsMeshContactGenerationCallback callback( sphereCenter, sphereRadius, contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer, extraData, meshScaling, idtMeshScale, &delayedContacts, renderOutput); PxVec3 obbCenter = sphereCenterShape1Space; PxVec3 obbExtents = PxVec3(inflatedRadius); PxMat33 obbRot(PxIdentity); if(!idtMeshScale) meshScaling.transformQueryBounds(obbCenter, obbExtents, obbRot); const Box obb(obbCenter, obbExtents, obbRot); Midphase::intersectOBB(meshData, obb, callback, true); callback.flushCache(); callback.mGeneration.generateLastContacts(); callback.mGeneration.processContacts(GU_SPHERE_MANIFOLD_CACHE_SIZE, false); } else { const PxMatTransformV aToB(curTransform); const FloatV projectBreakingThreshold = FMul(sphereRadius, FLoad(0.05f)); const FloatV refereshDistance = FAdd(sphereRadius, contactDist); multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance); } //multiManifold.drawManifold(*gRenderOutPut, sphereTransform, meshTransform); return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, sphereTransform, meshTransform, sphereRadius); } static FloatV pcmDistancePointTriangleSquared( const Vec3VArg p, const Vec3VArg a, const Vec3VArg b, const Vec3VArg c, Vec3V& closestP, FeatureCode& fc) { const FloatV zero = FZero(); const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V bc = V3Sub(c, b); const Vec3V ap = V3Sub(p, a); const Vec3V bp = V3Sub(p, b); const Vec3V cp = V3Sub(p, c); const FloatV d1 = V3Dot(ab, ap); // snom const FloatV d2 = V3Dot(ac, ap); // tnom const FloatV d3 = V3Dot(ab, bp); // -sdenom const FloatV d4 = V3Dot(ac, bp); // unom = d4 - d3 const FloatV d5 = V3Dot(ab, cp); // udenom = d5 - d6 const FloatV d6 = V3Dot(ac, cp); // -tdenom const FloatV unom = FSub(d4, d3); const FloatV udenom = FSub(d5, d6); const Vec3V n = V3Cross(ab, ac); const VecCrossV crossA = V3PrepareCross(ap); const VecCrossV crossB = V3PrepareCross(bp); const VecCrossV crossC = V3PrepareCross(cp); const Vec3V bCrossC = V3Cross(crossB, crossC); const Vec3V cCrossA = V3Cross(crossC, crossA); const Vec3V aCrossB = V3Cross(crossA, crossB); //const FloatV va = V3Dot(n, bCrossC);//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a //const FloatV vb = V3Dot(n, cCrossA);//edge region of AC, signed area rac, v = S(rca)/S(abc) for b //const FloatV vc = V3Dot(n, aCrossB);//edge region of AB, signed area rab, w = S(rab)/S(abc) for c //check if p in vertex region outside a const BoolV con00 = FIsGrtr(zero, d1); // snom <= 0 const BoolV con01 = FIsGrtr(zero, d2); // tnom <= 0 const BoolV con0 = BAnd(con00, con01); // vertex region a if(BAllEqTTTT(con0)) { //Vertex 0 fc = FC_VERTEX0; closestP = a; return V3Dot(ap, ap); } //check if p in vertex region outside b const BoolV con10 = FIsGrtrOrEq(d3, zero); const BoolV con11 = FIsGrtrOrEq(d3, d4); const BoolV con1 = BAnd(con10, con11); // vertex region b if(BAllEqTTTT(con1)) { //Vertex 1 fc = FC_VERTEX1; closestP = b; return V3Dot(bp, bp); } //check if p in vertex region outside c const BoolV con20 = FIsGrtrOrEq(d6, zero); const BoolV con21 = FIsGrtrOrEq(d6, d5); const BoolV con2 = BAnd(con20, con21); // vertex region c if(BAllEqTTTT(con2)) { //Vertex 2 fc = FC_VERTEX2; closestP = c; return V3Dot(cp, cp); } //check if p in edge region of AB //const FloatV vc = FSub(FMul(d1, d4), FMul(d3, d2)); const FloatV vc = V3Dot(n, aCrossB);//edge region of AB, signed area rab, w = S(rab)/S(abc) for c const BoolV con30 = FIsGrtr(zero, vc); const BoolV con31 = FIsGrtrOrEq(d1, zero); const BoolV con32 = FIsGrtr(zero, d3); const BoolV con3 = BAnd(con30, BAnd(con31, con32)); if(BAllEqTTTT(con3)) { // Edge 01 fc = FC_EDGE01; const FloatV sScale = FDiv(d1, FSub(d1, d3)); const Vec3V closest3 = V3ScaleAdd(ab, sScale, a);//V3Add(a, V3Scale(ab, sScale)); const Vec3V vv = V3Sub(p, closest3); closestP = closest3; return V3Dot(vv, vv); } //check if p in edge region of BC //const FloatV va = FSub(FMul(d3, d6),FMul(d5, d4)); const FloatV va = V3Dot(n, bCrossC);//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a const BoolV con40 = FIsGrtr(zero, va); const BoolV con41 = FIsGrtrOrEq(d4, d3); const BoolV con42 = FIsGrtrOrEq(d5, d6); const BoolV con4 = BAnd(con40, BAnd(con41, con42)); if(BAllEqTTTT(con4)) { // Edge 12 fc = FC_EDGE12; const FloatV uScale = FDiv(unom, FAdd(unom, udenom)); const Vec3V closest4 = V3ScaleAdd(bc, uScale, b);//V3Add(b, V3Scale(bc, uScale)); const Vec3V vv = V3Sub(p, closest4); closestP = closest4; return V3Dot(vv, vv); } //check if p in edge region of AC //const FloatV vb = FSub(FMul(d5, d2), FMul(d1, d6)); const FloatV vb = V3Dot(n, cCrossA);//edge region of AC, signed area rac, v = S(rca)/S(abc) for b const BoolV con50 = FIsGrtr(zero, vb); const BoolV con51 = FIsGrtrOrEq(d2, zero); const BoolV con52 = FIsGrtr(zero, d6); const BoolV con5 = BAnd(con50, BAnd(con51, con52)); if(BAllEqTTTT(con5)) { //Edge 20 fc = FC_EDGE20; const FloatV tScale = FDiv(d2, FSub(d2, d6)); const Vec3V closest5 = V3ScaleAdd(ac, tScale, a);//V3Add(a, V3Scale(ac, tScale)); const Vec3V vv = V3Sub(p, closest5); closestP = closest5; return V3Dot(vv, vv); } fc = FC_FACE; //P must project inside face region. Compute Q using Barycentric coordinates const FloatV nn = V3Dot(n, n); const FloatV t = FDiv(V3Dot(n, V3Sub(a, p)), nn); const Vec3V vv = V3Scale(n, t); closestP = V3Add(p, vv); return V3Dot(vv, vv); } bool Gu::PCMSphereVsMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds) { const FloatV zero = FZero(); const Vec3V v0 = V3LoadU(verts[0]); const Vec3V v1 = V3LoadU(verts[1]); const Vec3V v2 = V3LoadU(verts[2]); const Vec3V v10 = V3Sub(v1, v0); const Vec3V v20 = V3Sub(v2, v0); const Vec3V n = V3Normalize(V3Cross(v10, v20));//(p1 - p0).cross(p2 - p0).getNormalized(); const FloatV d = V3Dot(v0, n);//d = -p0.dot(n); const FloatV dist0 = FSub(V3Dot(mSphereCenter, n), d);//p.dot(n) + d; // Backface culling if(FAllGrtr(zero, dist0)) return false; Vec3V closestP; //mSphereCenter will be in the local space of the triangle mesh FeatureCode fc; FloatV sqDist = pcmDistancePointTriangleSquared(mSphereCenter, v0, v1, v2, closestP, fc); //sphere overlap with triangles if (FAllGrtr(mSqInflatedSphereRadius, sqDist)) { //sphere center is on the triangle surface, we take triangle normal as the patchNormal. Otherwise, we need to calculate the patchNormal if(fc==FC_FACE) { const Vec3V patchNormal = n; const FloatV dist = FSqrt(sqDist); mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[1])); mEdgeCache.addData(CachedEdge(vertInds[1], vertInds[2])); mEdgeCache.addData(CachedEdge(vertInds[2], vertInds[0])); mVertexCache.addData(CachedVertex(vertInds[0])); mVertexCache.addData(CachedVertex(vertInds[1])); mVertexCache.addData(CachedVertex(vertInds[2])); addToPatch(closestP, patchNormal, dist, triangleIndex); } else { const Vec3V patchNormal = V3Normalize(V3Sub(mSphereCenter, closestP)); //ML : defer the contacts generation const PxU32 nb = sizeof(PCMDeferredPolyData) / sizeof(PxU32); PxU32 newSize = nb + mDeferredContacts->size(); if(mDeferredContacts->capacity() < newSize) mDeferredContacts->reserve(2*(newSize+1)); PCMDeferredPolyData* PX_RESTRICT data = reinterpret_cast<PCMDeferredPolyData*>(mDeferredContacts->end()); mDeferredContacts->forceSize_Unsafe(newSize); SortedTriangle sortedTriangle; sortedTriangle.mSquareDist = sqDist; sortedTriangle.mIndex = mSortedTriangle.size(); mSortedTriangle.pushBack(sortedTriangle); data->mTriangleIndex = triangleIndex; data->mFeatureIndex = fc; data->triFlags32 = PxU32(triFlags); data->mInds[0] = vertInds[0]; data->mInds[1] = vertInds[1]; data->mInds[2] = vertInds[2]; V3StoreU(closestP, data->mVerts[0]); V3StoreU(patchNormal, data->mVerts[1]); V3StoreU(V3Splat(sqDist), data->mVerts[2]); } } return true; } void Gu::PCMSphereVsMeshContactGeneration::addToPatch(const Vec3VArg contactP, const Vec3VArg patchNormal, const FloatV dist, PxU32 triangleIndex) { PX_ASSERT(mNumContactPatch < PCM_MAX_CONTACTPATCH_SIZE); const Vec3V sphereCenter = V3Zero(); // in sphere local space bool foundPatch = false; if (mNumContactPatch > 0) { if (FAllGrtr(V3Dot(mContactPatch[mNumContactPatch - 1].mPatchNormal, patchNormal), mAcceptanceEpsilon)) { PCMContactPatch& patch = mContactPatch[mNumContactPatch - 1]; PX_ASSERT((patch.mEndIndex - patch.mStartIndex) == 1); if (FAllGrtr(patch.mPatchMaxPen, dist)) { //overwrite the old contact mManifoldContacts[patch.mStartIndex].mLocalPointA = sphereCenter;//in sphere's space mManifoldContacts[patch.mStartIndex].mLocalPointB = contactP; mManifoldContacts[patch.mStartIndex].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(patchNormal), dist); mManifoldContacts[patch.mStartIndex].mFaceIndex = triangleIndex; patch.mPatchMaxPen = dist; } foundPatch = true; } } if (!foundPatch) { mManifoldContacts[mNumContacts].mLocalPointA = sphereCenter;//in sphere's space mManifoldContacts[mNumContacts].mLocalPointB = contactP; mManifoldContacts[mNumContacts].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(patchNormal), dist); mManifoldContacts[mNumContacts++].mFaceIndex = triangleIndex; mContactPatch[mNumContactPatch].mStartIndex = mNumContacts - 1; mContactPatch[mNumContactPatch].mEndIndex = mNumContacts; mContactPatch[mNumContactPatch].mPatchMaxPen = dist; mContactPatch[mNumContactPatch++].mPatchNormal = patchNormal; } PX_ASSERT(mNumContactPatch < PCM_MAX_CONTACTPATCH_SIZE); if (mNumContacts >= 16) { PX_ASSERT(mNumContacts <= 64); processContacts(GU_SPHERE_MANIFOLD_CACHE_SIZE); } } void Gu::PCMSphereVsMeshContactGeneration::generateLastContacts() { // Process delayed contacts PxU32 nbSortedTriangle = mSortedTriangle.size(); if (nbSortedTriangle) { PxSort(mSortedTriangle.begin(), mSortedTriangle.size(), PxLess<SortedTriangle>()); const PCMDeferredPolyData* PX_RESTRICT cd = reinterpret_cast<const PCMDeferredPolyData*>(mDeferredContacts->begin()); for (PxU32 i = 0; i < nbSortedTriangle; ++i) { const PCMDeferredPolyData& currentContact = cd[mSortedTriangle[i].mIndex]; const PxU32 ref0 = currentContact.mInds[0]; const PxU32 ref1 = currentContact.mInds[1]; const PxU32 ref2 = currentContact.mInds[2]; //if addData sucessful, which means mEdgeCache doesn't have the edge const bool noEdge01 = mEdgeCache.addData(CachedEdge(ref0, ref1)); const bool noEdge12 = mEdgeCache.addData(CachedEdge(ref1, ref2)); const bool noEdge20 = mEdgeCache.addData(CachedEdge(ref2, ref0)); const bool noVertex0 = mVertexCache.addData(CachedVertex(ref0)); const bool noVertex1 = mVertexCache.addData(CachedVertex(ref1)); const bool noVertex2 = mVertexCache.addData(CachedVertex(ref2)); bool needsProcessing = false; { switch(currentContact.mFeatureIndex) { case FC_VERTEX0: needsProcessing = noVertex0; break; case FC_VERTEX1: needsProcessing = noVertex1; break; case FC_VERTEX2: needsProcessing = noVertex2; break; case FC_EDGE01: needsProcessing = noEdge01; break; case FC_EDGE12: needsProcessing = noEdge12; break; case FC_EDGE20: needsProcessing = noEdge20; break; case FC_FACE: case FC_UNDEFINED: PX_ASSERT(0); // PT: should not be possible break; }; } if (needsProcessing) { //we store the contact, patch normal and sq distance in the vertex memory in PCMDeferredPolyData const Vec3V contactP = V3LoadU(currentContact.mVerts[0]); const Vec3V patchNormal = V3LoadU(currentContact.mVerts[1]); const FloatV sqDist = FLoad(currentContact.mVerts[2].x); const FloatV dist = FSqrt(sqDist); addToPatch(contactP, patchNormal, dist, currentContact.mTriangleIndex); } } } }
17,383
C++
33.629482
174
0.730484
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenBoxConvex.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 "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" #include "GuPCMContactGenUtil.h" #include "foundation/PxVecMath.h" #include "foundation/PxAlloca.h" #include "GuVecCapsule.h" #include "GuVecBox.h" #include "GuEPA.h" #include "geomutils/PxContactBuffer.h" #include "common/PxRenderOutput.h" #define PCM_USE_INTERNAL_OBJECT 1 using namespace physx; using namespace Gu; using namespace aos; //Precompute the convex data // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ static bool testFaceNormal(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, const PxMatTransformV& transform0To1, const PxMatTransformV& transform1To0, const FloatVArg contactDist, FloatV& minOverlap, PxU32& feature, Vec3V& faceNormal, FeatureStatus faceStatus, FeatureStatus& status) { PX_UNUSED(polyData1); FloatV _minOverlap = FMax();//minOverlap; PxU32 _feature = 0; Vec3V _faceNormal = faceNormal; FloatV min0, max0; FloatV min1, max1; const Vec3V center1To0 = transform1To0.p; #if PCM_USE_INTERNAL_OBJECT const Vec3V zeroV = V3Zero(); const Vec3V shapeSpaceCenter1 = V3LoadU(polyData1.mCenter); const Vec3V internalCenter1In0 = transform1To0.transform(shapeSpaceCenter1); const FloatV internalRadius1 = FLoad(polyData1.mInternal.mRadius); const Vec3V internalExtents1 = V3LoadU(polyData1.mInternal.mExtents); const Vec3V negInternalExtents1 = V3Neg(internalExtents1); #endif //in the local space of polyData0 for(PxU32 i=0; i<polyData0.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData0.mPolygons[i]; const Vec3V minVert = V3LoadU(polyData0.mVerts[polygon.mMinIndex]); const FloatV planeDist = FLoad(polygon.mPlane.d); const Vec3V vertexSpacePlaneNormal = V3LoadU(polygon.mPlane.n); //transform plane n to shape space const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(map0->shape2Vertex, vertexSpacePlaneNormal); const FloatV magnitude = FRecip(V3Length(shapeSpacePlaneNormal)); //ML::use this to avoid LHS min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude); max0 = FMul(FNeg(planeDist), magnitude); //normalize shape space normal const Vec3V n0 = V3Scale(shapeSpacePlaneNormal, magnitude); //calculate polyData1 projection //rotate polygon's normal into the local space of polyData1 const Vec3V n1 = transform0To1.rotate(n0); #if PCM_USE_INTERNAL_OBJECT //test internal object //ML: we don't need to transform the normal into the vertex space. If polyData1 don't have scale, //the vertex2Shape matrix will be identity, shape space normal will be the same as vertex space's normal. //If polyData0 have scale, internalExtens1 will be 0. const Vec3V proj = V3Sel(V3IsGrtr(n1, zeroV), internalExtents1, negInternalExtents1); const FloatV radius = FMax(V3Dot(n1, proj), internalRadius1); const FloatV internalTrans = V3Dot(internalCenter1In0, n0); const FloatV _min1 = FSub(internalTrans, radius); const FloatV _max1 = FAdd(internalTrans, radius); const FloatV _min = FMax(min0, _min1); const FloatV _max = FMin(max0, _max1); const FloatV _tempOverlap = FSub(_max, _min); //const FloatV _tempOverlap = FSub(max0, _min1); //Internal object overlaps more than current min, so can skip it //because (a) it isn't a separating axis and (b) it isn't the smallest axis if(FAllGrtr(_tempOverlap, _minOverlap)) continue; #endif const FloatV translate = V3Dot(center1To0, n0); map1->doSupport(n1, min1, max1); min1 = FAdd(translate, min1); max1 = FAdd(translate, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); if(FAllGrtr(_minOverlap, tempOverlap)) { _minOverlap = tempOverlap; _feature = i; _faceNormal = n0; } } if(FAllGrtr(minOverlap, _minOverlap)) { faceNormal = _faceNormal; minOverlap = _minOverlap; status = faceStatus; } feature = _feature; return true; } //plane is in the shape space of polyData static void buildPartialHull(const PolygonalData& polyData, const SupportLocal* map, SeparatingAxes& validAxes, const Vec3VArg planeP, const Vec3VArg planeDir) { const FloatV zero = FZero(); const Vec3V dir = V3Normalize(planeDir); for(PxU32 i=0; i<polyData.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData.mPolygons[i]; const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8; Vec3V v0 = M33MulV3(map->vertex2Shape, V3LoadU_SafeReadW(polyData.mVerts[inds[polygon.mNbVerts - 1]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData FloatV dist0 = V3Dot(dir, V3Sub(v0, planeP)); for (PxU32 iStart = 0; iStart < polygon.mNbVerts; iStart++) { const Vec3V v1 = M33MulV3(map->vertex2Shape, V3LoadU_SafeReadW(polyData.mVerts[inds[iStart]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData const FloatV dist1 = V3Dot(dir, V3Sub(v1, planeP)); const BoolV con = BOr(FIsGrtr(dist0, zero), FIsGrtr(dist1, zero)); //cull edge if either of the vertex will on the positive size of the plane if(BAllEqTTTT(con)) { const Vec3V tempV = V3Sub(v0, v1); PxVec3 temp; V3StoreU(tempV, temp); validAxes.addAxis(temp.getNormalized()); } v0 = v1; dist0 = dist1; } } } static bool testEdgeNormal(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, const PxMatTransformV& transform0To1, const PxMatTransformV& transform1To0, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& edgeNormalIn0, FeatureStatus edgeStatus, FeatureStatus& status) { FloatV overlap = minOverlap; FloatV min0, max0; FloatV min1, max1; const FloatV eps = FEps(); const Vec3V shapeSpaceCenter0 = V3LoadU(polyData0.mCenter); const Vec3V shapeSpaceCenter1 = V3LoadU(polyData1.mCenter); #if PCM_USE_INTERNAL_OBJECT const Vec3V zeroV = V3Zero(); const Vec3V internalCenter1In0 = V3Sub(transform1To0.transform(shapeSpaceCenter1), shapeSpaceCenter0); const FloatV internalRadius1 = FLoad(polyData1.mInternal.mRadius); const Vec3V internalExtents1 = V3LoadU(polyData1.mInternal.mExtents); const Vec3V negInternalExtents1 = V3Neg(internalExtents1); const FloatV internalRadius0 = FLoad(polyData0.mInternal.mRadius); const Vec3V internalExtents0 = V3LoadU(polyData0.mInternal.mExtents); const Vec3V negInternalExtents0 = V3Neg(internalExtents0); #endif const Vec3V center1To0 = transform1To0.p; //in polyData0 shape space const Vec3V dir0 = V3Sub(transform1To0.transform(shapeSpaceCenter1), shapeSpaceCenter0); const Vec3V support0 = map0->doSupport(dir0); //in polyData1 shape space const Vec3V dir1 = transform0To1.rotate(V3Neg(dir0)); const Vec3V support1 = map1->doSupport(dir1); const Vec3V support0In1 = transform0To1.transform(support0); const Vec3V support1In0 = transform1To0.transform(support1); SeparatingAxes mSA0; SeparatingAxes mSA1; mSA0.reset(); mSA1.reset(); buildPartialHull(polyData0, map0, mSA0, support1In0, dir0); buildPartialHull(polyData1, map1, mSA1, support0In1, dir1); const PxVec3* axe0 = mSA0.getAxes(); const PxVec3* axe1 = mSA1.getAxes(); const PxU32 numAxe0 = mSA0.getNumAxes(); const PxU32 numAxe1 = mSA1.getNumAxes(); for(PxU32 i=0; i < numAxe0; ++i) { //axe0[i] is in the shape space of polyData0 const Vec3V v0 = V3LoadU(axe0[i]); for(PxU32 j=0; j< numAxe1; ++j) { //axe1[j] is in the shape space of polyData1 const Vec3V v1 = V3LoadU(axe1[j]); const Vec3V dir = V3Cross(v0, transform1To0.rotate(v1)); const FloatV lenSq = V3Dot(dir, dir); if(FAllGrtr(eps, lenSq)) continue; //n0 is in polyData0's local space const Vec3V n0 = V3Scale(dir, FRsqrt(lenSq)); //n1 is in polyData1's local space const Vec3V n1 = transform0To1.rotate(n0); #if PCM_USE_INTERNAL_OBJECT //ML: we don't need to transform the normal into the vertex space. If polyData1 don't have scale, //the vertex2Shape matrix will be identity, shape space normal will be the same as vertex space's normal. //If polyData0 have scale, internalExtens1 will be 0. //vertex space n1 const Vec3V proj = V3Sel(V3IsGrtr(n1, zeroV), internalExtents1, negInternalExtents1); const FloatV radius = FMax(V3Dot(n1, proj), internalRadius1); const FloatV internalTrans = V3Dot(internalCenter1In0, n0); const FloatV _min1 = FSub(internalTrans, radius); const FloatV _max1 = FAdd(internalTrans, radius); const Vec3V proj0 = V3Sel(V3IsGrtr(n0, zeroV), internalExtents0, negInternalExtents0); const FloatV radius0 = FMax(V3Dot(n0, proj0), internalRadius0); const FloatV _max0 = radius0; const FloatV _min0 = FNeg(radius0); PX_ASSERT(FAllGrtrOrEq(_max0, _min0)); PX_ASSERT(FAllGrtrOrEq(_max1, _min1)); const FloatV _min = FMax(_min0, _min1); const FloatV _max = FMin(_max0, _max1); const FloatV _tempOverlap = FSub(_max, _min); //Internal object overlaps more than current min, so can skip it //because (a) it isn't a separating axis and (b) it isn't the smallest axis if(FAllGrtr(_tempOverlap, overlap)) continue; #endif //get polyData0's projection map0->doSupport(n0, min0, max0); const FloatV translate = V3Dot(center1To0, n0); //get polyData1's projection map1->doSupport(n1, min1, max1); min1 = FAdd(translate, min1); max1 = FAdd(translate, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); #if PCM_USE_INTERNAL_OBJECT PX_ASSERT(FAllGrtrOrEq(tempOverlap, _tempOverlap)); #endif if(FAllGrtr(overlap, tempOverlap)) { overlap = tempOverlap; edgeNormalIn0 = n0; status = edgeStatus; } } } minOverlap = overlap; return true; } //contactNormal is in the space of polyData0 static void generatedContacts(const PolygonalData& polyData0, const PolygonalData& polyData1, const HullPolygonData& referencePolygon, const HullPolygonData& incidentPolygon, const SupportLocal* map0, const SupportLocal* map1, const PxMatTransformV& transform0To1, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, PxRenderOutput* renderOutput) { PX_UNUSED(renderOutput); const FloatV zero = FZero(); const PxU8* inds0 = polyData0.mPolygonVertexRefs + referencePolygon.mVRef8; //transform the plane normal to shape space const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(map0->shape2Vertex, V3LoadU(referencePolygon.mPlane.n))); //this is the matrix transform all points to the 2d plane const Mat33V rot = findRotationMatrixFromZAxis(contactNormal); const PxU8* inds1 = polyData1.mPolygonVertexRefs + incidentPolygon.mVRef8; Vec3V* points0In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16)); Vec3V* points1In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*incidentPolygon.mNbVerts, 16)); bool* points1In0Penetration = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*incidentPolygon.mNbVerts)); FloatV* points1In0TValue = reinterpret_cast<FloatV*>(PxAllocaAligned(sizeof(FloatV)*incidentPolygon.mNbVerts, 16)); //Transform all the verts from vertex space to shape space map0->populateVerts(inds0, referencePolygon.mNbVerts, polyData0.mVerts, points0In0); map1->populateVerts(inds1, incidentPolygon.mNbVerts, polyData1.mVerts, points1In0); #if PCM_LOW_LEVEL_DEBUG PersistentContactManifold::drawPolygon(*renderOutput, map0->transform, points0In0, (PxU32)referencePolygon.mNbVerts, 0x00ff0000); PersistentContactManifold::drawPolygon(*renderOutput, map1->transform, points1In0, (PxU32)incidentPolygon.mNbVerts, 0x0000ff00); #endif //This is used to calculate the project point when the 2D reference face points is inside the 2D incident face point const Vec3V sPoint = points1In0[0]; PX_ASSERT(incidentPolygon.mNbVerts <= 64); Vec3V eps = Vec3V_From_FloatV(FEps()); Vec3V max = Vec3V_From_FloatV(FMax()); Vec3V nmax = V3Neg(max); //transform reference polygon to 2d, calculate min and max Vec3V rPolygonMin= max; Vec3V rPolygonMax = nmax; for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { points0In0[i] = M33MulV3(rot, points0In0[i]); rPolygonMin = V3Min(rPolygonMin, points0In0[i]); rPolygonMax = V3Max(rPolygonMax, points0In0[i]); } rPolygonMin = V3Sub(rPolygonMin, eps); rPolygonMax = V3Add(rPolygonMax, eps); const FloatV d = V3GetZ(points0In0[0]); const FloatV rd = FAdd(d, contactDist); Vec3V iPolygonMin= max; Vec3V iPolygonMax = nmax; PxU32 inside = 0; for(PxU32 i=0; i<incidentPolygon.mNbVerts; ++i) { const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space const Vec3V a = transform0To1.transformInv(vert1); points1In0[i] = M33MulV3(rot, a); const FloatV z = V3GetZ(points1In0[i]); points1In0TValue[i] = FSub(z, d); points1In0[i] = V3SetZ(points1In0[i], d); iPolygonMin = V3Min(iPolygonMin, points1In0[i]); iPolygonMax = V3Max(iPolygonMax, points1In0[i]); if(FAllGrtr(rd, z)) { points1In0Penetration[i] = true; if(contains(points0In0, referencePolygon.mNbVerts, points1In0[i], rPolygonMin, rPolygonMax)) { inside++; if (numContacts == PxContactBuffer::MAX_CONTACTS) return; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), points1In0TValue[i]); manifoldContacts[numContacts].mLocalPointA = vert1; manifoldContacts[numContacts].mLocalPointB = M33TrnspsMulV3(rot, points1In0[i]); manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } } else { points1In0Penetration[i] = false; } } if(inside == incidentPolygon.mNbVerts) return; inside = 0; iPolygonMin = V3Sub(iPolygonMin, eps); iPolygonMax = V3Add(iPolygonMax, eps); const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n))); const Vec3V contactNormalIn1 = transform0To1.rotate(contactNormal); for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { if(contains(points1In0, incidentPolygon.mNbVerts, points0In0[i], iPolygonMin, iPolygonMax)) { //const Vec3V vert0=Vec3V_From_PxVec3(polyData0.mVerts[inds0[i]]); const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]); const Vec3V a = transform0To1.transform(vert0); const FloatV nom = V3Dot(incidentNormal, V3Sub(sPoint, a)); const FloatV denom = V3Dot(incidentNormal, contactNormalIn1); PX_ASSERT(FAllEq(denom, zero)==0); const FloatV t = FDiv(nom, denom); if(FAllGrtr(t, contactDist)) continue; inside++; if (numContacts == PxContactBuffer::MAX_CONTACTS) return; const Vec3V projPoint = V3ScaleAdd(contactNormalIn1, t, a); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), t); manifoldContacts[numContacts].mLocalPointA = projPoint; manifoldContacts[numContacts].mLocalPointB = vert0; manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } } if(inside == referencePolygon.mNbVerts) return; //(2) segment intersection for (PxU32 iStart = 0, iEnd = PxU32(incidentPolygon.mNbVerts - 1); iStart < incidentPolygon.mNbVerts; iEnd = iStart++) { if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd] ) )//|| (points1In0[i].status == POINT_OUTSIDE && points1In0[incidentIndex].status == POINT_OUTSIDE)) continue; const Vec3V ipA = points1In0[iStart]; const Vec3V ipB = points1In0[iEnd]; Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d)); Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d)); const Vec3V iMin = V3Min(ipA, ipB); const Vec3V iMax = V3Max(ipA, ipB); for (PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++) { const Vec3V rpA = points0In0[rStart]; const Vec3V rpB = points0In0[rEnd]; const Vec3V rMin = V3Min(rpA, rpB); const Vec3V rMax = V3Max(rpA, rpB); const BoolV tempCon =BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax)); const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon)); if(BAllEqTTTT(con)) continue; FloatV a1 = signed2DTriArea(rpA, rpB, ipA); FloatV a2 = signed2DTriArea(rpA, rpB, ipB); if(FAllGrtr(zero, FMul(a1, a2))) { FloatV a3 = signed2DTriArea(ipA, ipB, rpA); FloatV a4 = signed2DTriArea(ipA, ipB, rpB); if(FAllGrtr(zero, FMul(a3, a4))) { //these two segment intersect const FloatV t = FDiv(a1, FSub(a2, a1)); const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri); const Vec3V pAA = V3SetZ(pBB, d); const Vec3V pA = M33TrnspsMulV3(rot, pAA); const Vec3V pB = transform0To1.transform(M33TrnspsMulV3(rot, pBB)); const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA)); if(FAllGrtr(pen, contactDist)) continue; if (numContacts == PxContactBuffer::MAX_CONTACTS) return; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), pen); manifoldContacts[numContacts].mLocalPointA = pB; manifoldContacts[numContacts].mLocalPointB = pA; manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } } } } } bool Gu::generateFullContactManifold(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, const Vec3VArg normal, const Vec3VArg closestA, const Vec3VArg closestB, PxReal marginA, PxReal marginB, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength) { const PxMatTransformV transform1To0V = map0->transform.transformInv(map1->transform); const PxMatTransformV transform0To1V = map1->transform.transformInv(map0->transform); if(doOverlapTest) { //if gjk fail, SAT based yes/no test FeatureStatus status = POLYDATA0; FloatV minOverlap = FMax(); Vec3V minNormal = V3Zero(); PxU32 feature0; //in the local space of polyData0, minNormal is in polyData0 space if(!testFaceNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status)) return false; PxU32 feature1; //in the local space of polyData1, if minOverlap is overwrite inside this function, minNormal will be in polyData1 space if(!testFaceNormal(polyData1, polyData0, map1, map0, transform1To0V, transform0To1V, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status)) return false; bool doEdgeTest = false; EdgeTest: if(doEdgeTest) { if(!testEdgeNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, minNormal, EDGE, status)) return false; if(status != EDGE) return true; } if(status == POLYDATA0) { //minNormal is in the local space of polydata0 const HullPolygonData& referencePolygon = polyData0.mPolygons[feature0]; const Vec3V n = transform0To1V.rotate(minNormal); const HullPolygonData& incidentPolygon = polyData1.mPolygons[getPolygonIndex(polyData1, map1, n)]; generatedContacts(polyData0, polyData1, referencePolygon, incidentPolygon, map0, map1, transform0To1V, manifoldContacts, numContacts, contactDist, renderOutput); if (numContacts > 0) { const Vec3V nn = V3Neg(n); //flip the contacts for(PxU32 i=0; i<numContacts; ++i) { const Vec3V localPointB = manifoldContacts[i].mLocalPointB; manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA; manifoldContacts[i].mLocalPointA = localPointB; manifoldContacts[i].mLocalNormalPen = V4SetW(nn, V4GetW(manifoldContacts[i].mLocalNormalPen)); } } } else if(status == POLYDATA1) { //minNormal is in the local space of polydata1 const HullPolygonData& referencePolygon = polyData1.mPolygons[feature1]; const HullPolygonData& incidentPolygon = polyData0.mPolygons[getPolygonIndex(polyData0, map0, transform1To0V.rotate(minNormal))]; //reference face is polyData1 generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist, renderOutput); } else //if(status == EDGE0) { //minNormal is in the local space of polydata0 const HullPolygonData& incidentPolygon = polyData0.mPolygons[getPolygonIndex(polyData0, map0, V3Neg(minNormal))]; const HullPolygonData& referencePolygon = polyData1.mPolygons[getPolygonIndex(polyData1, map1, transform0To1V.rotate(minNormal))]; generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist, renderOutput); } if(numContacts == 0 && !doEdgeTest) { doEdgeTest = true; goto EdgeTest; } } else { const PxReal lowerEps = toleranceLength * PCM_WITNESS_POINT_LOWER_EPS; const PxReal upperEps = toleranceLength * PCM_WITNESS_POINT_UPPER_EPS; const PxReal toleranceA = PxClamp(marginA, lowerEps, upperEps); const PxReal toleranceB = PxClamp(marginB, lowerEps, upperEps); const Vec3V negNormal = V3Neg(normal); const Vec3V normalIn0 = transform0To1V.rotateInv(normal); PxU32 faceIndex1 = getWitnessPolygonIndex(polyData1, map1, negNormal, closestB, toleranceB); PxU32 faceIndex0 = getWitnessPolygonIndex(polyData0, map0, normalIn0, transform0To1V.transformInv(closestA), toleranceA); const HullPolygonData& referencePolygon = polyData1.mPolygons[faceIndex1]; const HullPolygonData& incidentPolygon = polyData0.mPolygons[faceIndex0]; const Vec3V referenceNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(referencePolygon.mPlane.n))); const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map0->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n))); const FloatV referenceProject = FAbs(V3Dot(referenceNormal, negNormal)); const FloatV incidentProject = FAbs(V3Dot(incidentNormal, normalIn0)); if (FAllGrtrOrEq(referenceProject, incidentProject)) { generatedContacts(polyData1, polyData0, referencePolygon, incidentPolygon, map1, map0, transform1To0V, manifoldContacts, numContacts, contactDist, renderOutput); } else { generatedContacts(polyData0, polyData1, incidentPolygon, referencePolygon, map0, map1, transform0To1V, manifoldContacts, numContacts, contactDist, renderOutput); if (numContacts > 0) { const Vec3V n = transform0To1V.rotate(incidentNormal); const Vec3V nn = V3Neg(n); //flip the contacts for (PxU32 i = 0; i<numContacts; ++i) { const Vec3V localPointB = manifoldContacts[i].mLocalPointB; manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA; manifoldContacts[i].mLocalPointA = localPointB; manifoldContacts[i].mLocalNormalPen = V4SetW(nn, V4GetW(manifoldContacts[i].mLocalNormalPen)); } } } } return true; } //This function called by box/convex and convex/convex pcm function bool Gu::addGJKEPAContacts(const GjkConvex* relativeConvex, const GjkConvex* localConvex, const PxMatTransformV& aToB, GjkStatus status, PersistentContact* manifoldContacts, const FloatV replaceBreakingThreshold, const FloatV tolerenceLength, GjkOutput& output, PersistentContactManifold& manifold) { bool doOverlapTest = false; if (status == GJK_DEGENERATE) { const Vec3V normal = output.normal; const FloatV costheta = V3Dot(output.searchDir, normal); if (FAllGrtr(costheta, FLoad(0.9999f))) { const Vec3V centreA = relativeConvex->getCenter(); const Vec3V centreB = localConvex->getCenter(); const Vec3V dir = V3Normalize(V3Sub(centreA, centreB)); const FloatV theta = V3Dot(dir, normal); if (FAllGrtr(theta, FLoad(0.707f))) { addManifoldPoint(manifoldContacts, manifold, output, aToB, replaceBreakingThreshold); } else { doOverlapTest = true; } } else { doOverlapTest = true; } } else if (status == GJK_CONTACT) { addManifoldPoint(manifoldContacts, manifold, output, aToB, replaceBreakingThreshold); } else { PX_ASSERT(status == EPA_CONTACT); status = epaPenetration(*relativeConvex, *localConvex, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, tolerenceLength, output); if (status == EPA_CONTACT) { addManifoldPoint(manifoldContacts, manifold, output, aToB, replaceBreakingThreshold); } else { doOverlapTest = true; } } return doOverlapTest; } bool Gu::computeMTD(const PolygonalData& polyData0, const PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, FloatV& penDepth, Vec3V& normal) { using namespace aos; const PxMatTransformV transform1To0V = map0->transform.transformInv(map1->transform); const PxMatTransformV transform0To1V = map1->transform.transformInv(map0->transform); FeatureStatus status = POLYDATA0; FloatV minOverlap = FMax(); Vec3V minNormal = V3Zero(); const FloatV contactDist = FZero(); PxU32 feature0; //in the local space of polyData0, minNormal is in polyData0 space if(!testFaceNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status)) return false; PxU32 feature1; //in the local space of polyData1, if minOverlap is overwrite inside this function, minNormal will be in polyData1 space if(!testFaceNormal(polyData1, polyData0, map1, map0, transform1To0V, transform0To1V, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status)) return false; if(!testEdgeNormal(polyData0, polyData1, map0, map1, transform0To1V, transform1To0V, contactDist, minOverlap, minNormal, EDGE, status)) return false; penDepth = minOverlap; if(status == POLYDATA1) { //minNormal is in the local space of polydata1 normal = map1->transform.rotate(minNormal); } else { PX_ASSERT(status == POLYDATA0 || status == EDGE); //ML: status == POLYDATA0 or status == EDGE, minNormal is in the local space of polydata0 normal = V3Neg(map0->transform.rotate(minNormal)); } return true; }
28,043
C++
35.754915
248
0.736619
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMTriangleContactGen.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 "GuPCMTriangleContactGen.h" #include "GuPCMContactConvexCommon.h" #include "GuVecTriangle.h" #include "GuBarycentricCoordinates.h" #include "GuConvexEdgeFlags.h" #include "foundation/PxAlloca.h" #if PCM_LOW_LEVEL_DEBUG #include "common/PxRenderBuffer.h" #endif #define EDGE_EDGE_GAUSS_MAP 0 #define BRUTE_FORCE_EDGE_EDGE 0 using namespace physx; using namespace Gu; using namespace aos; static bool testPolyFaceNormal(const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist, FloatV& minOverlap, PxU32& feature, Vec3V& faceNormal, FeatureStatus faceStatus, FeatureStatus& status) { FloatV _minOverlap = FMax(); PxU32 _feature = 0; Vec3V _faceNormal = faceNormal; FloatV min0, max0; FloatV min1, max1; const FloatV eps = FEps(); if(polyMap->isIdentityScale) { //in the local space of polyData0 for(PxU32 i=0; i<polyData.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData.mPolygons[i]; const Vec3V minVert = V3LoadU_SafeReadW(polyData.mVerts[polygon.mMinIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const FloatV planeDist = FLoad(polygon.mPlane.d); //shapeSpace and vertexSpace are the same const Vec3V planeNormal = V3LoadU_SafeReadW(polygon.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class //ML::avoid lHS, don't use the exiting function min0 = V3Dot(planeNormal, minVert); max0 = FNeg(planeDist); triMap->doSupport(planeNormal, min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); if(FAllGrtr(_minOverlap, tempOverlap)) { _minOverlap = tempOverlap; _feature = i; _faceNormal = planeNormal; } } } else { //in the local space of polyData0 for(PxU32 i=0; i<polyData.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData.mPolygons[i]; const Vec3V minVert = V3LoadU_SafeReadW(polyData.mVerts[polygon.mMinIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const FloatV planeDist = FLoad(polygon.mPlane.d); const Vec3V vertexSpacePlaneNormal = V3LoadU_SafeReadW(polygon.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class //transform plane n to shape space const Vec3V shapeSpacePlaneNormal = M33TrnspsMulV3(polyMap->shape2Vertex, vertexSpacePlaneNormal); const FloatV magnitude = FRsqrtFast(V3LengthSq(shapeSpacePlaneNormal)); //FRecip(V3Length(shapeSpacePlaneNormal)); //ML::avoid lHS, don't use the exiting function min0 = FMul(V3Dot(vertexSpacePlaneNormal, minVert), magnitude); max0 = FMul(FNeg(planeDist), magnitude); //normalize the shapeSpacePlaneNormal const Vec3V planeN = V3Scale(shapeSpacePlaneNormal, magnitude); triMap->doSupport(planeN, min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); if(FAllGrtr(_minOverlap, tempOverlap)) { _minOverlap = tempOverlap; _feature = i; _faceNormal = planeN; } } } if(FAllGrtr(minOverlap, FAdd(_minOverlap, eps))) { faceNormal = _faceNormal; minOverlap = _minOverlap; status = faceStatus; } feature = _feature; return true; } //triangle is in the local space of polyData static bool testTriangleFaceNormal(const TriangleV& triangle, const PolygonalData& /*polyData*/, const SupportLocalImpl<TriangleV>* /*triMap*/, const SupportLocal* polyMap, const FloatVArg contactDist, FloatV& minOverlap, PxU32& feature, Vec3V& faceNormal, FeatureStatus faceStatus, FeatureStatus& status) { FloatV min1, max1; const FloatV eps = FEps(); const Vec3V triangleLocNormal = triangle.normal(); const FloatV min0 = V3Dot(triangleLocNormal, triangle.verts[0]); const FloatV max0 = min0; //triangle normal is in the vertex space polyMap->doSupport(triangleLocNormal, min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; minOverlap = FSub(FSub(max0, min1), eps); status = faceStatus; feature = 0; faceNormal = triangleLocNormal; return true; } static bool testPolyEdgeNormal(const TriangleV& triangle, const PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status) { FloatV overlap = minOverlap; FloatV min0, max0; FloatV min1, max1; const FloatV zero = FZero(); const Vec3V eps2 = V3Splat(FLoad(1e-6f)); const Vec3V v0 = M33MulV3(polyMap->shape2Vertex, triangle.verts[0]); const Vec3V v1 = M33MulV3(polyMap->shape2Vertex, triangle.verts[1]); const Vec3V v2 = M33MulV3(polyMap->shape2Vertex, triangle.verts[2]); const TriangleV vertexSpaceTriangle(v0, v1, v2); PxU32 nbTriangleAxes = 0; Vec3V triangleAxes[3]; for(PxI8 kStart = 0, kEnd =2; kStart<3; kEnd = kStart++) { const bool active = (triFlags & (1 << (kEnd+3))) != 0; if(active) { const Vec3V p00 = vertexSpaceTriangle.verts[kStart]; const Vec3V p01 = vertexSpaceTriangle.verts[kEnd]; triangleAxes[nbTriangleAxes++] = V3Sub(p01, p00); } } if(nbTriangleAxes == 0) return true; //create localTriPlane in the vertex space const Vec3V vertexSpaceTriangleNormal = vertexSpaceTriangle.normal(); for(PxU32 i =0; i<polyData.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData.mPolygons[i]; const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8; const Vec3V vertexSpacePlaneNormal = V3LoadU(polygon.mPlane.n); //fast culling. if(FAllGrtr(V3Dot(vertexSpacePlaneNormal, vertexSpaceTriangleNormal), zero)) continue; // Loop through polygon vertices == polygon edges; for(PxU32 lStart = 0, lEnd =PxU32(polygon.mNbVerts-1); lStart<polygon.mNbVerts; lEnd = PxU32(lStart++)) { //in the vertex space const Vec3V p10 = V3LoadU_SafeReadW(polyData.mVerts[inds[lStart]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const Vec3V p11 = V3LoadU_SafeReadW(polyData.mVerts[inds[lEnd]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const Vec3V convexEdge = V3Sub(p11, p10); for(PxU32 j = 0; j < nbTriangleAxes; ++j) { const Vec3V currentPolyEdge = triangleAxes[j]; const Vec3V v = V3Cross(convexEdge, currentPolyEdge); //two edges aren't parallel if((!V3AllGrtr(eps2, V3Abs(v))) && (FAllGrtr(V3Dot(v, vertexSpaceTriangleNormal), zero))) { //transform the v back to the shape space const Vec3V shapeSpaceV = M33TrnspsMulV3(polyMap->shape2Vertex, v); const Vec3V n0 = V3Normalize(shapeSpaceV); triMap->doSupport(n0, min0, max0); polyMap->doSupport(n0, min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap0 = FSub(max0, min1); const FloatV tempOverlap1 = FSub(max1, min0); if(FAllGrtr(overlap, tempOverlap0)) { overlap = tempOverlap0; minNormal = n0; status = edgeStatus; } if(FAllGrtr(overlap, tempOverlap1)) { overlap = tempOverlap1; minNormal = V3Neg(n0); status = edgeStatus; } } } } } minOverlap = overlap; return true; } #if BRUTE_FORCE_EDGE_EDGE static bool testPolyEdgeNormalBruteForce(const TriangleV& triangle, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status) { PX_UNUSED(triFlags); FloatV min0, max0; FloatV min1, max1; FloatV bestDist = FLoad(PX_MAX_F32); Vec3V bestAxis = V3Zero(); const Vec3V eps2 = V3Splat(FLoad(1e-6)); PxU32 bestPolyIndex = 0; PxU32 bestStart = 0; PxU32 bestEnd = 0; PxI8 bestTriStart = 0; PxI8 bestTriEnd = 0; for(PxU32 i =0; i<polyData.mNbPolygons; ++i) { const HullPolygonData& polygon = polyData.mPolygons[i]; const PxU8* inds = polyData.mPolygonVertexRefs + polygon.mVRef8; // Loop through polygon vertices == polygon edges; for(PxU32 lStart = 0, lEnd =PxU32(polygon.mNbVerts-1); lStart<polygon.mNbVerts; lEnd = PxU32(lStart++)) { //in the vertex space const Vec3V p10 = V3LoadU_SafeReadW(polyData.mVerts[inds[lStart]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData const Vec3V p11 = V3LoadU_SafeReadW(polyData.mVerts[inds[lEnd]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData //shape sapce const Vec3V vertex10 = M33MulV3(polyMap->vertex2Shape, p10); const Vec3V vertex11 = M33MulV3(polyMap->vertex2Shape, p11); const Vec3V convexEdge = V3Sub(vertex11, vertex10); for (PxI8 kEnd = 0, kStart = 2; kEnd<3; kStart = kEnd++) { const Vec3V triVert0 = triangle.verts[kStart]; const Vec3V triVert1 = triangle.verts[kEnd]; const Vec3V triangleEdge = V3Sub(triVert1, triVert0); const Vec3V v = V3Cross(convexEdge, triangleEdge); if (!V3AllGrtr(eps2, V3Abs(v))) { //transform the v back to the shape space const Vec3V n0 = V3Normalize(v); triMap->doSupport(n0, min0, max0); polyMap->doSupport(n0, min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if(BAllEqTTTT(con)) return false; const FloatV tempOverlap = FSub(max0, min1); if (FAllGrtr(bestDist, tempOverlap)) { bestDist = tempOverlap; bestAxis = n0; bestPolyIndex = i; bestStart = lStart; bestEnd = lEnd; bestTriStart = kStart; bestTriEnd = kEnd; } } } } } if (FAllGrtr(minOverlap, bestDist)) { minOverlap = bestDist; minNormal = bestAxis; status = edgeStatus; } return true; } static bool testPolyEdgeNormalBruteForceVertsByEdges(const TriangleV& triangle, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* triMap, const SupportLocal* polyMap, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status, PxU32& bestEdgeIndex, PxI8& bestTriStart, PxI8& bestTriEnd) { PX_UNUSED(triFlags); const PxU32 numConvexEdges = polyData.mNbEdges; const PxU16* verticesByEdges16 = polyData.mVerticesByEdges; const PxVec3* vertices = polyData.mVerts; FloatV bestDist = FLoad(PX_MAX_F32); Vec3V bestAxis = V3Zero(); const Vec3V eps2 = V3Splat(FLoad(1e-6)); for (PxU32 convexEdgeIdx = 0; convexEdgeIdx < numConvexEdges; ++convexEdgeIdx) { const PxU16 v0idx1 = verticesByEdges16[convexEdgeIdx * 2]; const PxU32 v1idx1 = verticesByEdges16[convexEdgeIdx * 2 + 1]; //shape sapce const Vec3V vertex10 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v0idx1])); const Vec3V vertex11 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v1idx1])); Vec3V convexEdge = V3Sub(vertex11, vertex10); for (PxI8 kEnd = 0, kStart = 2; kEnd<3; kStart = kEnd++) { const Vec3V triVert0 = triangle.verts[kStart]; const Vec3V triVert1 = triangle.verts[kEnd]; const Vec3V triEdge = V3Sub(triVert1, triVert0); // compute the separation along this axis in vertex space Vec3V axis = V3Cross(convexEdge, triEdge); if (!V3AllGrtr(eps2, V3Abs(axis))) { axis = V3Normalize(axis); FloatV min0, max0; FloatV min1, max1; triMap->doSupport(axis, min0, max0); polyMap->doSupport(axis, min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if (BAllEqTTTT(con)) return false; const FloatV dist0 = FSub(max0, min1); const FloatV dist1 = FSub(max1, min0); if (FAllGrtr(dist0, dist1)) axis = V3Neg(axis); const FloatV dist = FMin(dist0, dist1); if (FAllGrtr(bestDist, dist)) { bestDist = dist; bestAxis = axis; bestEdgeIndex = convexEdgeIdx; bestTriStart = kStart; bestTriEnd = kEnd; } } } } if (FAllGrtr(minOverlap, bestDist)) { minOverlap = bestDist; minNormal = bestAxis; status = edgeStatus; } return true; } #endif #if EDGE_EDGE_GAUSS_MAP static bool isMinkowskiFace(const Vec3V& A, const Vec3V& B, const Vec3V& B_x_A, const Vec3V& C, const Vec3V& D, const Vec3V& D_x_C) { const FloatV zero = FZero(); // Two edges build a face on the Minkowski sum if the associated arcs AB and CD intersect on the Gauss map. // The associated arcs are defined by the adjacent face normals of each edge. const FloatV CBA = V3Dot(C, B_x_A); const FloatV DBA = V3Dot(D, B_x_A); const FloatV ADC = V3Dot(A, D_x_C); const FloatV BDC = V3Dot(B, D_x_C); const BoolV con0 = FIsGrtrOrEq(zero, FMul(CBA, DBA)); const BoolV con1 = FIsGrtrOrEq(zero, FMul(ADC, BDC)); const BoolV con2 = FIsGrtr(FMul(CBA, BDC), zero); const BoolV con = BAnd(con2, BAnd(con0, con1)); return (BAllEqTTTT(con) != 0); //return CBA * DBA < 0.0f && ADC * BDC < 0.0f && CBA * BDC > 0.0f; } #define SAT_VARIFY 0 static bool testPolyEdgeNormalGaussMap(const TriangleV& triangle, PxU8 /*triFlags*/, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* /*triMap*/, const SupportLocal* polyMap, const FloatVArg contactDist, FloatV& minOverlap, Vec3V& minNormal, FeatureStatus edgeStatus, FeatureStatus& status, PxU32& gaussMapBestEdgeIndex, PxI8& gaussMapBestTriStart, PxI8& gaussMapBestTriEnd) { const FloatV zero = FZero(); const Vec3V triNormal = triangle.normal(); const PxU32 numConvexEdges = polyData.mNbEdges; const PxU16* verticesByEdges16 = polyData.mVerticesByEdges; const PxU8* facesByEdges8 = polyData.mFacesByEdges; const PxVec3* vertices = polyData.mVerts; FloatV bestDist = FLoad(-PX_MAX_F32); Vec3V axis = V3Zero(); Vec3V bestAxis = V3Zero(); const Vec3V eps2 = V3Splat(FLoad(1e-6)); //Center is in shape space const Vec3V shapeSpaceCOM = V3LoadU(polyData.mCenter); const Vec3V vertexSpaceCOM = M33MulV3(polyMap->shape2Vertex, shapeSpaceCOM); PxVec3 vertexCOM; V3StoreU(vertexSpaceCOM, vertexCOM); for (PxU32 convexEdgeIdx = 0; convexEdgeIdx < numConvexEdges; ++convexEdgeIdx) { const PxU16 v0idx1 = verticesByEdges16[convexEdgeIdx*2]; const PxU32 v1idx1 = verticesByEdges16[convexEdgeIdx * 2 + 1]; const PxU8 f10 = facesByEdges8[convexEdgeIdx * 2]; const PxU8 f11 = facesByEdges8[convexEdgeIdx * 2 + 1]; //shape sapce const Vec3V vertex10 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v0idx1])); const Vec3V vertex11 = M33MulV3(polyMap->vertex2Shape, V3LoadU(vertices[v1idx1])); Vec3V convexEdge = V3Sub(vertex11, vertex10); const HullPolygonData& face0 = polyData.mPolygons[f10]; const HullPolygonData& face1 = polyData.mPolygons[f11]; const Vec3V convexNormal0 = M33TrnspsMulV3(polyMap->shape2Vertex, V3LoadU(face0.mPlane.n)); const Vec3V convexNormal1 = M33TrnspsMulV3(polyMap->shape2Vertex, V3LoadU(face1.mPlane.n)); float signDist0 = face0.mPlane.distance(vertexCOM); float signDist1 = face1.mPlane.distance(vertexCOM); PX_ASSERT(signDist0 < 0.f); PX_ASSERT(signDist1 < 0.f); for (PxI8 kEnd = 0, kStart = 2; kEnd<3; kStart = kEnd++) { const Vec3V triVert0 = triangle.verts[kStart]; const Vec3V triVert1 = triangle.verts[kEnd]; const Vec3V triEdge = V3Sub(triVert1, triVert0); //if (isMinkowskiFace(convexNormal0, convexNormal1, V3Neg(convexEdge), V3Neg(triNormal), triNormal, V3Neg(triEdge))) if (isMinkowskiFace(convexNormal0, convexNormal1, convexEdge, V3Neg(triNormal), triNormal, triEdge)) { // compute the separation along this axis in vertex space axis = V3Cross(convexEdge, triEdge); if (!V3AllGrtr(eps2, V3Abs(axis))) { axis = V3Normalize(axis); const Vec3V v = V3Sub(vertex10, shapeSpaceCOM); // ensure the axis is outward pointing on the edge on the minkowski sum. Assure normal points from convex hull to triangle const FloatV temp = V3Dot(axis, v); if (FAllGrtr(zero, temp)) axis = V3Neg(axis); //compute the distance from any of the verts in the triangle to plane(axis, vertex10)(n.dot(p-a)) const Vec3V ap = V3Sub(triVert0, vertex10); const FloatV dist = V3Dot(axis, ap); if (FAllGrtr(dist, contactDist)) return false; #if SAT_VARIFY FloatV min0, max0; FloatV min1, max1; triMap->doSupport(V3Neg(axis), min0, max0); polyMap->doSupport(V3Neg(axis), min1, max1); const BoolV con = BOr(FIsGrtr(min1, FAdd(max0, contactDist)), FIsGrtr(min0, FAdd(max1, contactDist))); if (BAllEqTTTT(con)) return false; /*const FloatV dist = FSub(max0, min1); if (FAllGrtr(bestDist, dist)) { bestDist = dist; bestAxis = axis; }*/ const FloatV tempDist = FSub(max0, min1); const FloatV dif = FAbs(FAdd(tempDist, dist)); PX_UNUSED(dif); PX_ASSERT(FAllGrtr(FLoad(1e-4f), dif)); #endif if (FAllGrtr(dist, bestDist)) { bestDist = dist; bestAxis = axis; gaussMapBestEdgeIndex = convexEdgeIdx; gaussMapBestTriStart = kStart; gaussMapBestTriEnd = kEnd; } } } } } if (FAllGrtr(minOverlap, bestDist)) { minOverlap = bestDist; minNormal = bestAxis; status = edgeStatus; } return true; } #endif static PX_FORCE_INLINE PxU32 addMeshContacts(MeshPersistentContact* manifoldContacts, const Vec3V& pA, const Vec3V& pB, const Vec4V& normalPen, PxU32 triangleIndex, PxU32 numContacts) { manifoldContacts[numContacts].mLocalPointA = pA; manifoldContacts[numContacts].mLocalPointB = pB; manifoldContacts[numContacts].mLocalNormalPen = normalPen; manifoldContacts[numContacts].mFaceIndex = triangleIndex; return numContacts+1; } static void generatedTriangleContacts(const TriangleV& triangle, PxU32 triangleIndex, PxU8/* _triFlags*/, const PolygonalData& polyData1, const HullPolygonData& incidentPolygon, const SupportLocal* map1, MeshPersistentContact* manifoldContacts, PxU32& numManifoldContacts, const FloatVArg contactDist, const Vec3VArg contactNormal, PxRenderOutput* renderOutput) { PX_UNUSED(renderOutput); //PxU8 triFlags = _triFlags; const PxU32 previousContacts = numManifoldContacts; const FloatV zero = FZero(); const Mat33V rot = findRotationMatrixFromZAxis(contactNormal); const PxU8* inds1 = polyData1.mPolygonVertexRefs + incidentPolygon.mVRef8; Vec3V points0In0[3]; Vec3V* points1In0 = reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*incidentPolygon.mNbVerts, 16)); FloatV* points1In0TValue = reinterpret_cast<FloatV*>(PxAllocaAligned(sizeof(FloatV)*incidentPolygon.mNbVerts, 16)); bool* points1In0Penetration = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*incidentPolygon.mNbVerts)); points0In0[0] = triangle.verts[0]; points0In0[1] = triangle.verts[1]; points0In0[2] = triangle.verts[2]; //Transform all the verts from vertex space to shape space map1->populateVerts(inds1, incidentPolygon.mNbVerts, polyData1.mVerts, points1In0); #if PCM_LOW_LEVEL_DEBUG PersistentContactManifold::drawPolygon(*renderOutput, map1->transform, points1In0, incidentPolygon.mNbVerts, (PxU32)PxDebugColor::eARGB_RED); //PersistentContactManifold::drawTriangle(*renderOutput, map1->transform.transform(points1In0[0]), map1->transform.transform(points0In0[1]), map1->transform.transform(points0In0[2]), (PxU32)PxDebugColor::eARGB_BLUE); #endif Vec3V eps = Vec3V_From_FloatV(FEps()); Vec3V max = Vec3V_From_FloatV(FMax()); Vec3V nmax = V3Neg(max); //transform reference polygon to 2d, calculate min and max Vec3V rPolygonMin= max; Vec3V rPolygonMax = nmax; for(PxU32 i=0; i<3; ++i) { points0In0[i] = M33MulV3(rot, points0In0[i]); rPolygonMin = V3Min(rPolygonMin, points0In0[i]); rPolygonMax = V3Max(rPolygonMax, points0In0[i]); } rPolygonMin = V3Sub(rPolygonMin, eps); rPolygonMax = V3Add(rPolygonMax, eps); const FloatV d = V3GetZ(points0In0[0]); const FloatV rd = FAdd(d, contactDist); Vec3V iPolygonMin= max; Vec3V iPolygonMax = nmax; PxU32 inside = 0; for(PxU32 i=0; i<incidentPolygon.mNbVerts; ++i) { const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space points1In0[i] = M33MulV3(rot, vert1); const FloatV z = V3GetZ(points1In0[i]); points1In0TValue[i] = FSub(z, d); points1In0[i] = V3SetZ(points1In0[i], d); iPolygonMin = V3Min(iPolygonMin, points1In0[i]); iPolygonMax = V3Max(iPolygonMax, points1In0[i]); bool penetrated = false; if(FAllGrtr(rd, z)) { penetrated = true; if(contains(points0In0, 3, points1In0[i], rPolygonMin, rPolygonMax)) { inside++; //add this contact to the buffer const FloatV t = V3Dot(contactNormal, V3Sub(triangle.verts[0], vert1)); const Vec3V projectPoint = V3ScaleAdd(contactNormal, t, vert1); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), FNeg(t)); numManifoldContacts = addMeshContacts(manifoldContacts, vert1, projectPoint, localNormalPen, triangleIndex, numManifoldContacts); //if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction const PxU32 numContacts = numManifoldContacts - previousContacts; if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { //a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce //the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(6) points SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts); numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } } } points1In0Penetration[i] = penetrated; } if(inside == incidentPolygon.mNbVerts) return; inside = 0; iPolygonMin = V3Sub(iPolygonMin, eps); iPolygonMax = V3Add(iPolygonMax, eps); const Vec3V incidentNormal = V3Normalize(M33TrnspsMulV3(map1->shape2Vertex, V3LoadU(incidentPolygon.mPlane.n))); const FloatV iPlaneD = V3Dot(incidentNormal, M33MulV3(map1->vertex2Shape, V3LoadU(polyData1.mVerts[inds1[0]]))); for(PxU32 i=0; i<3; ++i) { if(contains(points1In0, incidentPolygon.mNbVerts, points0In0[i], iPolygonMin, iPolygonMax)) { inside++; const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]); const FloatV t = FSub(V3Dot(incidentNormal, vert0), iPlaneD); if(FAllGrtr(t, contactDist)) continue; const Vec3V projPoint = V3NegScaleSub(incidentNormal, t, vert0); const Vec3V v = V3Sub(projPoint, vert0); const FloatV t3 = V3Dot(v, contactNormal); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), t3); numManifoldContacts = addMeshContacts(manifoldContacts, projPoint, vert0, localNormalPen, triangleIndex, numManifoldContacts); //if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction const PxU32 numContacts = numManifoldContacts - previousContacts; if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { //a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce //the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts); numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } } } if(inside == 3) return; //(2) segment intersection for(PxU32 rStart = 0, rEnd = 2; rStart < 3; rEnd = rStart++) { const Vec3V rpA = points0In0[rStart]; const Vec3V rpB = points0In0[rEnd]; const Vec3V rMin = V3Min(rpA, rpB); const Vec3V rMax = V3Max(rpA, rpB); for(PxU32 iStart = 0, iEnd = PxU32(incidentPolygon.mNbVerts - 1); iStart < incidentPolygon.mNbVerts; iEnd = iStart++) { if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd]))//|| (points1In0[i].status == POINT_OUTSIDE && points1In0[incidentIndex].status == POINT_OUTSIDE)) continue; const Vec3V ipA = points1In0[iStart]; const Vec3V ipB = points1In0[iEnd]; const Vec3V iMin = V3Min(ipA, ipB); const Vec3V iMax = V3Max(ipA, ipB); const BoolV tempCon = BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax)); const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon)); if(BAllEqTTTT(con)) continue; const FloatV a1 = signed2DTriArea(rpA, rpB, ipA); const FloatV a2 = signed2DTriArea(rpA, rpB, ipB); if(FAllGrtr(zero, FMul(a1, a2))) { const FloatV a3 = signed2DTriArea(ipA, ipB, rpA); const FloatV a4 = signed2DTriArea(ipA, ipB, rpB); if(FAllGrtr(zero, FMul(a3, a4))) { //these two segment intersect in 2d const FloatV t = FMul(a1, FRecip(FSub(a2, a1))); const Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d)); const Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d)); const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri); const Vec3V pAA = V3SetZ(pBB, d); const Vec3V pA = M33TrnspsMulV3(rot, pAA); const Vec3V pB = M33TrnspsMulV3(rot, pBB); const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA)); if(FAllGrtr(pen, contactDist)) continue; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(contactNormal), pen); numManifoldContacts = addMeshContacts(manifoldContacts, pB, pA, localNormalPen, triangleIndex, numManifoldContacts); //if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction const PxU32 numContacts = numManifoldContacts - previousContacts; if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { //a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce //the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts); numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } } } } } } static void generatedPolyContacts(const PolygonalData& polyData0, const HullPolygonData& referencePolygon, const TriangleV& triangle, PxU32 triangleIndex, PxU8 triFlags, const SupportLocal* map0, MeshPersistentContact* manifoldContacts, PxU32& numManifoldContacts, const FloatVArg contactDist, const Vec3VArg contactNormal, PxRenderOutput* renderOutput) { PX_UNUSED(triFlags); PX_UNUSED(renderOutput); const FloatV zero = FZero(); const PxU32 previousContacts = numManifoldContacts; const PxU8* inds0 = polyData0.mPolygonVertexRefs + referencePolygon.mVRef8; const Vec3V nContactNormal = V3Neg(contactNormal); //this is the matrix transform all points to the 2d plane const Mat33V rot = findRotationMatrixFromZAxis(contactNormal); Vec3V* points0In0=reinterpret_cast<Vec3V*>(PxAllocaAligned(sizeof(Vec3V)*referencePolygon.mNbVerts, 16)); Vec3V points1In0[3]; FloatV points1In0TValue[3]; bool points1In0Penetration[3] = { false, false, false }; //Transform all the verts from vertex space to shape space map0->populateVerts(inds0, referencePolygon.mNbVerts, polyData0.mVerts, points0In0); points1In0[0] = triangle.verts[0]; points1In0[1] = triangle.verts[1]; points1In0[2] = triangle.verts[2]; #if PCM_LOW_LEVEL_DEBUG PersistentContactManifold::drawPolygon(*renderOutput, map0->transform, points0In0, referencePolygon.mNbVerts, (PxU32)PxDebugColor::eARGB_GREEN); //PersistentContactManifold::drawTriangle(*gRenderOutPut, map0->transform.transform(points1In0[0]), map0->transform.transform(points1In0[1]), map0->transform.transform(points1In0[2]), (PxU32)PxDebugColor::eARGB_BLUE); #endif //the first point in the reference plane const Vec3V referencePoint = points0In0[0]; Vec3V eps = Vec3V_From_FloatV(FEps()); Vec3V max = Vec3V_From_FloatV(FMax()); Vec3V nmax = V3Neg(max); //transform reference polygon to 2d, calculate min and max Vec3V rPolygonMin= max; Vec3V rPolygonMax = nmax; for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { //points0In0[i].vertext = M33TrnspsMulV3(rot, Vec3V_From_PxVec3(polyData0.mVerts[inds0[i]])); points0In0[i] = M33MulV3(rot, points0In0[i]); rPolygonMin = V3Min(rPolygonMin, points0In0[i]); rPolygonMax = V3Max(rPolygonMax, points0In0[i]); } rPolygonMin = V3Sub(rPolygonMin, eps); rPolygonMax = V3Add(rPolygonMax, eps); const FloatV d = V3GetZ(points0In0[0]); const FloatV rd = FAdd(d, contactDist); Vec3V iPolygonMin= max; Vec3V iPolygonMax = nmax; PxU32 inside = 0; for(PxU32 i=0; i<3; ++i) { const Vec3V vert1 =points1In0[i]; //this still in polyData1's local space points1In0[i] = M33MulV3(rot, vert1); const FloatV z = V3GetZ(points1In0[i]); points1In0TValue[i] = FSub(z, d); points1In0[i] = V3SetZ(points1In0[i], d); iPolygonMin = V3Min(iPolygonMin, points1In0[i]); iPolygonMax = V3Max(iPolygonMax, points1In0[i]); if(FAllGrtr(rd, z)) { points1In0Penetration[i] = true; //ML : check to see whether all the points of triangles in 2D space are within reference polygon's range if(contains(points0In0, referencePolygon.mNbVerts, points1In0[i], rPolygonMin, rPolygonMax)) { inside++; //calculate projection point const FloatV t = V3Dot(contactNormal, V3Sub(vert1, referencePoint)); const Vec3V projectPoint = V3NegScaleSub(contactNormal, t, vert1); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(nContactNormal), t); numManifoldContacts = addMeshContacts(manifoldContacts, projectPoint, vert1, localNormalPen, triangleIndex, numManifoldContacts); //if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction const PxU32 numContacts = numManifoldContacts - previousContacts; if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { //a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce //the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts); numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } } } } if(inside == 3) return; inside = 0; iPolygonMin = V3Sub(iPolygonMin, eps); iPolygonMax = V3Add(iPolygonMax, eps); const Vec3V incidentNormal = triangle.normal(); const FloatV iPlaneD = V3Dot(incidentNormal, triangle.verts[0]); const FloatV one = FOne(); for(PxU32 i=0; i<referencePolygon.mNbVerts; ++i) { if(contains(points1In0, 3, points0In0[i], iPolygonMin, iPolygonMax)) { const Vec3V vert0 = M33TrnspsMulV3(rot, points0In0[i]); const FloatV t = FSub(V3Dot(incidentNormal, vert0), iPlaneD); if(FAllGrtr(t, contactDist)) continue; const Vec3V projPoint = V3NegScaleSub(incidentNormal, t, vert0); FloatV u, w; barycentricCoordinates(projPoint, triangle.verts[0], triangle.verts[1], triangle.verts[2], u, w); const BoolV con = BAnd(FIsGrtrOrEq(u, zero), BAnd(FIsGrtrOrEq(w, zero), FIsGrtrOrEq(one, FAdd(u, w)))); if(BAllEqTTTT(con)) { inside++; const Vec3V v = V3Sub(projPoint, vert0); const FloatV t3 = V3Dot(v, contactNormal); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(nContactNormal), t3); numManifoldContacts = addMeshContacts(manifoldContacts, vert0, projPoint, localNormalPen, triangleIndex, numManifoldContacts); //if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction const PxU32 numContacts = numManifoldContacts - previousContacts; if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { //a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce //the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts); numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } } } } if(inside == referencePolygon.mNbVerts) return; //Always generate segment contacts //(2) segment intersection for(PxU32 iStart = 0, iEnd = 2; iStart < 3; iEnd = iStart++) { if((!points1In0Penetration[iStart] && !points1In0Penetration[iEnd] ) ) continue; const Vec3V ipA = points1In0[iStart]; const Vec3V ipB = points1In0[iEnd]; const Vec3V iMin = V3Min(ipA, ipB); const Vec3V iMax = V3Max(ipA, ipB); for(PxU32 rStart = 0, rEnd = PxU32(referencePolygon.mNbVerts - 1); rStart < referencePolygon.mNbVerts; rEnd = rStart++) { const Vec3V rpA = points0In0[rStart]; const Vec3V rpB = points0In0[rEnd]; const Vec3V rMin = V3Min(rpA, rpB); const Vec3V rMax = V3Max(rpA, rpB); const BoolV tempCon = BOr(V3IsGrtr(iMin, rMax), V3IsGrtr(rMin, iMax)); const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon)); if(BAllEqTTTT(con)) continue; const FloatV a1 = signed2DTriArea(rpA, rpB, ipA); const FloatV a2 = signed2DTriArea(rpA, rpB, ipB); if(FAllGrtr(zero, FMul(a1, a2))) { const FloatV a3 = signed2DTriArea(ipA, ipB, rpA); const FloatV a4 = signed2DTriArea(ipA, ipB, rpB); if(FAllGrtr(zero, FMul(a3, a4))) { //these two segment intersect const FloatV t = FMul(a1, FRecip(FSub(a2, a1))); const Vec3V ipAOri = V3SetZ(points1In0[iStart], FAdd(points1In0TValue[iStart], d)); const Vec3V ipBOri = V3SetZ(points1In0[iEnd], FAdd(points1In0TValue[iEnd], d)); const Vec3V pBB = V3NegScaleSub(V3Sub(ipBOri, ipAOri), t, ipAOri); const Vec3V pAA = V3SetZ(pBB, d); const Vec3V pA = M33TrnspsMulV3(rot, pAA); const Vec3V pB = M33TrnspsMulV3(rot, pBB); const FloatV pen = FSub(V3GetZ(pBB), V3GetZ(pAA)); if(FAllGrtr(pen, contactDist)) continue; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(nContactNormal), pen); numManifoldContacts = addMeshContacts(manifoldContacts, pA, pB, localNormalPen, triangleIndex, numManifoldContacts); //if the numContacts are more than GU_MESH_CONTACT_REDUCTION_THRESHOLD, we need to do contact reduction const PxU32 numContacts = numManifoldContacts - previousContacts; if(numContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { //a polygon has more than GU_MESH_CONTACT_REDUCTION_THRESHOLD(16) contacts with this triangle, we will reduce //the contacts to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points SinglePersistentContactManifold::reduceContacts(&manifoldContacts[previousContacts], numContacts); numManifoldContacts = previousContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } } } } } } bool Gu::PCMConvexVsMeshContactGeneration::generateTriangleFullContactManifold(const TriangleV& localTriangle, PxU32 triangleIndex, const PxU32* triIndices, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* localTriMap, const SupportLocal* polyMap, MeshPersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& patchNormal) { FeatureStatus status = POLYDATA0; FloatV minOverlap = FMax(); //minNormal will be in the local space of polyData Vec3V minNormal = V3Zero(); PxU32 feature0; if(!testTriangleFaceNormal(localTriangle, polyData, localTriMap, polyMap, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status)) return false; PxU32 feature1; if(!testPolyFaceNormal(polyData, localTriMap, polyMap, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status)) return false; if(!testPolyEdgeNormal(localTriangle, triFlags, polyData, localTriMap, polyMap, contactDist, minOverlap, minNormal, EDGE, status)) return false; const Vec3V triNormal = localTriangle.normal(); if(status == POLYDATA0) { //minNormal is the triangle normal and it is in the local space of polydata0 PxI32 index2; PxI32 polyIndex = getPolygonIndex(polyData, polyMap, minNormal, index2); const HullPolygonData& referencePolygon = polyData.mPolygons[polyIndex]; patchNormal = triNormal; generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, referencePolygon, polyMap, manifoldContacts, numContacts, contactDist, triNormal, mRenderOutput); if(index2 != -1) { generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, polyData.mPolygons[index2], polyMap, manifoldContacts, numContacts, contactDist, triNormal, mRenderOutput); } } else { if(status == POLYDATA1) { const HullPolygonData* referencePolygon = &polyData.mPolygons[feature1]; const FloatV cosTheta = V3Dot(V3Neg(minNormal), triNormal); const FloatV threshold = FLoad(0.707106781f);//about 45 degree0 if(FAllGrtr(cosTheta, threshold)) { patchNormal = triNormal; generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, *referencePolygon, polyMap, manifoldContacts, numContacts, contactDist, triNormal, mRenderOutput); } else { //ML : defer the contacts generation if(mSilhouetteEdgesAreActive || !(triFlags & (ETD_SILHOUETTE_EDGE_01 | ETD_SILHOUETTE_EDGE_12 | ETD_SILHOUETTE_EDGE_20))) { const PxU32 nb = sizeof(PCMDeferredPolyData) / sizeof(PxU32); PxU32 newSize = nb + mDeferredContacts->size(); if(mDeferredContacts->capacity() < newSize) mDeferredContacts->reserve((newSize+1)*2); PCMDeferredPolyData* PX_RESTRICT data = reinterpret_cast<PCMDeferredPolyData*>(mDeferredContacts->end()); mDeferredContacts->forceSize_Unsafe(newSize); data->mTriangleIndex = triangleIndex; data->mFeatureIndex = feature1; data->triFlags32 = PxU32(triFlags); data->mInds[0] = triIndices[0]; data->mInds[1] = triIndices[1]; data->mInds[2] = triIndices[2]; V3StoreU(localTriangle.verts[0], data->mVerts[0]); V3StoreU(localTriangle.verts[1], data->mVerts[1]); V3StoreU(localTriangle.verts[2], data->mVerts[2]); } return true; } } else { PxI32 index2; feature1 = PxU32(getPolygonIndex(polyData, polyMap, minNormal, index2)); const HullPolygonData* referencePolygon = &polyData.mPolygons[feature1]; const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(polyMap->shape2Vertex, V3LoadU(referencePolygon->mPlane.n))); const Vec3V nContactNormal = V3Neg(contactNormal); //if the minimum sperating axis is edge case, we don't defer it because it is an activeEdge patchNormal = nContactNormal; generatedPolyContacts(polyData, *referencePolygon, localTriangle, triangleIndex, triFlags, polyMap, manifoldContacts, numContacts, contactDist, contactNormal, mRenderOutput); } } return true; } bool Gu::PCMConvexVsMeshContactGeneration::generateTriangleFullContactManifold(const TriangleV& localTriangle, PxU32 triangleIndex, PxU8 triFlags, const PolygonalData& polyData, const SupportLocalImpl<TriangleV>* localTriMap, const SupportLocal* polyMap, MeshPersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& patchNormal, PxRenderOutput* renderOutput) { const FloatV threshold = FLoad(0.7071f);//about 45 degree PX_UNUSED(threshold); { FeatureStatus status = POLYDATA0; FloatV minOverlap = FMax(); //minNormal will be in the local space of polyData Vec3V minNormal = V3Zero(); PxU32 feature0; if(!testTriangleFaceNormal(localTriangle, polyData, localTriMap, polyMap, contactDist, minOverlap, feature0, minNormal, POLYDATA0, status)) return false; PxU32 feature1; if(!testPolyFaceNormal(polyData, localTriMap, polyMap, contactDist, minOverlap, feature1, minNormal, POLYDATA1, status)) return false; if(!testPolyEdgeNormal(localTriangle, triFlags, polyData, localTriMap, polyMap, contactDist, minOverlap, minNormal, EDGE, status)) return false; const Vec3V triNormal = localTriangle.normal(); patchNormal = triNormal; const HullPolygonData* referencePolygon = &polyData.mPolygons[getPolygonIndex(polyData, polyMap, triNormal)]; generatedTriangleContacts(localTriangle, triangleIndex, triFlags, polyData, *referencePolygon, polyMap, manifoldContacts, numContacts, contactDist, triNormal, renderOutput); } return true; } bool Gu::PCMConvexVsMeshContactGeneration::generatePolyDataContactManifold(const TriangleV& localTriangle, PxU32 featureIndex, PxU32 triangleIndex, PxU8 triFlags, MeshPersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist, Vec3V& patchNormal) { const HullPolygonData* referencePolygon = &mPolyData.mPolygons[featureIndex]; const Vec3V contactNormal = V3Normalize(M33TrnspsMulV3(mPolyMap->shape2Vertex, V3LoadU(referencePolygon->mPlane.n))); const Vec3V nContactNormal = V3Neg(contactNormal); patchNormal = nContactNormal; generatedPolyContacts(mPolyData, *referencePolygon, localTriangle, triangleIndex, triFlags, mPolyMap, manifoldContacts, numContacts, contactDist, contactNormal, mRenderOutput); return true; }
43,008
C++
36.108714
340
0.729887
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereCapsule.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 "geomutils/PxContactBuffer.h" #include "GuVecSphere.h" #include "GuVecCapsule.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGenUtil.h" using namespace physx; using namespace aos; static PX_FORCE_INLINE FloatV distancePointSegmentSquared(const Vec3VArg a, const Vec3VArg b, const Vec3VArg p, FloatV& param) { const FloatV zero = FZero(); const FloatV one = FOne(); const Vec3V ap = V3Sub(p, a); const Vec3V ab = V3Sub(b, a); const FloatV nom = V3Dot(ap, ab); const FloatV denom = V3Dot(ab, ab); const FloatV tValue = FClamp(FDiv(nom, denom), zero, one); const FloatV t = FSel(FIsEq(denom, zero), zero, tValue); const Vec3V v = V3NegScaleSub(ab, t, ap); param = t; return V3Dot(v, v); } bool Gu::pcmContactSphereCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape1); //Sphere in world space const Vec3V sphereCenter = V3LoadA(&transform0.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV sphereRadius = FLoad(shapeSphere.radius); const FloatV capsuleRadius = FLoad(shapeCapsule.radius); const FloatV cDist = FLoad(params.mContactDistance); //const FloatV r0 = FloatV_From_F32(shapeCapsule.radius); const FloatV halfHeight0 = FLoad(shapeCapsule.halfHeight); const Vec3V basisVector0 = QuatGetBasisVector0(q1); const Vec3V tmp0 = V3Scale(basisVector0, halfHeight0); const Vec3V s = V3Add(p1, tmp0); const Vec3V e = V3Sub(p1, tmp0); const FloatV radiusSum = FAdd(sphereRadius, capsuleRadius); const FloatV inflatedSum = FAdd(radiusSum, cDist); // Collision detection FloatV t; const FloatV squareDist = distancePointSegmentSquared(s, e, sphereCenter, t); const FloatV sqInflatedSum = FMul(inflatedSum, inflatedSum); if(FAllGrtr(sqInflatedSum, squareDist))//BAllEq(con, bTrue)) { const Vec3V p = V3ScaleAdd(V3Sub(e, s), t, s); const Vec3V dir = V3Sub(sphereCenter, p); const Vec3V normal = V3NormalizeSafe(dir, V3UnitX()); const Vec3V point = V3NegScaleSub(normal, sphereRadius, sphereCenter);//transform back to the world space const FloatV dist = FSub(FSqrt(squareDist), radiusSum); //context.mContactBuffer.contact(point, normal, FSub(FSqrt(squareDist), radiusSum)); return outputSimplePCMContact(contactBuffer, point, normal, dist); } return false; }
4,174
C++
39.53398
126
0.756349
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxTriangleMesh.h" #include "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuVecConvexHull.h" #include "GuVecConvexHullNoScale.h" #include "GuVecTriangle.h" #include "GuContactMethodImpl.h" #include "GuPCMShapeConvex.h" #include "GuConvexUtilsInternal.h" #include "GuPCMContactConvexCommon.h" #include "GuPCMContactMeshCallback.h" #include "GuIntersectionTriangleBox.h" #include "GuBox.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace aos; namespace { struct PCMConvexVsMeshContactGenerationCallback : PCMMeshContactGenerationCallback<PCMConvexVsMeshContactGenerationCallback> { PCMConvexVsMeshContactGenerationCallback& operator=(const PCMConvexVsMeshContactGenerationCallback&); PCMConvexVsMeshContactGeneration mGeneration; const BoxPadded& mBox; PCMConvexVsMeshContactGenerationCallback( const FloatVArg contactDistance, const FloatVArg replaceBreakingThreshold, const PxTransformV& convexTransform, const PxTransformV& meshTransform, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, const PolygonalData& polyData, const SupportLocal* polyMap, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* delayedContacts, const FastVertex2ShapeScaling& convexScaling, bool idtConvexScale, const FastVertex2ShapeScaling& meshScaling, const PxU8* extraTriData, bool idtMeshScale, bool silhouetteEdgesAreActive, const BoxPadded& box, PxRenderOutput* renderOutput = NULL ) : PCMMeshContactGenerationCallback<PCMConvexVsMeshContactGenerationCallback>(meshScaling, extraTriData, idtMeshScale), mGeneration(contactDistance, replaceBreakingThreshold, convexTransform, meshTransform, multiManifold, contactBuffer, polyData, polyMap, delayedContacts, convexScaling, idtConvexScale, silhouetteEdgesAreActive, renderOutput), mBox(box) { } PX_FORCE_INLINE PxIntBool doTest(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2) { // PT: this one is safe because midphase vertices are directly passed to the function return intersectTriangleBox(mBox, v0, v1, v2); } template<PxU32 CacheSize> void processTriangleCache(TriangleCache<CacheSize>& cache) { mGeneration.processTriangleCache<CacheSize, PCMConvexVsMeshContactGeneration>(cache); } }; } bool Gu::PCMContactConvexMesh(const PolygonalData& polyData, const SupportLocal* polyMap, const FloatVArg minMargin, const PxBounds3& hullAABB, const PxTriangleMeshGeometry& shapeMesh, const PxTransform& transform0, const PxTransform& transform1, PxReal contactDistance, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& convexScaling, const FastVertex2ShapeScaling& meshScaling, bool idtConvexScale, bool idtMeshScale, MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput) { const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&transform0.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV contactDist = FLoad(contactDistance); //Transfer A into the local space of B const PxTransformV convexTransform(p0, q0);//box const PxTransformV meshTransform(p1, q1);//triangleMesh const PxTransformV curTransform = meshTransform.transformInv(convexTransform); if(multiManifold.invalidate(curTransform, minMargin)) { const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f)); multiManifold.mNumManifolds = 0; multiManifold.setRelativeTransform(curTransform); //////////////////// const TriangleMesh* PX_RESTRICT meshData = _getMeshData(shapeMesh); const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); BoxPadded hullOBB; computeHullOBB(hullOBB, hullAABB, contactDistance, world0, world1, meshScaling, idtMeshScale); // Setup the collider PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts; const PxU8* PX_RESTRICT extraData = meshData->getExtraTrigData(); PCMConvexVsMeshContactGenerationCallback blockCallback( contactDist, replaceBreakingThreshold, convexTransform, meshTransform, multiManifold, contactBuffer, polyData, polyMap, &delayedContacts, convexScaling, idtConvexScale, meshScaling, extraData, idtMeshScale, true, hullOBB, renderOutput); Midphase::intersectOBB(meshData, hullOBB, blockCallback, true); PX_ASSERT(multiManifold.mNumManifolds <= GU_MAX_MANIFOLD_SIZE); blockCallback.flushCache(); //This is very important blockCallback.mGeneration.generateLastContacts(); blockCallback.mGeneration.processContacts(GU_SINGLE_MANIFOLD_CACHE_SIZE, false); #if PCM_LOW_LEVEL_DEBUG multiManifold.drawManifold(*renderOutput, transform0, transform1); #endif } else { const PxMatTransformV aToB(curTransform); const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f)); multiManifold.refreshManifold(aToB, projectBreakingThreshold, contactDist); } return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, meshTransform); } bool Gu::pcmContactConvexMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); const ConvexHullData* hullData = _getHullData(shapeConvex); MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const PxTransformV convexTransform = loadTransformA(transform0); const bool idtScaleMesh = shapeMesh.scale.isIdentity(); FastVertex2ShapeScaling meshScaling; if(!idtScaleMesh) meshScaling.init(shapeMesh.scale); FastVertex2ShapeScaling convexScaling; PxBounds3 hullAABB; PolygonalData polyData; const bool idtScaleConvex = getPCMConvexData(shapeConvex, convexScaling, hullAABB, polyData); const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const PxReal toleranceScale = params.mToleranceLength; const FloatV minMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceScale, GU_PCM_MESH_MANIFOLD_EPSILON); const ConvexHullV convexHull(hullData, V3Zero(), vScale, vQuat, idtScaleConvex); if(idtScaleConvex) { SupportLocalImpl<ConvexHullNoScaleV> convexMap(static_cast<const ConvexHullNoScaleV&>(convexHull), convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, true); return PCMContactConvexMesh(polyData, &convexMap, minMargin, hullAABB, shapeMesh, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling, meshScaling, idtScaleConvex, idtScaleMesh, multiManifold, renderOutput); } else { SupportLocalImpl<ConvexHullV> convexMap(convexHull, convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, false); return PCMContactConvexMesh(polyData, &convexMap, minMargin, hullAABB, shapeMesh, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling, meshScaling, idtScaleConvex, idtScaleMesh, multiManifold, renderOutput); } } bool Gu::pcmContactBoxMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); const PxBounds3 hullAABB(-shapeBox.halfExtents, shapeBox.halfExtents); const bool idtMeshScale = shapeMesh.scale.isIdentity(); FastVertex2ShapeScaling meshScaling; if(!idtMeshScale) meshScaling.init(shapeMesh.scale); FastVertex2ShapeScaling idtScaling; const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); const PxReal toleranceLength = params.mToleranceLength; const FloatV minMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength, GU_PCM_MESH_MANIFOLD_EPSILON); const BoxV boxV(V3Zero(), boxExtents); const PxTransformV boxTransform = loadTransformA(transform0);//box PolygonalData polyData; PCMPolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData); const Mat33V identity = M33Identity(); SupportLocalImpl<BoxV> boxMap(boxV, boxTransform, identity, identity, true); return PCMContactConvexMesh(polyData, &boxMap, minMargin, hullAABB, shapeMesh, transform0, transform1, params.mContactDistance, contactBuffer, idtScaling, meshScaling, true, idtMeshScale, multiManifold, renderOutput); }
10,213
C++
40.520325
184
0.800255
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexHeightField.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxTriangleMesh.h" #include "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuVecConvexHull.h" #include "GuVecConvexHullNoScale.h" #include "GuVecTriangle.h" #include "GuContactMethodImpl.h" #include "GuPCMShapeConvex.h" #include "GuHeightField.h" #include "GuHeightFieldUtil.h" #include "GuPCMContactConvexCommon.h" #include "GuPCMContactMeshCallback.h" #include "foundation/PxVecMath.h" using namespace physx; using namespace Gu; using namespace aos; namespace { struct PCMConvexVsHeightfieldContactGenerationCallback : PCMHeightfieldContactGenerationCallback< PCMConvexVsHeightfieldContactGenerationCallback > { PCMConvexVsHeightfieldContactGenerationCallback& operator=(const PCMConvexVsHeightfieldContactGenerationCallback&); PCMConvexVsMeshContactGeneration mGeneration; PCMConvexVsHeightfieldContactGenerationCallback( const FloatVArg contactDistance, const FloatVArg replaceBreakingThreshold, const PolygonalData& polyData, const SupportLocal* polyMap, const Cm::FastVertex2ShapeScaling& convexScaling, bool idtConvexScale, const PxTransformV& convexTransform, const PxTransformV& heightfieldTransform, const PxTransform& heightfieldTransform1, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, HeightFieldUtil& hfUtil, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* delayedContacts, bool silhouetteEdgesAreActive, PxRenderOutput* renderOutput = NULL ) : PCMHeightfieldContactGenerationCallback< PCMConvexVsHeightfieldContactGenerationCallback >(hfUtil, heightfieldTransform1), mGeneration(contactDistance, replaceBreakingThreshold, convexTransform, heightfieldTransform, multiManifold, contactBuffer, polyData, polyMap, delayedContacts, convexScaling, idtConvexScale, silhouetteEdgesAreActive, renderOutput) { } template<PxU32 CacheSize> void processTriangleCache(TriangleCache<CacheSize>& cache) { mGeneration.processTriangleCache<CacheSize, PCMConvexVsMeshContactGeneration>(cache); } }; } bool Gu::PCMContactConvexHeightfield( const PolygonalData& polyData, const SupportLocal* polyMap, const FloatVArg minMargin, const PxBounds3& hullAABB, const PxHeightFieldGeometry& shapeHeightfield, const PxTransform& transform0, const PxTransform& transform1, PxReal contactDistance, PxContactBuffer& contactBuffer, const Cm::FastVertex2ShapeScaling& convexScaling, bool idtConvexScale, MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput) { const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&transform0.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV contactDist = FLoad(contactDistance); //Transfer A into the local space of B const PxTransformV convexTransform(p0, q0);//box const PxTransformV heightfieldTransform(p1, q1);//heightfield const PxTransformV curTransform = heightfieldTransform.transformInv(convexTransform); if(multiManifold.invalidate(curTransform, minMargin)) { const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f)); multiManifold.mNumManifolds = 0; multiManifold.setRelativeTransform(curTransform); //////////////////// HeightFieldUtil hfUtil(shapeHeightfield); const HeightField& hf = hfUtil.getHeightField(); //////////////////// /*const Cm::Matrix34 world0(transform0); const Cm::Matrix34 world1(transform1); const PxU8* PX_RESTRICT extraData = meshData->mExtraTrigData;*/ PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts; PCMConvexVsHeightfieldContactGenerationCallback blockCallback( contactDist, replaceBreakingThreshold, polyData, polyMap, convexScaling, idtConvexScale, convexTransform, heightfieldTransform, transform1, multiManifold, contactBuffer, hfUtil, &delayedContacts, !(hf.getFlags() & PxHeightFieldFlag::eNO_BOUNDARY_EDGES), renderOutput ); hfUtil.overlapAABBTriangles(transform0, transform1, hullAABB, blockCallback); PX_ASSERT(multiManifold.mNumManifolds <= GU_MAX_MANIFOLD_SIZE); blockCallback.mGeneration.generateLastContacts(); blockCallback.mGeneration.processContacts(GU_SINGLE_MANIFOLD_CACHE_SIZE, false); } else { const PxMatTransformV aToB(curTransform); const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.6f)); multiManifold.refreshManifold(aToB, projectBreakingThreshold, contactDist); } #if PCM_LOW_LEVEL_DEBUG multiManifold.drawManifold(*renderOutput, convexTransform, heightfieldTransform); #endif return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, heightfieldTransform); } bool Gu::pcmContactConvexHeightField(GU_CONTACT_METHOD_ARGS) { const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0); const PxHeightFieldGeometry& shapeHeightField = checkedCast<PxHeightFieldGeometry>(shape1); const ConvexHullData* hullData = _getHullData(shapeConvex); MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&transform0.p.x); const PxTransformV convexTransform(p0, q0); //const bool idtScaleMesh = shapeMesh.scale.isIdentity(); //Cm::FastVertex2ShapeScaling meshScaling; //if(!idtScaleMesh) // meshScaling.init(shapeMesh.scale); Cm::FastVertex2ShapeScaling convexScaling; PxBounds3 hullAABB; PolygonalData polyData; const bool idtScaleConvex = getPCMConvexData(shapeConvex, convexScaling, hullAABB, polyData); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const PxReal toleranceLength = params.mToleranceLength; const FloatV minMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength, GU_PCM_MESH_MANIFOLD_EPSILON); const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const ConvexHullV convexHull(hullData, V3Zero(), vScale, vQuat, shapeConvex.scale.isIdentity()); if(idtScaleConvex) { SupportLocalImpl<ConvexHullNoScaleV> convexMap(static_cast<const ConvexHullNoScaleV&>(convexHull), convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScaleConvex); return PCMContactConvexHeightfield(polyData, &convexMap, minMargin, hullAABB, shapeHeightField, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling, idtScaleConvex, multiManifold, renderOutput); } else { SupportLocalImpl<ConvexHullV> convexMap(convexHull, convexTransform, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScaleConvex); return PCMContactConvexHeightfield(polyData, &convexMap, minMargin, hullAABB, shapeHeightField, transform0, transform1, params.mContactDistance, contactBuffer, convexScaling, idtScaleConvex, multiManifold, renderOutput); } } bool Gu::pcmContactBoxHeightField(GU_CONTACT_METHOD_ARGS) { MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); const PxHeightFieldGeometry& shapeHeightField = checkedCast<PxHeightFieldGeometry>(shape1); const PxVec3 ext = shapeBox.halfExtents + PxVec3(params.mContactDistance); const PxBounds3 hullAABB(-ext, ext); const Cm::FastVertex2ShapeScaling idtScaling; const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&transform0.p.x); const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); const PxReal toranceLength = params.mToleranceLength; const FloatV minMargin = CalculatePCMBoxMargin(boxExtents, toranceLength, GU_PCM_MESH_MANIFOLD_EPSILON); const BoxV boxV(V3Zero(), boxExtents); const PxTransformV boxTransform(p0, q0);//box PolygonalData polyData; PCMPolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData); const Mat33V identity = M33Identity(); //SupportLocalImpl<BoxV> boxMap(boxV, boxTransform, identity, identity); SupportLocalImpl<BoxV> boxMap(boxV, boxTransform, identity, identity, true); return PCMContactConvexHeightfield(polyData, &boxMap, minMargin, hullAABB, shapeHeightField, transform0, transform1, params.mContactDistance, contactBuffer, idtScaling, true, multiManifold, renderOutput); }
9,905
C++
39.268293
184
0.798082
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereSphere.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 "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "foundation/PxVecTransform.h" #include "GuPCMContactGenUtil.h" using namespace physx; bool Gu::pcmContactSphereSphere(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); using namespace aos; const PxSphereGeometry& shapeSphere0 = checkedCast<PxSphereGeometry>(shape0); const PxSphereGeometry& shapeSphere1 = checkedCast<PxSphereGeometry>(shape1); const FloatV cDist = FLoad(params.mContactDistance); const Vec3V p0 = V3LoadA(&transform0.p.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV r0 = FLoad(shapeSphere0.radius); const FloatV r1 = FLoad(shapeSphere1.radius); const Vec3V _delta = V3Sub(p0, p1); const FloatV distanceSq = V3Dot(_delta, _delta); const FloatV radiusSum = FAdd(r0, r1); const FloatV inflatedSum = FAdd(radiusSum, cDist); if(FAllGrtr(FMul(inflatedSum, inflatedSum), distanceSq)) { const FloatV eps = FLoad(0.00001f); const FloatV dist = FSqrt(distanceSq); const BoolV bCon = FIsGrtrOrEq(eps, dist); const Vec3V normal = V3Sel(bCon, V3UnitX(), V3ScaleInv(_delta, dist)); const Vec3V point = V3ScaleAdd(normal, r1, p1); const FloatV pen = FSub(dist, radiusSum); return outputSimplePCMContact(contactBuffer, point, normal, pen); } return false; }
3,016
C++
42.099999
78
0.758952
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactPlaneBox.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 "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuContactMethodImpl.h" #include "GuPersistentContactManifold.h" using namespace physx; bool Gu::pcmContactPlaneBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(shape0); PX_UNUSED(renderOutput); using namespace aos; PersistentContactManifold& manifold = cache.getManifold(); PxPrefetchLine(&manifold, 256); // Get actual shape data const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); const PxTransformV transf0 = loadTransformA(transform1);//box transform const PxTransformV transf1 = loadTransformA(transform0);//plane transform //box to plane const PxTransformV curTransf(transf1.transformInv(transf0)); //in world space const Vec3V negPlaneNormal = V3Normalize(V3Neg(QuatGetBasisVector0(transf1.q))); const FloatV contactDist = FLoad(params.mContactDistance); const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); const PxReal toleranceLength = params.mToleranceLength; const FloatV boxMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength); const FloatV projectBreakingThreshold = FMul(boxMargin, FLoad(0.2f)); const PxU32 initialContacts = manifold.mNumContacts; manifold.refreshContactPoints(curTransf, projectBreakingThreshold, contactDist); const PxU32 newContacts = manifold.mNumContacts; const bool bLostContacts = (newContacts != initialContacts);//((initialContacts == 0) || (newContacts != initialContacts)); if(bLostContacts || manifold.invalidate_PrimitivesPlane(curTransf, boxMargin, FLoad(0.2f))) { //ML:localNormal is the local space of plane normal, however, because shape1 is box and shape0 is plane, we need to use the reverse of contact normal(which will be the plane normal) to make the refreshContactPoints //work out the correct pentration for points const Vec3V localNormal = V3UnitX(); manifold.mNumContacts = 0; manifold.setRelativeTransform(curTransf); const PxMatTransformV aToB(curTransf); const FloatV bx = V3GetX(boxExtents); const FloatV by = V3GetY(boxExtents); const FloatV bz = V3GetZ(boxExtents); const FloatV nbx = FNeg(bx); const FloatV nby = FNeg(by); const FloatV nbz = FNeg(bz); const Vec3V temp0 = V3Scale(aToB.getCol0(), bx); const Vec3V temp1 = V3Scale(aToB.getCol1(), by); const Vec3V temp2 = V3Scale(aToB.getCol2(), bz); const Vec3V ntemp2 = V3Neg(temp2); const FloatV px = V3GetX(aToB.p); //box's points in the local space of plane const Vec3V temp01 = V3Add(temp0, temp1);//(x, y) const Vec3V temp02 = V3Sub(temp0, temp1);//(x, -y) const FloatV s0 = V3GetX(V3Add(temp2, temp01));//(x, y, z) const FloatV s1 = V3GetX(V3Add(ntemp2, temp01));//(x, y, -z) const FloatV s2 = V3GetX(V3Add(temp2, temp02));//(x, -y, z) const FloatV s3 = V3GetX(V3Add(ntemp2, temp02));//(x, -y, -z) const FloatV s4 = V3GetX(V3Sub(temp2, temp02));//(-x, y, z) const FloatV s5 = V3GetX(V3Sub(ntemp2, temp02));//(-x, y, -z) const FloatV s6 = V3GetX(V3Sub(temp2, temp01));//(-x, -y, z) const FloatV s7 = V3GetX(V3Sub(ntemp2, temp01));//(-x, -y, -z) const FloatV acceptanceDist = FSub(contactDist, px); PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); PxU32 numContacts = 0; if(FAllGrtr(acceptanceDist, s0)) { const FloatV pen = FAdd(s0, px); //(x, y, z) manifoldContacts[numContacts].mLocalPointA = boxExtents;//aToB.transformInv(p); manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(boxExtents)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s1)) { const FloatV pen = FAdd(s1, px); //(x, y, -z) const Vec3V p = V3Merge(bx, by, nbz); //add to contact stream manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p); manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s2)) { const FloatV pen = FAdd(s2, px); //(x, -y, z) const Vec3V p = V3Merge(bx, nby, bz); manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p); manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s3)) { const FloatV pen = FAdd(s3, px); //(x, -y, -z) const Vec3V p = V3Merge(bx, nby, nbz); manifoldContacts[numContacts].mLocalPointA = p; manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s4)) { const FloatV pen = FAdd(s4, px); //(-x, y, z) const Vec3V p = V3Merge(nbx, by, bz); manifoldContacts[numContacts].mLocalPointA = p; manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s5)) { const FloatV pen = FAdd(s5, px); //(-x, y, -z) const Vec3V p = V3Merge(nbx, by, nbz); manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p); manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s6)) { const FloatV pen = FAdd(s6, px); //(-x, -y, z) const Vec3V p = V3Merge(nbx, nby, bz); manifoldContacts[numContacts].mLocalPointA = p;//aToB.transformInv(p); manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } if(FAllGrtr(acceptanceDist, s7)) { const FloatV pen = FAdd(s7, px); //(-x, -y, -z) const Vec3V p = V3Merge(nbx, nby, nbz); manifoldContacts[numContacts].mLocalPointA = p; manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, pen, aToB.transform(p)); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } //reduce contacts manifold.addBatchManifoldContactsCluster(manifoldContacts, numContacts); manifold.addManifoldContactsToContactBuffer(contactBuffer, negPlaneNormal, transf1, contactDist); return manifold.getNumContacts() > 0; } else { manifold.addManifoldContactsToContactBuffer(contactBuffer, negPlaneNormal, transf1, contactDist); //manifold.drawManifold(*gRenderOutPut, transf0, transf1); return manifold.getNumContacts() > 0; } }
8,603
C++
39.971428
216
0.734511
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMTriangleContactGen.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_PCM_TRIANGLE_CONTACT_GEN_H #define GU_PCM_TRIANGLE_CONTACT_GEN_H #include "GuPCMContactGenUtil.h" #include "GuPersistentContactManifold.h" namespace physx { class PxTriangleMeshGeometry; class PxHeightFieldGeometry; namespace Gu { bool PCMContactConvexMesh(const Gu::PolygonalData& polyData0, const Gu::SupportLocal* polyMap, const aos::FloatVArg minMargin, const PxBounds3& hullAABB, const PxTriangleMeshGeometry& shapeMesh, const PxTransform& transform0, const PxTransform& transform1, PxReal contactDistance, PxContactBuffer& contactBuffer, const Cm::FastVertex2ShapeScaling& convexScaling, const Cm::FastVertex2ShapeScaling& meshScaling, bool idtConvexScale, bool idtMeshScale, Gu::MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput); bool PCMContactConvexHeightfield(const Gu::PolygonalData& polyData0, const Gu::SupportLocal* polyMap, const aos::FloatVArg minMargin, const PxBounds3& hullAABB, const PxHeightFieldGeometry& shapeHeightfield, const PxTransform& transform0, const PxTransform& transform1, PxReal contactDistance, PxContactBuffer& contactBuffer, const Cm::FastVertex2ShapeScaling& convexScaling, bool idtConvexScale, Gu::MultiplePersistentContactManifold& multiManifold, PxRenderOutput* renderOutput); } } #endif
3,034
C
51.327585
162
0.782465
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactBoxBox.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 "geomutils/PxContactBuffer.h" #include "GuGJKPenetration.h" #include "GuEPA.h" #include "GuVecBox.h" #include "GuConvexHelper.h" #include "GuPCMShapeConvex.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGenUtil.h" using namespace physx; using namespace Gu; using namespace aos; static void getIncidentPolygon(Vec3V* pts, Vec3V& faceNormal, const Vec3VArg axis, const PxMatTransformV& transf1To0, const Vec3VArg extents) { const FloatV zero = FZero(); FloatV ex = V3GetX(extents); FloatV ey = V3GetY(extents); FloatV ez = V3GetZ(extents); const Vec3V u0 = transf1To0.getCol0(); const Vec3V u1 = transf1To0.getCol1(); const Vec3V u2 = transf1To0.getCol2(); //calculate the insident face for b const FloatV d0 = V3Dot(u0, axis); const FloatV d1 = V3Dot(u1, axis); const FloatV d2 = V3Dot(u2, axis); const FloatV absd0 = FAbs(d0); const FloatV absd1 = FAbs(d1); const FloatV absd2 = FAbs(d2); if(FAllGrtrOrEq(absd0, absd1) && FAllGrtrOrEq(absd0, absd2)) { //the incident face is on u0 const BoolV con = FIsGrtr(d0, zero); faceNormal = V3Sel(con, V3Neg(u0), u0); ex = FSel(con, FNeg(ex), ex); const Vec3V r0 = V3Scale(u0, ex); const Vec3V r1 = V3Scale(u1, ey); const Vec3V r2 = V3Scale(u2, ez); const Vec3V temp0 = V3Add(transf1To0.p, r0); const Vec3V temp1 = V3Add(r1, r2); const Vec3V temp2 = V3Sub(r1, r2); pts[0] = V3Add(temp0, temp1); // (-x/x, y, z) pts[1] = V3Add(temp0, temp2); // (-x/x, y, -z) pts[2] = V3Sub(temp0, temp1); // (-x/x, -y, -z) pts[3] = V3Sub(temp0, temp2); // (-x/x, -y, z) } else if(FAllGrtrOrEq(absd1, absd2)) { //the incident face is on u1 const BoolV con = FIsGrtr(d1, zero); faceNormal = V3Sel(con, V3Neg(u1), u1); ey = FSel(con, FNeg(ey), ey); const Vec3V r0 = V3Scale(u0, ex); const Vec3V r1 = V3Scale(u1, ey); const Vec3V r2 = V3Scale(u2, ez); const Vec3V temp0 = V3Add(transf1To0.p, r1); const Vec3V temp1 = V3Add(r0, r2); const Vec3V temp2 = V3Sub(r0, r2); pts[0] = V3Add(temp0, temp1); // (x, -y/y, z) pts[1] = V3Add(temp0, temp2); // (x, -y/y, -z) pts[2] = V3Sub(temp0, temp1); // (-x, -y/y, -z) pts[3] = V3Sub(temp0, temp2); // (-x, -y/y, z) } else { //the incident face is on u2 const BoolV con = FIsGrtr(d2, zero); faceNormal = V3Sel(con, V3Neg(u2), u2); ez = FSel(con, FNeg(ez), ez); const Vec3V r0 = V3Scale(u0, ex); const Vec3V r1 = V3Scale(u1, ey); const Vec3V r2 = V3Scale(u2, ez); const Vec3V temp0 = V3Add(transf1To0.p, r2); const Vec3V temp1 = V3Add(r0, r1); const Vec3V temp2 = V3Sub(r0, r1); pts[0] = V3Add(temp0, temp1); // ( x, y, z) pts[1] = V3Add(temp0, temp2); // ( x, -y, z) pts[2] = V3Sub(temp0, temp1); // (-x, -y, z) pts[3] = V3Sub(temp0, temp2); // (-x, y, z) } } //p0 and p1 is in the local space of AABB static bool intersectSegmentAABB(const Vec3VArg p0, const Vec3VArg d, const Vec3VArg max, const Vec3VArg min, FloatV& tmin, FloatV& tmax) { const Vec3V eps = V3Load(1e-6f); const Vec3V absV = V3Abs(d); const FloatV one = FOne(); const Vec3V zero = V3Zero(); const Vec3V fMax = Vec3V_From_FloatV(FMax()); FloatV tminf = FZero(); FloatV tmaxf = one; const BoolV isParallel = V3IsGrtr(eps, absV); const BoolV isOutsideOfRange = BOr(V3IsGrtr(p0, max), V3IsGrtr(min, p0)); //const BoolV isParallelAndOutOfRange = BAnd(isParallel, isOutsideOfRange); if(!BAllEqFFFF(BAnd(isParallel, isOutsideOfRange))) return false; const Vec3V odd = V3RecipFast(d); const Vec3V t1 = V3Sel(isParallel, zero, V3Mul(V3Sub(min, p0), odd)); const Vec3V t2 = V3Sel(isParallel, fMax, V3Mul(V3Sub(max, p0), odd)); const Vec3V tt1 = V3Min(t1, t2); const Vec3V tt2 = V3Max(t1, t2); const FloatV ft1 = V3ExtractMax(tt1); const FloatV ft2 = V3ExtractMin(tt2); tminf = FMax(ft1, tminf); tmaxf = FMin(tmaxf, ft2); tmin = tminf; tmax = tmaxf; const BoolV con0 = FIsGrtr(tminf, tmaxf); const BoolV con1 = FIsGrtr(tminf, one); const BoolV isNotIntersect = BOr(con0, con1); return BAllEqFFFF(isNotIntersect) == 1; } //pts, faceNormal and contact normal are in the local space of new space static void calculateContacts(const FloatVArg extentX_, const FloatVArg extentY_, Vec3V* pts, const Vec3VArg incidentFaceNormalInNew, const Vec3VArg localNormal, PersistentContact* manifoldContacts, PxU32& numContacts, const FloatVArg contactDist) { const FloatV zero = FZero(); const FloatV max = FMax(); const FloatV eps = FLoad(1.0001f); const FloatV extentX = FMul(extentX_, eps); const FloatV extentY = FMul(extentY_, eps); const FloatV nExtentX = FNeg(extentX); const FloatV nExtentY = FNeg(extentY); bool pPenetration[4]; bool pArea[4]; Vec3V bmin = V3Splat(max); Vec3V bmax = V3Neg(bmin); const Vec3V bound = V3Merge(extentX, extentY, max); //get the projection point of pts for(PxU32 i=0; i< 4; ++i) { bmin = V3Min(bmin, pts[i]); bmax = V3Max(bmax, pts[i]); const FloatV z = FNeg(V3GetZ(pts[i])); if(FAllGrtr(contactDist, z)) { pPenetration[i] = true; const Vec3V absPt = V3Abs(pts[i]); const BoolV con = V3IsGrtrOrEq(bound, absPt); if(BAllEqTTTT(con)) { pArea[i] = true; //Add the point to the manifold manifoldContacts[numContacts].mLocalPointA = V3SetZ(pts[i], zero); //transformNewTo0.transform(localPointA); manifoldContacts[numContacts].mLocalPointB = pts[i];//transform1ToNew.transformInv(pts[i]); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), z); } else { pArea[i] = false; } } else { pPenetration[i] = false; pArea[i] = false; } } if(numContacts == 4) return; //if(pPenetration[0] && pPenetration[1] && pPenetration[2] && pPenetration[3]) { //if(!pArea[0] || !pArea[1] || !pArea[2] || !pArea[3]) { const FloatV denom = V3GetZ(incidentFaceNormalInNew); { const Vec3V q0 = V3Merge(extentX, extentY, zero); if(contains(pts, 4, q0, bmin, bmax)) { const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0)); const FloatV t = FDiv(nom, denom); const FloatV pen = FNeg(t); if(FAllGrtr(contactDist, pen)) { manifoldContacts[numContacts].mLocalPointA = q0; manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } } } { const Vec3V q0 = V3Merge(extentX, nExtentY, zero); if(contains(pts, 4, q0, bmin, bmax)) { const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0)); const FloatV t = FDiv(nom, denom); const FloatV pen = FNeg(t); if(FAllGrtr(contactDist, pen)) { manifoldContacts[numContacts].mLocalPointA = q0; manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } } } { const Vec3V q0 = V3Merge( nExtentX, extentY, zero); if(contains(pts, 4, q0, bmin, bmax)) { const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0)); const FloatV t = FDiv(nom, denom); const FloatV pen = FNeg(t); if(FAllGrtr(contactDist, pen)) { manifoldContacts[numContacts].mLocalPointA = q0; manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } } } { const Vec3V q0 = V3Merge(nExtentX, nExtentY, zero); if(contains(pts, 4, q0, bmin, bmax)) { const FloatV nom = V3Dot(incidentFaceNormalInNew, V3Sub(pts[0], q0)); const FloatV t = FDiv(nom, denom); const FloatV pen = FNeg(t); if(FAllGrtr(contactDist, pen)) { manifoldContacts[numContacts].mLocalPointA = q0; manifoldContacts[numContacts].mLocalPointB = V3SetZ(q0, t); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), pen); } } } } } const Vec3V ext = V3Merge(extentX, extentY, max); const Vec3V negExt = V3Merge(nExtentX, nExtentY, FNeg(FAdd(contactDist, FEps()))); for (PxU32 rStart = 0, rEnd = 3; rStart < 4; rEnd = rStart++) { const Vec3V p0 = pts[rStart]; const Vec3V p1 = pts[rEnd]; if(!pPenetration[rStart] && !pPenetration[rEnd]) continue; const bool con0 = pPenetration[rStart] && pArea[rStart]; const bool con1 = pPenetration[rEnd] && pArea[rEnd]; if(con0 && con1) continue; //intersect t value with x plane const Vec3V p0p1 = V3Sub(p1, p0); FloatV tmin, tmax; if(::intersectSegmentAABB(p0, p0p1, ext, negExt, tmin, tmax)) { if(!con0) { const Vec3V intersectP = V3ScaleAdd(p0p1, tmin, p0); manifoldContacts[numContacts].mLocalPointA = V3SetZ(intersectP, zero); manifoldContacts[numContacts].mLocalPointB = intersectP; manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), FNeg(V3GetZ(intersectP))); } if(!con1) { const Vec3V intersectP = V3ScaleAdd(p0p1, tmax, p0); manifoldContacts[numContacts].mLocalPointA = V3SetZ(intersectP, zero); manifoldContacts[numContacts].mLocalPointB = intersectP; manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), FNeg(V3GetZ(intersectP))); } } } } static PxU32 doBoxBoxGenerateContacts(const Vec3VArg box0Extent, const Vec3VArg box1Extent, const PxMatTransformV& transform0, const PxMatTransformV& transform1, const FloatVArg contactDist, PersistentContact* manifoldContacts, PxU32& numContacts) { const FloatV ea0 = V3GetX(box0Extent); const FloatV ea1 = V3GetY(box0Extent); const FloatV ea2 = V3GetZ(box0Extent); const FloatV eb0 = V3GetX(box1Extent); const FloatV eb1 = V3GetY(box1Extent); const FloatV eb2 = V3GetZ(box1Extent); const PxMatTransformV transform1To0 = transform0.transformInv(transform1); const Mat33V rot0To1 =M33Trnsps(transform1To0.rot); const Vec3V uEps = V3Load(1e-6f); const FloatV zero = FZero(); const FloatV tx = V3GetX(transform1To0.p); const FloatV ty = V3GetY(transform1To0.p); const FloatV tz = V3GetZ(transform1To0.p); const Vec3V col0 = transform1To0.getCol0(); const Vec3V col1 = transform1To0.getCol1(); const Vec3V col2 = transform1To0.getCol2(); const Vec3V abs1To0Col0 = V3Add(V3Abs(col0), uEps); const Vec3V abs1To0Col1 = V3Add(V3Abs(col1), uEps); const Vec3V abs1To0Col2 = V3Add(V3Abs(col2), uEps); const Vec3V abs0To1Col0 = V3Add(V3Abs(rot0To1.col0), uEps); const Vec3V abs0To1Col1 = V3Add(V3Abs(rot0To1.col1), uEps); const Vec3V abs0To1Col2 = V3Add(V3Abs(rot0To1.col2), uEps); FloatV sign[6]; FloatV overlap[6]; FloatV ra, rb, radiusSum; //ua0 { sign[0] = tx; const Vec3V vtemp3 = V3Mul(abs0To1Col0, box1Extent); rb = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3))); radiusSum = FAdd(ea0, rb); overlap[0] = FAdd(FSub(radiusSum, FAbs(sign[0])), contactDist); if(FAllGrtr(zero, overlap[0])) return false; } //ua1 { sign[1] = ty; const Vec3V vtemp3 = V3Mul(abs0To1Col1, box1Extent); rb = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3))); radiusSum = FAdd(ea1, rb); overlap[1] = FAdd(FSub(radiusSum, FAbs(sign[1])), contactDist); if(FAllGrtr(zero, overlap[1])) return false; } //ua2 { sign[2] = tz; ra = ea2; const Vec3V vtemp3 = V3Mul(abs0To1Col2, box1Extent); rb = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3))); radiusSum = FAdd(ea2, rb); overlap[2] = FAdd(FSub(radiusSum, FAbs(sign[2])), contactDist); if(FAllGrtr(zero, overlap[2])) return false; } //ub0 { sign[3] = V3Dot(transform1To0.p, col0); const Vec3V vtemp3 = V3Mul(abs1To0Col0, box0Extent); ra = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3))); radiusSum = FAdd(ra, eb0); overlap[3] = FAdd(FSub(radiusSum, FAbs(sign[3])), contactDist); if(FAllGrtr(zero, overlap[3])) return false; } //ub1 { sign[4] = V3Dot(transform1To0.p, col1); const Vec3V vtemp3 = V3Mul(abs1To0Col1, box0Extent); ra = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3))); radiusSum = FAdd(ra, eb1); overlap[4] = FAdd(FSub(radiusSum, FAbs(sign[4])), contactDist); if(FAllGrtr(zero, overlap[4])) return false; } //ub2 { sign[5] = V3Dot(transform1To0.p, col2); const Vec3V vtemp3 = V3Mul(abs1To0Col2, box0Extent); ra = FAdd(V3GetX(vtemp3), FAdd(V3GetY(vtemp3), V3GetZ(vtemp3))); radiusSum = FAdd(ra, eb2); overlap[5] = FAdd(FSub(radiusSum, FAbs(sign[5])), contactDist); if(FAllGrtr(zero, overlap[5])) return false; } //ua0 X ub0 { //B into A's space, ua0Xub0[0,-b3, b2] const FloatV absSign = FAbs(FSub(FMul(V3GetY(col0), tz), FMul(V3GetZ(col0), ty))); //B into A's space, ua0Xub0[0,-b3, b2] const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col0), ea1); const FloatV vtemp1 = FMul(V3GetY(abs1To0Col0), ea2); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub0[0, a3, -a2] const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col0), eb1); const FloatV vtemp02 = FMul(V3GetY(abs0To1Col0), eb2); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum)) return false; } //ua0 X ub1 { //B into A's space, ua0Xub0[0, -b3, b2] const FloatV absSign = FAbs(FSub(FMul(V3GetY(col1), tz), FMul(V3GetZ(col1), ty))); //B into A's space, ua0Xub0[0, -b3, b2] const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col1), ea1); const FloatV vtemp1 = FMul(V3GetY(abs1To0Col1), ea2); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[-a3, 0, a1] const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col0), eb0); const FloatV vtemp02 = FMul(V3GetX(abs0To1Col0), eb2); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum)) return false; } //ua0 X ub2 { //B into A's space, ua0Xub0[0, -b3, b2] const FloatV absSign = FAbs(FSub(FMul(V3GetY(col2), tz), FMul(V3GetZ(col2), ty))); //B into A's space, ua0Xub0[0, -b3, b2] const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col2), ea1); const FloatV vtemp1 = FMul(V3GetY(abs1To0Col2), ea2); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[a2, -a1, 0] const FloatV vtemp01 = FMul(V3GetY(abs0To1Col0), eb0); const FloatV vtemp02 = FMul(V3GetX(abs0To1Col0), eb1); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum)) return false; } //ua1 X ub0 { //B into A's space, ua0Xub0[b3, 0, -b1] const FloatV absSign = FAbs(FSub(FMul(V3GetZ(col0), tx), FMul(V3GetX(col0), tz))); //B into A's space, ua0Xub0[b3, 0, -b1] const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col0), ea0); const FloatV vtemp1 = FMul(V3GetX(abs1To0Col0), ea2); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[0, a3, -a2] const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col1), eb1); const FloatV vtemp02 = FMul(V3GetY(abs0To1Col1), eb2); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum))return false; } //ua1 X ub1 { //B into A's space, ua0Xub0[b3, 0, -b1] const FloatV absSign = FAbs(FSub(FMul(V3GetZ(col1), tx), FMul(V3GetX(col1), tz))); //B into A's space, ua0Xub0[b3, 0, -b1] const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col1), ea0); const FloatV vtemp1 = FMul(V3GetX(abs1To0Col1), ea2); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[-a3, 0, -a1] const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col1), eb0); const FloatV vtemp02 = FMul(V3GetX(abs0To1Col1), eb2); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum))return false; } //ua1 X ub2 { //B into A's space, ua0Xub0[b3, 0, -b1] const FloatV absSign=FAbs(FSub(FMul(V3GetZ(col2), tx), FMul(V3GetX(col2), tz))); //B into A's space, ua0Xub0[b3, 0, -b1] const FloatV vtemp0 = FMul(V3GetZ(abs1To0Col2), ea0); const FloatV vtemp1 = FMul(V3GetX(abs1To0Col2), ea2); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[a2, -a1, 0] const FloatV vtemp01 = FMul(V3GetY(abs0To1Col1), eb0); const FloatV vtemp02 = FMul(V3GetX(abs0To1Col1), eb1); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum))return false; } //ua2 X ub0 { //B into A's space, ua2Xub0[-b2, b1, 0] const FloatV absSign = FAbs(FSub(FMul(V3GetX(col0), ty), FMul(V3GetY(col0), tx))); //B into A's space, ua2Xub0[-b2, b1, 0] const FloatV vtemp0 = FMul(V3GetY(abs1To0Col0), ea0); const FloatV vtemp1 = FMul(V3GetX(abs1To0Col0), ea1); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[0, a3, -a2] const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col2), eb1); const FloatV vtemp02 = FMul(V3GetY(abs0To1Col2), eb2); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum))return false; } //ua2 X ub1 { //B into A's space, ua2Xub0[-b2, b1, 0] const FloatV absSign = FAbs(FSub(FMul(V3GetX(col1), ty), FMul(V3GetY(col1), tx))); //B into A's space, ua2Xub0[-b2, b1, 0] const FloatV vtemp0 = FMul(V3GetY(abs1To0Col1), ea0); const FloatV vtemp1 = FMul(V3GetX(abs1To0Col1), ea1); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[-a3, 0, a1] const FloatV vtemp01 = FMul(V3GetZ(abs0To1Col2), eb0); const FloatV vtemp02 = FMul(V3GetX(abs0To1Col2), eb2); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum))return false; } //ua2 X ub2 { //B into A's space, ua2Xub0[-b2, b1, 0] const FloatV absSign=FAbs(FSub(FMul(V3GetX(col2), ty), FMul(V3GetY(col2), tx))); //B into A's space, ua2Xub0[-b2, b1, 0] const FloatV vtemp0 = FMul(V3GetY(abs1To0Col2), ea0); const FloatV vtemp1 = FMul(V3GetX(abs1To0Col2), ea1); ra = FAdd(vtemp0, vtemp1); //A into B's space, ua0Xub1[a2, -a1, 0] const FloatV vtemp01 = FMul(V3GetY(abs0To1Col2), eb0); const FloatV vtemp02 = FMul(V3GetX(abs0To1Col2), eb1); rb = FAdd(vtemp01, vtemp02); radiusSum = FAdd(FAdd(ra, rb), contactDist); if(FAllGrtr(absSign, radiusSum))return false; } Vec3V mtd; PxU32 feature = 0; FloatV minOverlap = overlap[0]; for(PxU32 i=1; i<6; ++i) { if(FAllGrtr(minOverlap, overlap[i])) { minOverlap = overlap[i]; feature = i; } } PxMatTransformV newTransformV; const Vec3V axis00 = transform0.getCol0(); const Vec3V axis01 = transform0.getCol1(); const Vec3V axis02 = transform0.getCol2(); const Vec3V axis10 = transform1.getCol0(); const Vec3V axis11 = transform1.getCol1(); const Vec3V axis12 = transform1.getCol2(); Vec3V incidentFaceNormalInNew; Vec3V pts[4]; bool flip = false; switch(feature) { case 0: //ua0 { if(FAllGrtrOrEq(zero, sign[0])) { mtd = axis00; newTransformV.rot.col0 = V3Neg(axis02); newTransformV.rot.col1 = axis01; newTransformV.rot.col2 = axis00; newTransformV.p = V3NegScaleSub(axis00, ea0, transform0.p); } else { const Vec3V nAxis00 = V3Neg(axis00); mtd = nAxis00; newTransformV.rot.col0 = axis02; newTransformV.rot.col1 = axis01; newTransformV.rot.col2 = nAxis00; newTransformV.p = V3ScaleAdd(axis00, ea0, transform0.p); } const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform1); const Vec3V localNormal = newTransformV.rotateInv(mtd); getIncidentPolygon(pts, incidentFaceNormalInNew, V3Neg(localNormal), transform1ToNew, box1Extent); calculateContacts(ea2, ea1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist); break; }; case 1: //ua1 { if(FAllGrtrOrEq(zero, sign[1])) { mtd = axis01; newTransformV.rot.col0 = axis00; newTransformV.rot.col1 = V3Neg(axis02); newTransformV.rot.col2 = axis01; newTransformV.p = V3NegScaleSub(axis01, ea1, transform0.p); } else { const Vec3V nAxis01 = V3Neg(axis01); mtd = nAxis01; newTransformV.rot.col0 = axis00; newTransformV.rot.col1 = axis02; newTransformV.rot.col2 = nAxis01; newTransformV.p = V3ScaleAdd(axis01, ea1, transform0.p); } const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform1); const Vec3V localNormal = newTransformV.rotateInv(mtd); getIncidentPolygon(pts, incidentFaceNormalInNew, V3Neg(localNormal), transform1ToNew, box1Extent); calculateContacts(ea0, ea2, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist); break; }; case 2: //ua2 { if(FAllGrtrOrEq(zero, sign[2])) { mtd = axis02; newTransformV.rot.col0 = axis00; newTransformV.rot.col1 = axis01; newTransformV.rot.col2 = axis02; newTransformV.p = V3NegScaleSub(axis02, ea2, transform0.p); } else { const Vec3V nAxis02 = V3Neg(axis02); mtd = nAxis02; newTransformV.rot.col0 = axis00; newTransformV.rot.col1 = V3Neg(axis01); newTransformV.rot.col2 = nAxis02; newTransformV.p = V3ScaleAdd(axis02, ea2, transform0.p); } const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform1); const Vec3V localNormal = newTransformV.rotateInv(mtd); getIncidentPolygon(pts, incidentFaceNormalInNew, V3Neg(localNormal), transform1ToNew, box1Extent); calculateContacts(ea0, ea1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist); break; }; case 3: //ub0 { flip = true; if(FAllGrtrOrEq(zero, sign[3])) { mtd = axis10; newTransformV.rot.col0 = axis12; newTransformV.rot.col1 = axis11; newTransformV.rot.col2 = V3Neg(axis10); newTransformV.p = V3ScaleAdd(axis10, eb0, transform1.p); //transform0.p - extents0.x*axis00; } else { mtd = V3Neg(axis10); newTransformV.rot.col0 = V3Neg(axis12); newTransformV.rot.col1 = axis11; newTransformV.rot.col2 = axis10; newTransformV.p = V3NegScaleSub(axis10, eb0, transform1.p);//transform0.p + extents0.x*axis00; } const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform0); const Vec3V localNormal = newTransformV.rotateInv(mtd); getIncidentPolygon(pts, incidentFaceNormalInNew, localNormal, transform1ToNew, box0Extent); calculateContacts(eb2, eb1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist); break; }; case 4: //ub1; { flip = true; if(FAllGrtrOrEq(zero, sign[4])) { mtd = axis11; newTransformV.rot.col0 = axis10; newTransformV.rot.col1 = axis12; newTransformV.rot.col2 = V3Neg(axis11); newTransformV.p = V3ScaleAdd(axis11, eb1, transform1.p); } else { mtd = V3Neg(axis11); newTransformV.rot.col0 = axis10; newTransformV.rot.col1 = V3Neg(axis12); newTransformV.rot.col2 = axis11; newTransformV.p = V3NegScaleSub(axis11, eb1, transform1.p); //transform0.p + extents0.x*axis00; } const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform0); const Vec3V localNormal = newTransformV.rotateInv(mtd); getIncidentPolygon(pts, incidentFaceNormalInNew, localNormal, transform1ToNew, box0Extent); calculateContacts(eb0, eb2, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist); break; } case 5: //ub2; { flip = true; if(FAllGrtrOrEq(zero, sign[5])) { mtd = axis12; newTransformV.rot.col0 = axis10; newTransformV.rot.col1 = V3Neg(axis11); newTransformV.rot.col2 = V3Neg(axis12); newTransformV.p = V3ScaleAdd(axis12, eb2, transform1.p); } else { mtd = V3Neg(axis12); newTransformV.rot.col0 = axis10; newTransformV.rot.col1 = axis11; newTransformV.rot.col2 = axis12; newTransformV.p = V3NegScaleSub(axis12, eb2, transform1.p); } const PxMatTransformV transform1ToNew = newTransformV.transformInv(transform0); const Vec3V localNormal = newTransformV.rotateInv(mtd); getIncidentPolygon(pts, incidentFaceNormalInNew, localNormal, transform1ToNew, box0Extent); calculateContacts(eb0, eb1, pts, incidentFaceNormalInNew, localNormal, manifoldContacts, numContacts, contactDist); break; }; default: return false; } if(numContacts != 0) { if(flip) { for(PxU32 i=0; i<numContacts; ++i) { const Vec3V localB = manifoldContacts[i].mLocalPointB; manifoldContacts[i].mLocalPointB = manifoldContacts[i].mLocalPointA; manifoldContacts[i].mLocalPointA = localB; } } const PxMatTransformV transformNewTo1 = transform1.transformInv(newTransformV); const PxMatTransformV transformNewTo0 = transform0.transformInv(newTransformV); //transform points to the local space of transform0 and transform1 const Vec3V localNormalInB = transformNewTo1.rotate(Vec3V_From_Vec4V(manifoldContacts[0].mLocalNormalPen)); for(PxU32 i=0; i<numContacts; ++i) { manifoldContacts[i].mLocalPointA = transformNewTo0.transform(manifoldContacts[i].mLocalPointA); manifoldContacts[i].mLocalPointB = transformNewTo1.transform(manifoldContacts[i].mLocalPointB); manifoldContacts[i].mLocalNormalPen = V4SetW(localNormalInB, V4GetW(manifoldContacts[i].mLocalNormalPen)); } } return true; } bool Gu::pcmContactBoxBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_ASSERT(transform1.q.isSane()); PX_ASSERT(transform0.q.isSane()); const PxBoxGeometry& shapeBox0 = checkedCast<PxBoxGeometry>(shape0); const PxBoxGeometry& shapeBox1 = checkedCast<PxBoxGeometry>(shape1); // Get actual shape data PersistentContactManifold& manifold = cache.getManifold(); PxPrefetchLine(&manifold, 256); const FloatV contactDist = FLoad(params.mContactDistance); const Vec3V boxExtents0 = V3LoadU(shapeBox0.halfExtents); const Vec3V boxExtents1 = V3LoadU(shapeBox1.halfExtents); //Transfer A into the local space of B const PxTransformV transf0 = loadTransformA(transform0); const PxTransformV transf1 = loadTransformA(transform1); const PxTransformV curRTrans(transf1.transformInv(transf0)); const PxMatTransformV aToB(curRTrans); const PxReal toleranceLength = params.mToleranceLength; const FloatV boxMargin0 = CalculatePCMBoxMargin(boxExtents0, toleranceLength); const FloatV boxMargin1 = CalculatePCMBoxMargin(boxExtents1, toleranceLength); const FloatV minMargin = FMin(boxMargin0, boxMargin1); const PxU32 initialContacts = manifold.mNumContacts; const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f)); manifold.refreshContactPoints(aToB, projectBreakingThreshold, contactDist); const PxU32 newContacts = manifold.mNumContacts; const bool bLostContacts = (newContacts != initialContacts); const FloatV radiusA = V3Length(boxExtents0); const FloatV radiusB = V3Length(boxExtents1); if(bLostContacts || manifold.invalidate_BoxConvex(curRTrans, transf0.q, transf1.q, minMargin, radiusA, radiusB)) { manifold.setRelativeTransform(curRTrans, transf0.q, transf1.q); PxMatTransformV transfV0(transf0); PxMatTransformV transfV1(transf1); transfV0.rot.col0 = V3Normalize(transfV0.rot.col0); transfV0.rot.col1 = V3Normalize(transfV0.rot.col1); transfV0.rot.col2 = V3Normalize(transfV0.rot.col2); transfV1.rot.col0 = V3Normalize(transfV1.rot.col0); transfV1.rot.col1 = V3Normalize(transfV1.rot.col1); transfV1.rot.col2 = V3Normalize(transfV1.rot.col2); PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); PxU32 numContacts = 0; if(doBoxBoxGenerateContacts(boxExtents0, boxExtents1, transfV0, transfV1, contactDist, manifoldContacts, numContacts)) { if(numContacts > 0) { manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength); const Vec3V worldNormal = V3Normalize(transfV1.rotate(Vec3V_From_Vec4V(manifold.mContactPoints[0].mLocalNormalPen))); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transfV1); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } else { const Vec3V zeroV = V3Zero(); const BoxV box0(zeroV, boxExtents0); const BoxV box1(zeroV, boxExtents1); manifold.mNumWarmStartPoints = 0; const RelativeConvex<BoxV> convexA(box0, aToB); const LocalConvex<BoxV> convexB(box1); GjkOutput output; GjkStatus status = gjkPenetration<RelativeConvex<BoxV>, LocalConvex<BoxV> >(convexA, convexB, aToB.p, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); if(status == EPA_CONTACT) { const RelativeConvex<BoxV> convexA1(box0, aToB); const LocalConvex<BoxV> convexB1(box1); status = epaPenetration(convexA1, convexB1, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, FLoad(toleranceLength), output); } if(status == GJK_CONTACT || status == EPA_CONTACT) { const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.05f)); const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA); const Vec3V localPointB = output.closestB; const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); numContacts += manifold.addManifoldPoint(localPointA, localPointB, localNormalPen, replaceBreakingThreshold); //transform the normal back to world space const Vec3V worldNormal = V3Normalize(transf1.rotate(output.normal)); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } } } } else if(manifold.getNumContacts() > 0) { const Vec3V worldNormal = manifold.getWorldNormal(transf1); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, transf1, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return true; } return false; }
31,690
C++
31.603909
247
0.698927
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexCommon.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 "GuVecTriangle.h" #include "GuPCMContactConvexCommon.h" #include "GuConvexEdgeFlags.h" #include "GuBarycentricCoordinates.h" using namespace physx; using namespace Gu; using namespace aos; // This function adds the newly created manifold contacts to a new patch or existing patches void PCMConvexVsMeshContactGeneration::addContactsToPatch(const Vec3VArg patchNormal, PxU32 previousNumContacts) { const Vec3V patchNormalInTriangle = mMeshToConvex.rotateInv(patchNormal); const PxU32 newContacts = mNumContacts - previousNumContacts; if(newContacts > GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE) { //if the current created manifold contacts are more than GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE(4) points, we will reduce the total numContacts //to GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE. However, after we add these points into a patch, the patch contacts will be variable. Then we will //do contact reduction for that patch in the processContacts. After the contact reduction, there will be no more than GU_SINGLE_MANIFOLD_CACHE_SIZE(6) //contacts inside a signlePersistentContactManifold SinglePersistentContactManifold::reduceContacts(&mManifoldContacts[previousNumContacts], newContacts); mNumContacts = previousNumContacts + GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } //get rid of duplicate manifold contacts for the newly created contacts for(PxU32 i = previousNumContacts; i<mNumContacts; ++i) { for(PxU32 j=i+1; j<mNumContacts; ++j) { Vec3V dif = V3Sub(mManifoldContacts[j].mLocalPointB, mManifoldContacts[i].mLocalPointB); FloatV d = V3Dot(dif, dif); if(FAllGrtr(mSqReplaceBreakingThreshold, d)) { mManifoldContacts[j] = mManifoldContacts[mNumContacts-1]; mNumContacts--; j--; } } } //calculate the maxPen and transform the patch normal and localPointB into mesh's local space FloatV maxPen = FMax(); for(PxU32 i = previousNumContacts; i<mNumContacts; ++i) { const FloatV pen = V4GetW(mManifoldContacts[i].mLocalNormalPen); mManifoldContacts[i].mLocalNormalPen = V4SetW(patchNormalInTriangle, pen); mManifoldContacts[i].mLocalPointB = mMeshToConvex.transformInv(mManifoldContacts[i].mLocalPointB); maxPen = FMin(maxPen, pen); } //Based on the patch normal and add the newly avaiable manifold points to the corresponding patch addManifoldPointToPatch(patchNormalInTriangle, maxPen, previousNumContacts); PX_ASSERT(mNumContactPatch <PCM_MAX_CONTACTPATCH_SIZE); if(mNumContacts >= GU_MESH_CONTACT_REDUCTION_THRESHOLD) { PX_ASSERT(mNumContacts <= PxContactBuffer::MAX_CONTACTS); processContacts(GU_SINGLE_MANIFOLD_CACHE_SIZE); } } void PCMConvexVsMeshContactGeneration::generateLastContacts() { // Process delayed contacts PxU32 nbEntries = mDeferredContacts->size(); if(nbEntries) { nbEntries /= sizeof(PCMDeferredPolyData)/sizeof(PxU32); const PCMDeferredPolyData* PX_RESTRICT cd = reinterpret_cast<const PCMDeferredPolyData*>(mDeferredContacts->begin()); for(PxU32 i=0;i<nbEntries;i++) { const PCMDeferredPolyData& currentContact = cd[i]; const PxU32 ref0 = currentContact.mInds[0]; const PxU32 ref1 = currentContact.mInds[1]; const PxU32 ref2 = currentContact.mInds[2]; const PxU8 triFlags = PxU8(currentContact.triFlags32); const bool needsProcessing = (((triFlags & ETD_CONVEX_EDGE_01) != 0 || mEdgeCache.get(CachedEdge(ref0, ref1)) == NULL)) && (((triFlags & ETD_CONVEX_EDGE_12) != 0 || mEdgeCache.get(CachedEdge(ref1, ref2)) == NULL)) && (((triFlags & ETD_CONVEX_EDGE_20) != 0 || mEdgeCache.get(CachedEdge(ref2, ref0)) == NULL)); if(needsProcessing) { const TriangleV localTriangle(currentContact.mVerts); Vec3V patchNormal; const PxU32 previousNumContacts = mNumContacts; //the localTriangle is in the convex space //Generate contacts - we didn't generate contacts with any neighbours generatePolyDataContactManifold(localTriangle, currentContact.mFeatureIndex, currentContact.mTriangleIndex, triFlags, mManifoldContacts, mNumContacts, mContactDist, patchNormal); FloatV v, w; const FloatV upperBound = FLoad(0.97f); const FloatV lowerBound = FSub(FOne(), upperBound); PxU32 currentContacts = mNumContacts; for(PxU32 j=currentContacts; j>previousNumContacts; --j) { PxU32 ind = j-1; //calculate the barycentric coordinate of the contacts in localTriangle, p = a + v(b-a) + w(c-a)., p=ua+vb+wc barycentricCoordinates(mManifoldContacts[ind].mLocalPointB, localTriangle.verts[0], localTriangle.verts[1], localTriangle.verts[2], v, w); //const FloatV u = FSub(one, FAdd(v, w)); bool keepContact = true; if(FAllGrtr(v, upperBound))//v > upperBound { //vertex1 keepContact = !mVertexCache.contains(CachedVertex(ref1)); } else if(FAllGrtr(w, upperBound))// w > upperBound { //vertex2 keepContact = !mVertexCache.contains(CachedVertex(ref2)); } else if(FAllGrtrOrEq(lowerBound, FAdd(v, w))) // u(1-(v+w)) > upperBound { //vertex0 keepContact = !mVertexCache.contains(CachedVertex(ref0)); } if(!keepContact) { //ML: if feature code is any of the vertex in this triangle and we have generated contacts with any other triangles which contains this vertex, we should drop it currentContacts--; for(PxU32 k = ind; k < currentContacts; ++k) { mManifoldContacts[k] = mManifoldContacts[k+1]; } } } mNumContacts = currentContacts; if(currentContacts > previousNumContacts) { addContactsToPatch(patchNormal, previousNumContacts); } } } } } bool PCMConvexVsMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds) { const Mat33V identity = M33Identity(); const FloatV zero = FZero(); const Vec3V v0 = V3LoadU(verts[0]); const Vec3V v1 = V3LoadU(verts[1]); const Vec3V v2 = V3LoadU(verts[2]); const Vec3V v10 = V3Sub(v1, v0); const Vec3V v20 = V3Sub(v2, v0); const Vec3V n = V3Normalize(V3Cross(v10, v20));//(p1 - p0).cross(p2 - p0).getNormalized(); const FloatV d = V3Dot(v0, n);//d = -p0.dot(n); const FloatV dist = FSub(V3Dot(mHullCenterMesh, n), d);//p.dot(n) + d; // Backface culling if(FAllGrtr(zero, dist)) return false; //tranform verts into the box local space const Vec3V locV0 = mMeshToConvex.transform(v0); const Vec3V locV1 = mMeshToConvex.transform(v1); const Vec3V locV2 = mMeshToConvex.transform(v2); const TriangleV localTriangle(locV0, locV1, locV2); { SupportLocalImpl<TriangleV> localTriMap(localTriangle, mConvexTransform, identity, identity, true); const PxU32 previousNumContacts = mNumContacts; Vec3V patchNormal; generateTriangleFullContactManifold(localTriangle, triangleIndex, vertInds, triFlags, mPolyData, &localTriMap, mPolyMap, mManifoldContacts, mNumContacts, mContactDist, patchNormal); if(mNumContacts > previousNumContacts) { #if PCM_LOW_LEVEL_DEBUG PersistentContactManifold::drawTriangle(*mRenderOutput, mMeshTransform.transform(v0), mMeshTransform.transform(v1), mMeshTransform.transform(v2), 0x00ff00); #endif const bool inActiveEdge0 = (triFlags & ETD_CONVEX_EDGE_01) == 0; const bool inActiveEdge1 = (triFlags & ETD_CONVEX_EDGE_12) == 0; const bool inActiveEdge2 = (triFlags & ETD_CONVEX_EDGE_20) == 0; if(inActiveEdge0) mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[1])); if(inActiveEdge1) mEdgeCache.addData(CachedEdge(vertInds[1], vertInds[2])); if(inActiveEdge2) mEdgeCache.addData(CachedEdge(vertInds[2], vertInds[0])); mVertexCache.addData(CachedVertex(vertInds[0])); mVertexCache.addData(CachedVertex(vertInds[1])); mVertexCache.addData(CachedVertex(vertInds[2])); addContactsToPatch(patchNormal, previousNumContacts); } } return true; } bool PCMConvexVsMeshContactGeneration::processTriangle(const PolygonalData& polyData, const SupportLocal* polyMap, const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const FloatVArg inflation, bool isDoubleSided, const PxTransformV& convexTransform, const PxMatTransformV& meshToConvex, MeshPersistentContact* manifoldContacts, PxU32& numContacts) { const Mat33V identity = M33Identity(); const FloatV zero = FZero(); const Vec3V v0 = V3LoadU(verts[0]); const Vec3V v1 = V3LoadU(verts[1]); const Vec3V v2 = V3LoadU(verts[2]); //tranform verts into the box local space const Vec3V locV0 = meshToConvex.transform(v0); const Vec3V locV1 = meshToConvex.transform(v1); const Vec3V locV2 = meshToConvex.transform(v2); const Vec3V v10 = V3Sub(locV1, locV0); const Vec3V v20 = V3Sub(locV2, locV0); const Vec3V n = V3Normalize(V3Cross(v10, v20));//(p1 - p0).cross(p2 - p0).getNormalized(); const FloatV d = V3Dot(locV0, n);//d = -p0.dot(n); const FloatV dist = FSub(V3Dot(polyMap->shapeSpaceCenterOfMass, n), d);//p.dot(n) + d; // Backface culling const bool culled = !isDoubleSided && (FAllGrtr(zero, dist)); if(culled) return false; const TriangleV localTriangle(locV0, locV1, locV2); SupportLocalImpl<TriangleV> localTriMap(localTriangle, convexTransform, identity, identity, true); Vec3V patchNormal; generateTriangleFullContactManifold(localTriangle, triangleIndex, triFlags, polyData, &localTriMap, polyMap, manifoldContacts, numContacts, inflation, patchNormal); return true; }
11,132
C++
39.191336
219
0.738951
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactMeshCallback.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_PCM_CONTACT_MESH_CALLBACK_H #define GU_PCM_CONTACT_MESH_CALLBACK_H #include "GuMidphaseInterface.h" #include "GuEntityReport.h" #include "GuHeightFieldUtil.h" #include "GuTriangleCache.h" #include "GuConvexEdgeFlags.h" namespace physx { namespace Gu { template <typename Derived> struct PCMMeshContactGenerationCallback : MeshHitCallback<PxGeomRaycastHit> { public: const Cm::FastVertex2ShapeScaling& mMeshScaling; const PxU8* PX_RESTRICT mExtraTrigData; bool mIdtMeshScale; static const PxU32 CacheSize = 16; Gu::TriangleCache<CacheSize> mCache; PCMMeshContactGenerationCallback(const Cm::FastVertex2ShapeScaling& meshScaling, const PxU8* extraTrigData, bool idtMeshScale) : MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE), mMeshScaling(meshScaling), mExtraTrigData(extraTrigData), mIdtMeshScale(idtMeshScale) { } void flushCache() { if (!mCache.isEmpty()) { (static_cast<Derived*>(this))->template processTriangleCache< CacheSize >(mCache); mCache.reset(); } } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { if (!(static_cast<Derived*>(this))->doTest(v0, v1, v2)) return true; const PxU32 triangleIndex = hit.faceIndex; PxU8 extraData = getConvexEdgeFlags(mExtraTrigData, triangleIndex); const PxU32* vertexIndices = vinds; PxVec3 v[3]; PxU32 localStorage[3]; if(mIdtMeshScale) { v[0] = v0; v[1] = v1; v[2] = v2; } else { const PxI32 winding = mMeshScaling.flipsNormal() ? 1 : 0; v[0] = mMeshScaling * v0; v[1 + winding] = mMeshScaling * v1; v[2 - winding] = mMeshScaling * v2; if(winding) { flipConvexEdgeFlags(extraData); localStorage[0] = vinds[0]; localStorage[1] = vinds[2]; localStorage[2] = vinds[1]; vertexIndices = localStorage; } } if (mCache.isFull()) { (static_cast<Derived*>(this))->template processTriangleCache< CacheSize >(mCache); mCache.reset(); } mCache.addTriangle(v, vertexIndices, triangleIndex, extraData); return true; } protected: PCMMeshContactGenerationCallback& operator=(const PCMMeshContactGenerationCallback&); }; template <typename Derived> struct PCMHeightfieldContactGenerationCallback : Gu::OverlapReport { public: const Gu::HeightFieldUtil& mHfUtil; const PxTransform& mHeightfieldTransform; bool mBoundaryCollisions; PCMHeightfieldContactGenerationCallback(const Gu::HeightFieldUtil& hfUtil, const PxTransform& heightfieldTransform) : mHfUtil(hfUtil), mHeightfieldTransform(heightfieldTransform) { mBoundaryCollisions = !(hfUtil.getHeightField().getFlags() & PxHeightFieldFlag::eNO_BOUNDARY_EDGES); } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { const PxU32 CacheSize = 16; Gu::TriangleCache<CacheSize> cache; const PxU32 nbPasses = (nb+(CacheSize-1))/CacheSize; PxU32 nbTrigs = nb; const PxU32* inds0 = indices; const PxU8 nextInd[] = {2,0,1}; for(PxU32 i = 0; i < nbPasses; ++i) { cache.mNumTriangles = 0; PxU32 trigCount = PxMin(nbTrigs, CacheSize); nbTrigs -= trigCount; while(trigCount--) { PxU32 triangleIndex = *(inds0++); PxU32 vertIndices[3]; PxTriangle currentTriangle; // in world space PxU32 adjInds[3]; mHfUtil.getTriangle(mHeightfieldTransform, currentTriangle, vertIndices, adjInds, triangleIndex, false, false); PxVec3 normal; currentTriangle.normal(normal); PxU8 triFlags = 0; //KS - temporary until we can calculate triFlags for HF for(PxU32 a = 0; a < 3; ++a) { if (adjInds[a] != 0xFFFFFFFF) { PxTriangle adjTri; PxU32 inds[3]; mHfUtil.getTriangle(mHeightfieldTransform, adjTri, inds, NULL, adjInds[a], false, false); //We now compare the triangles to see if this edge is active PX_ASSERT(inds[0] == vertIndices[a] || inds[1] == vertIndices[a] || inds[2] == vertIndices[a]); PX_ASSERT(inds[0] == vertIndices[(a + 1) % 3] || inds[1] == vertIndices[(a + 1) % 3] || inds[2] == vertIndices[(a + 1) % 3]); PxVec3 adjNormal; adjTri.denormalizedNormal(adjNormal); PxU32 otherIndex = nextInd[a]; PxF32 projD = adjNormal.dot(currentTriangle.verts[otherIndex] - adjTri.verts[0]); if (projD < 0.f) { adjNormal.normalize(); PxF32 proj = adjNormal.dot(normal); if (proj < 0.997f) { triFlags |= (1 << (a + 3)); } } } else if (mBoundaryCollisions) { triFlags |= (1 << (a + 3)); //Mark boundary edge active } else triFlags |= (1 << a); //Mark as silhouette edge } cache.addTriangle(currentTriangle.verts, vertIndices, triangleIndex, triFlags); } PX_ASSERT(cache.mNumTriangles <= 16); (static_cast<Derived*>(this))->template processTriangleCache< CacheSize >(cache); } return true; } protected: PCMHeightfieldContactGenerationCallback& operator=(const PCMHeightfieldContactGenerationCallback&); }; template <typename Derived> struct PCMTetMeshContactGenerationCallback : TetMeshHitCallback<PxGeomRaycastHit> { public: static const PxU32 CacheSize = 16; Gu::TetrahedronCache<CacheSize> mCache; PCMTetMeshContactGenerationCallback(): TetMeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE) { } void flushCache() { if (!mCache.isEmpty()) { (static_cast<Derived*>(this))->template processTetrahedronCache< CacheSize >(mCache); mCache.reset(); } } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxVec3& v3, PxReal&, const PxU32* vinds) { if (!(static_cast<Derived*>(this))->doTest(v0, v1, v2, v3)) return true; PxVec3 v[4] = { v0, v1, v2, v3 }; const PxU32 tetIndex = hit.faceIndex; if (mCache.isFull()) { (static_cast<Derived*>(this))->template processTetrahedronCache< CacheSize >(mCache); mCache.reset(); } mCache.addTetrahedrons(v, vinds, tetIndex); return true; } protected: PCMTetMeshContactGenerationCallback& operator=(const PCMTetMeshContactGenerationCallback&); }; }//Gu }//physx #endif
7,926
C
29.488461
131
0.709311
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPersistentContactManifold.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 "geomutils/PxContactBuffer.h" #include "foundation/PxAlloca.h" #include "foundation/PxVecTransform.h" #include "foundation/PxUtilities.h" #include "GuPersistentContactManifold.h" #include "GuGJKUtil.h" #include "GuPCMContactGenUtil.h" using namespace physx; using namespace aos; using namespace Gu; // This local function is to avoid DLL call static FloatV distancePointSegmentSquaredLocal(const Vec3VArg a, const Vec3VArg b, const Vec3VArg p) { const FloatV zero = FZero(); const FloatV one = FOne(); const Vec3V ap = V3Sub(p, a); const Vec3V ab = V3Sub(b, a); const FloatV nom = V3Dot(ap, ab); const FloatV denom = V3Dot(ab, ab); const FloatV tValue = FClamp(FDiv(nom, denom), zero, one); const FloatV t = FSel(FIsEq(denom, zero), zero, tValue); const Vec3V v = V3NegScaleSub(ab, t, ap); return V3Dot(v, v); } // This local function is to avoid DLL call static FloatV distancePointTriangleSquaredLocal(const Vec3VArg p, const Vec3VArg a, const Vec3VArg b, const Vec3VArg c) { const FloatV zero = FZero(); //const Vec3V zero = V3Zero(); const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V bc = V3Sub(c, b); const Vec3V ap = V3Sub(p, a); const Vec3V bp = V3Sub(p, b); const Vec3V cp = V3Sub(p, c); const FloatV d1 = V3Dot(ab, ap); // snom const FloatV d2 = V3Dot(ac, ap); // tnom const FloatV d3 = V3Dot(ab, bp); // -sdenom const FloatV d4 = V3Dot(ac, bp); // unom = d4 - d3 const FloatV d5 = V3Dot(ab, cp); // udenom = d5 - d6 const FloatV d6 = V3Dot(ac, cp); // -tdenom const FloatV unom = FSub(d4, d3); const FloatV udenom = FSub(d5, d6); //check if p in vertex region outside a const BoolV con00 = FIsGrtr(zero, d1); // snom <= 0 const BoolV con01 = FIsGrtr(zero, d2); // tnom <= 0 const BoolV con0 = BAnd(con00, con01); // vertex region a if(BAllEqTTTT(con0)) { const Vec3V vv = V3Sub(p, a); return V3Dot(vv, vv); } //check if p in vertex region outside b const BoolV con10 = FIsGrtrOrEq(d3, zero); const BoolV con11 = FIsGrtrOrEq(d3, d4); const BoolV con1 = BAnd(con10, con11); // vertex region b if(BAllEqTTTT(con1)) { const Vec3V vv = V3Sub(p, b); return V3Dot(vv, vv); } //check if p in vertex region outside c const BoolV con20 = FIsGrtrOrEq(d6, zero); const BoolV con21 = FIsGrtrOrEq(d6, d5); const BoolV con2 = BAnd(con20, con21); // vertex region c if(BAllEqTTTT(con2)) { const Vec3V vv = V3Sub(p, c); return V3Dot(vv, vv); } //check if p in edge region of AB const FloatV vc = FSub(FMul(d1, d4), FMul(d3, d2)); const BoolV con30 = FIsGrtr(zero, vc); const BoolV con31 = FIsGrtrOrEq(d1, zero); const BoolV con32 = FIsGrtr(zero, d3); const BoolV con3 = BAnd(con30, BAnd(con31, con32)); if(BAllEqTTTT(con3)) { const FloatV sScale = FDiv(d1, FSub(d1, d3)); const Vec3V closest3 = V3ScaleAdd(ab, sScale, a);//V3Add(a, V3Scale(ab, sScale)); const Vec3V vv = V3Sub(p, closest3); return V3Dot(vv, vv); } //check if p in edge region of BC const FloatV va = FSub(FMul(d3, d6),FMul(d5, d4)); const BoolV con40 = FIsGrtr(zero, va); const BoolV con41 = FIsGrtrOrEq(d4, d3); const BoolV con42 = FIsGrtrOrEq(d5, d6); const BoolV con4 = BAnd(con40, BAnd(con41, con42)); if(BAllEqTTTT(con4)) { const FloatV uScale = FDiv(unom, FAdd(unom, udenom)); const Vec3V closest4 = V3ScaleAdd(bc, uScale, b);//V3Add(b, V3Scale(bc, uScale)); const Vec3V vv = V3Sub(p, closest4); return V3Dot(vv, vv); } //check if p in edge region of AC const FloatV vb = FSub(FMul(d5, d2), FMul(d1, d6)); const BoolV con50 = FIsGrtr(zero, vb); const BoolV con51 = FIsGrtrOrEq(d2, zero); const BoolV con52 = FIsGrtr(zero, d6); const BoolV con5 = BAnd(con50, BAnd(con51, con52)); if(BAllEqTTTT(con5)) { const FloatV tScale = FDiv(d2, FSub(d2, d6)); const Vec3V closest5 = V3ScaleAdd(ac, tScale, a);//V3Add(a, V3Scale(ac, tScale)); const Vec3V vv = V3Sub(p, closest5); return V3Dot(vv, vv); } //P must project inside face region. Compute Q using Barycentric coordinates const Vec3V n = V3Cross(ab, ac); const FloatV nn = V3Dot(n,n); const FloatV t = FSel(FIsGrtr(nn, zero),FDiv(V3Dot(n, V3Sub(a, p)), nn), zero); const Vec3V closest6 = V3Add(p, V3Scale(n, t)); const Vec3V vv = V3Sub(p, closest6); return V3Dot(vv, vv); } namespace physx { namespace Gu { //This is the translational threshold used in invalidate_BoxConvexHull. 0.5 is 50% of the object margin. we use different threshold between //0 and 4 points. This threashold is a scale that is multiplied by the objects' margins. const PxF32 invalidateThresholds[5] = { 0.5f, 0.125f, 0.25f, 0.375f, 0.375f }; //This is the translational threshold used in invalidate_SphereCapsule. 0.5 is 50% of the object margin, we use different threshold between //0 and 2 points. This threshold is a scale that is multiplied by the objects' margin const PxF32 invalidateThresholds2[3] = { 0.5f, 0.1f, 0.75f }; //This is the rotational threshold used in invalidate_BoxConvexHull. 0.9998 is a threshold for quat difference //between previous and current frame const PxF32 invalidateQuatThresholds[5] = { 0.9998f, 0.9999f, 0.9999f, 0.9999f, 0.9999f }; //This is the rotational threshold used in invalidate_SphereCapsule. 0.9995f is a threshold for quat difference //between previous and current frame const PxF32 invalidateQuatThresholds2[3] = { 0.9995f, 0.9999f, 0.9997f }; } } #if VISUALIZE_PERSISTENT_CONTACT #include "common/PxRenderOutput.h" static void drawManifoldPoint(const PersistentContact& manifold, const PxTransformV& trA, const PxTransformV& trB, PxRenderOutput& out, PxU32 color=0xffffff) { PX_UNUSED(color); const Vec3V worldA = trA.transform(manifold.mLocalPointA); const Vec3V worldB = trB.transform(manifold.mLocalPointB); const Vec3V localNormal = Vec3V_From_Vec4V(manifold.mLocalNormalPen); const FloatV pen = V4GetW(manifold.mLocalNormalPen); const Vec3V worldNormal = trB.rotate(localNormal); PxVec3 a, b, v; V3StoreU(worldA, a); V3StoreU(worldB, b); V3StoreU(worldNormal, v); PxF32 dist; FStore(pen, &dist); PxVec3 e = a - v*dist; PxF32 size = 0.05f; const PxVec3 up(0.f, size, 0.f); const PxVec3 right(size, 0.f, 0.f); const PxVec3 forwards(0.f, 0.f, size); PxF32 size2 = 0.1f; const PxVec3 up2(0.f, size2, 0.f); const PxVec3 right2(size2, 0.f, 0.f); const PxVec3 forwards2(0.f, 0.f, size2); const PxMat44 m = PxMat44(PxIdentity); out << m << PxRenderOutput::LINES; out << 0xffff00ff << a << e; out << 0xff00ffff << a + up << a - up; out << 0xff00ffff << a + right << a - right; out << 0xff00ffff << a + forwards << a - forwards; out << 0xffff0000 << b + up2 << b - up2; out << 0xffff0000 << b + right2 << b - right2; out << 0xffff0000 << b + forwards2 << b - forwards2; out << 0xffff0000 << a << b; const PxVec3 c = a - v*10.f; out << 0xffff00ff << a << c; } static void drawManifoldPoint(const PersistentContact& manifold, const PxTransformV& trA, const PxTransformV& trB, const FloatVArg radius, PxRenderOutput& out, PxU32 color=0xffffff) { PX_UNUSED(color); const Vec3V localNormal = Vec3V_From_Vec4V(manifold.mLocalNormalPen); const Vec3V worldNormal = trB.rotate(localNormal); const Vec3V worldA = V3NegScaleSub(worldNormal, radius, trA.transform(manifold.mLocalPointA)); const Vec3V worldB = trB.transform(manifold.mLocalPointB); const FloatV pen = FSub(V4GetW(manifold.mLocalNormalPen), radius); PxVec3 a, b, v; V3StoreU(worldA, a); V3StoreU(worldB, b); V3StoreU(worldNormal, v); PxF32 dist; FStore(pen, &dist); PxVec3 e = a - v*dist; PxF32 size = 0.05f; const PxVec3 up(0.f, size, 0.f); const PxVec3 right(size, 0.f, 0.f); const PxVec3 forwards(0.f, 0.f, size); PxF32 size2 = 0.1f; const PxVec3 up2(0.f, size2, 0.f); const PxVec3 right2(size2, 0.f, 0.f); const PxVec3 forwards2(0.f, 0.f, size2); PxMat44 m = PxMat44(PxIdentity); out << 0xffff00ff << m << PxRenderOutput::LINES << a << e; out << 0xff00ffff << m << PxRenderOutput::LINES << a + up << a - up; out << 0xff00ffff << m << PxRenderOutput::LINES << a + right << a - right; out << 0xff00ffff << m << PxRenderOutput::LINES << a + forwards << a - forwards; out << 0xffff0000 << m << PxRenderOutput::LINES << b + up2 << b - up2; out << 0xffff0000 << m << PxRenderOutput::LINES << b + right2 << b - right2; out << 0xffff0000 << m << PxRenderOutput::LINES << b + forwards2 << b - forwards2; out << 0xffff0000 << m << PxRenderOutput::LINES << a << b; } static PxU32 gColors[8] = { 0xff0000ff, 0xff00ff00, 0xffff0000, 0xff00ffff, 0xffff00ff, 0xffffff00, 0xff000080, 0xff008000}; #endif // SIMD version Mat33V Gu::findRotationMatrixFromZAxis(const Vec3VArg to) { const FloatV one = FOne(); const FloatV threshold = FLoad(0.9999f); const FloatV e = V3GetZ(to); const FloatV f = FAbs(e); if(FAllGrtr(threshold, f)) { const FloatV vx = FNeg(V3GetY(to)); const FloatV vy = V3GetX(to); const FloatV h = FRecip(FAdd(one, e)); const FloatV hvx = FMul(h,vx); const FloatV hvxy = FMul(hvx, vy); const Vec3V col0 = V3Merge(FScaleAdd(hvx, vx, e), hvxy, vy); const Vec3V col1 = V3Merge(hvxy, FScaleAdd(h, FMul(vy, vy), e), FNeg(vx)); const Vec3V col2 = V3Merge(FNeg(vy), vx, e); return Mat33V(col0, col1, col2); } else { const FloatV two = FLoad(2.f); const Vec3V from = V3UnitZ(); const Vec3V absFrom = V3UnitY(); const Vec3V u = V3Sub(absFrom, from); const Vec3V v = V3Sub(absFrom, to); const FloatV dotU = V3Dot(u, u); const FloatV dotV = V3Dot(v, v); const FloatV dotUV = V3Dot(u, v); const FloatV c1 = FNeg(FDiv(two, dotU)); const FloatV c2 = FNeg(FDiv(two, dotV)); const FloatV c3 = FMul(c1, FMul(c2, dotUV)); const Vec3V c1u = V3Scale(u, c1); const Vec3V c2v = V3Scale(v, c2); const Vec3V c3v = V3Scale(v, c3); FloatV temp0 = V3GetX(c1u); FloatV temp1 = V3GetX(c2v); FloatV temp2 = V3GetX(c3v); Vec3V col0 = V3ScaleAdd(u, temp0, V3ScaleAdd(v, temp1, V3Scale(u, temp2))); col0 = V3SetX(col0, FAdd(V3GetX(col0), one)); temp0 = V3GetY(c1u); temp1 = V3GetY(c2v); temp2 = V3GetY(c3v); Vec3V col1 = V3ScaleAdd(u, temp0, V3ScaleAdd(v, temp1, V3Scale(u, temp2))); col1 = V3SetY(col1, FAdd(V3GetY(col1), one)); temp0 = V3GetZ(c1u); temp1 = V3GetZ(c2v); temp2 = V3GetZ(c3v); Vec3V col2 = V3ScaleAdd(u, temp0, V3ScaleAdd(v, temp1, V3Scale(u, temp2))); col2 = V3SetZ(col2, FAdd(V3GetZ(col2), one)); return Mat33V(col0, col1, col2); } } void PersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b; V3StoreU(trA.p, a); V3StoreU(trB.p, b); for(PxU32 i = 0; i< mNumContacts; ++i) { PersistentContact& m = mContactPoints[i]; drawManifoldPoint(m, trA, trB, out, gColors[i]); } #else PX_UNUSED(out); PX_UNUSED(trA); PX_UNUSED(trB); #endif } void PersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB, const FloatVArg radius) const { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b; V3StoreU(trA.p, a); V3StoreU(trB.p, b); for(PxU32 i = 0; i< mNumContacts; ++i) { PersistentContact& m = mContactPoints[i]; drawManifoldPoint(m, trA, trB, radius, out, gColors[i]); } #else PX_UNUSED(out); PX_UNUSED(trA); PX_UNUSED(trB); PX_UNUSED(radius); #endif } void PersistentContactManifold::drawManifold(const PersistentContact& m, PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const { #if VISUALIZE_PERSISTENT_CONTACT drawManifoldPoint(m, trA, trB, out, gColors[0]); #else PX_UNUSED(out); PX_UNUSED(trA); PX_UNUSED(trB); PX_UNUSED(m); #endif } void PersistentContactManifold::drawPoint(PxRenderOutput& out, const Vec3VArg p, const PxF32 size, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT const PxVec3 up(0.f, size, 0.f); const PxVec3 right(size, 0.f, 0.f); const PxVec3 forwards(0.f, 0.f, size); PxVec3 a; V3StoreU(p, a); const PxMat44 m(PxIdentity); out << color << m << PxRenderOutput::LINES << a + up << a - up; out << color << m << PxRenderOutput::LINES << a + right << a - right; out << color << m << PxRenderOutput::LINES << a + forwards << a - forwards; #else PX_UNUSED(out); PX_UNUSED(p); PX_UNUSED(size); PX_UNUSED(color); #endif } void PersistentContactManifold::drawLine(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b; V3StoreU(p0, a); V3StoreU(p1, b); const PxMat44 m(PxIdentity); out << color << m << PxRenderOutput::LINES << a << b; #else PX_UNUSED(out); PX_UNUSED(p0); PX_UNUSED(p1); PX_UNUSED(color); #endif } void PersistentContactManifold::drawTriangle(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, const Vec3VArg p2, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b, c; V3StoreU(p0, a); V3StoreU(p1, b); V3StoreU(p2, c); const PxMat44 m(PxIdentity); out << color << m << PxRenderOutput::TRIANGLES << a << b << c; #else PX_UNUSED(out); PX_UNUSED(p0); PX_UNUSED(p1); PX_UNUSED(p2); PX_UNUSED(color); #endif } void PersistentContactManifold::drawTetrahedron(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, const Vec3VArg p2, const Vec3VArg p3, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b, c, d; V3StoreU(p0, a); V3StoreU(p1, b); V3StoreU(p2, c); V3StoreU(p3, d); const PxMat44 m(PxIdentity); out << color << m << PxRenderOutput::LINES << a << b; out << color << m << PxRenderOutput::LINES << a << c; out << color << m << PxRenderOutput::LINES << a << d; out << color << m << PxRenderOutput::LINES << b << c; out << color << m << PxRenderOutput::LINES << b << d; out << color << m << PxRenderOutput::LINES << c << d; #else PX_UNUSED(out); PX_UNUSED(p0); PX_UNUSED(p1); PX_UNUSED(p2); PX_UNUSED(color); #endif } void PersistentContactManifold::drawPolygon(PxRenderOutput& out, const PxTransformV& transform, const Vec3V* points, PxU32 numVerts, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT for(PxU32 i=0; i<numVerts; ++i) { Vec3V tempV0 = points[i == 0 ? numVerts-1 : i-1]; Vec3V tempV1 = points[i]; drawLine(out, transform.transform(tempV0), transform.transform(tempV1), color); } #else PX_UNUSED(out); PX_UNUSED(transform); PX_UNUSED(points); PX_UNUSED(numVerts); PX_UNUSED(color); #endif } void PersistentContactManifold::drawPolygon(PxRenderOutput& out, const PxMatTransformV& transform, const Vec3V* points, PxU32 numVerts, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT for(PxU32 i=0; i<numVerts; ++i) { Vec3V tempV0 = points[i == 0 ? numVerts-1 : i-1]; Vec3V tempV1 = points[i]; drawLine(out, transform.transform(tempV0), transform.transform(tempV1), color); } #else PX_UNUSED(out); PX_UNUSED(transform); PX_UNUSED(points); PX_UNUSED(numVerts); PX_UNUSED(color); #endif } void PersistentContactManifold::recordWarmStart(PxU8* aIndices, PxU8* bIndices, PxU8& nbWarmStartPoints) { nbWarmStartPoints = mNumWarmStartPoints; for(PxU8 i = 0; i < mNumWarmStartPoints; ++i) { aIndices[i] = mAIndice[i]; bIndices[i] = mBIndice[i]; } } void PersistentContactManifold::setWarmStart(const PxU8* aIndices, const PxU8* bIndices, const PxU8 nbWarmStartPoints) { mNumWarmStartPoints = nbWarmStartPoints; for(PxU8 i = 0; i < nbWarmStartPoints; ++i) { mAIndice[i] = aIndices[i]; mBIndice[i] = bIndices[i]; } } // If a new point and the exisitng point's distance are within some replace breaking threshold, we will replace the existing point with the new point. // This is used for incremental manifold strategy. bool PersistentContactManifold::replaceManifoldPoint(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen , const FloatVArg replaceBreakingThreshold) { const FloatV shortestDist = FMul(replaceBreakingThreshold, replaceBreakingThreshold); for(PxU32 i=0; i<mNumContacts; ++i) { const PersistentContact& mp = mContactPoints[i]; const Vec3V diffB = V3Sub(mp.mLocalPointB, localPointB); const FloatV sqDifB = V3Dot(diffB, diffB); const Vec3V diffA = V3Sub(mp.mLocalPointA, localPointA); const FloatV sqDifA = V3Dot(diffA, diffA); const FloatV minSqDif = FMin(sqDifB, sqDifA); if(FAllGrtr(shortestDist, minSqDif)) { mContactPoints[i].mLocalPointA = localPointA; mContactPoints[i].mLocalPointB = localPointB; mContactPoints[i].mLocalNormalPen = localNormalPen; return true; } } return false; } PxU32 PersistentContactManifold::reduceContactSegment(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen) { const Vec3V p = localPointB; const Vec3V p0 = mContactPoints[0].mLocalPointB; const Vec3V p1 = mContactPoints[1].mLocalPointB; const Vec3V v0 = V3Sub(p0, p); const Vec3V v1 = V3Sub(p1, p); const FloatV dist0 = V3Dot(v0, v0); const FloatV dist1 = V3Dot(v1, v1); if(FAllGrtr(dist0, dist1)) { mContactPoints[1].mLocalPointA = localPointA; mContactPoints[1].mLocalPointB = localPointB; mContactPoints[1].mLocalNormalPen = localNormalPen; } else { mContactPoints[0].mLocalPointA = localPointA; mContactPoints[0].mLocalPointB = localPointB; mContactPoints[0].mLocalNormalPen = localNormalPen; } return 0; } PxU32 PersistentContactManifold::reduceContactsForPCM(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen) { bool chosen[5]; PxMemZero(chosen, sizeof(bool)*5); const FloatV negMax = FNeg(FMax()); PersistentContact tempContacts[5]; for(PxU32 i=0; i<4; ++i) { tempContacts[i] = mContactPoints[i]; } tempContacts[4].mLocalPointA = localPointA; tempContacts[4].mLocalPointB = localPointB; tempContacts[4].mLocalNormalPen = localNormalPen; //ML: we set the start point to be the 4th point FloatV maxDist = V4GetW(localNormalPen); PxI32 index = 4; //Choose deepest point for(PxI32 i=0; i<4; ++i) { const FloatV pen = V4GetW(tempContacts[i].mLocalNormalPen); if(FAllGrtr(maxDist, pen)) { maxDist = pen; index = i; } } chosen[index] = true; mContactPoints[0] = tempContacts[index]; //ML: we set the start point to be the 0th point Vec3V dir = V3Sub(tempContacts[0].mLocalPointB, mContactPoints[0].mLocalPointB); maxDist = V3Dot(dir, dir); index = 0; for(PxI32 i=1; i<5; ++i) { if(!chosen[i]) { dir = V3Sub(tempContacts[i].mLocalPointB, mContactPoints[0].mLocalPointB); const FloatV d = V3Dot(dir, dir); if(FAllGrtr(d, maxDist)) { maxDist = d; index = i; } } } //PX_ASSERT(chosen[index] == false); chosen[index] = true; mContactPoints[1] = tempContacts[index]; maxDist = negMax; for(PxI32 i=0; i<5; ++i) { if(!chosen[i]) { const FloatV sqDif = distancePointSegmentSquaredLocal(mContactPoints[0].mLocalPointB, mContactPoints[1].mLocalPointB, tempContacts[i].mLocalPointB); if(FAllGrtr(sqDif, maxDist)) { maxDist = sqDif; index = i; } } } //PX_ASSERT(chosen[index] == false); chosen[index] = true; mContactPoints[2]=tempContacts[index]; //Find point farthest away from segment tempContactPoints[0] - tempContactPoints[1] maxDist = negMax; for(PxI32 i=0; i<5; ++i) { if(!chosen[i]) { const FloatV sqDif = distancePointTriangleSquaredLocal( tempContacts[i].mLocalPointB, mContactPoints[0].mLocalPointB, mContactPoints[1].mLocalPointB, mContactPoints[2].mLocalPointB); if(FAllGrtr(sqDif, maxDist)) { maxDist= sqDif; index = i; } } } //PX_ASSERT(chosen[index] == false); if(chosen[index] == true) { //if we don't have any new contacts, which means the leftover contacts are inside the triangles mNumContacts = 3; return 0; } else { chosen[index] = true; mContactPoints[3] = tempContacts[index]; } //Final pass, we work out the index that we didn't choose and bind it to its closest point. We then consider whether we want to swap the point if the //point we were about to discard is deeper... PxU32 notChosenIndex = 0; for(PxU32 a = 0; a < 5; ++a) { if(!chosen[a]) { notChosenIndex = a; break; } } FloatV closest = FMax(); index = 0; for(PxI32 a = 0; a < 4; ++a) { Vec3V dif = V3Sub(mContactPoints[a].mLocalPointA, tempContacts[notChosenIndex].mLocalPointA); const FloatV d2 = V3Dot(dif, dif); if(FAllGrtr(closest, d2)) { closest = d2; index = a; } } if(FAllGrtr(V4GetW(mContactPoints[index].mLocalNormalPen), V4GetW(tempContacts[notChosenIndex].mLocalNormalPen))) { //Swap mContactPoints[index] = tempContacts[notChosenIndex]; } return 0; } // This function is for box/convexHull vs box/convexHull. void PersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg normal, const PxTransformV& transf1, const FloatVArg contactOffset) { //add the manifold contacts; PxU32 contactCount = 0; for(PxU32 i=0; (i< mNumContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++i) { const PersistentContact& p = getContactPoint(i); const FloatV dist = V4GetW(p.mLocalNormalPen); //Either the newly created points or the cache points might have dist/penetration larger than contactOffset if(FAllGrtrOrEq(contactOffset, dist)) { const Vec3V worldP = transf1.transform(p.mLocalPointB); outputPCMContact(contactBuffer, contactCount, worldP, normal, dist); } } contactBuffer.count = contactCount; } // This function is for direct implementation for box vs box. We don't need to discard the contacts based on whether the contact offset is larger than penetration/dist because // the direct implementation will guarantee the penetration/dist won't be larger than the contact offset. Also, we won't have points from the cache if the direct implementation // of box vs box is called. void PersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg normal, const PxMatTransformV& transf1) { //add the manifold contacts; PxU32 contactCount = 0; for(PxU32 i=0; (i< mNumContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++i) { const PersistentContact& p = getContactPoint(i); const Vec3V worldP = transf1.transform(p.mLocalPointB); const FloatV dist = V4GetW(p.mLocalNormalPen); outputPCMContact(contactBuffer, contactCount, worldP, normal, dist); } contactBuffer.count = contactCount; } // This function is for sphere/capsule vs other primitives. We treat sphere as a point and capsule as a segment in the contact gen and store the sphere center or a point in the segment for capsule // in the manifold. void PersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg normal, const Vec3VArg projectionNormal, const PxTransformV& transf0, const FloatVArg radius, const FloatVArg contactOffset) { //add the manifold contacts; PxU32 contactCount = 0; for(PxU32 i=0; (i< mNumContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++i) { const PersistentContact& p = getContactPoint(i); const FloatV dist = FSub(V4GetW(p.mLocalNormalPen), radius); //The newly created points should have a dist < contactOffset. However, points might come from the PCM contact cache so we might still have points which are //larger than contactOffset. The reason why we don't want to discard the contacts in the contact cache whose dist > contactOffset is because the contacts may //only temporarily become separated. The points still project onto roughly the same spot but so, if the bodies move together again, the contacts may be valid again. //This is important when simulating at large time-steps because GJK can only generate 1 point of contact and missing contacts for just a single frame with large time-steps //may introduce noticeable instability. if(FAllGrtrOrEq(contactOffset, dist)) { const Vec3V worldP = V3NegScaleSub(projectionNormal, radius, transf0.transform(p.mLocalPointA)); outputPCMContact(contactBuffer, contactCount, worldP, normal, dist); } } contactBuffer.count = contactCount; } // This function is used in the box/convexhull full manifold contact genenation. We will pass in a list of manifold contacts. If the number of contacts are more than // GU_MANIFOLD_CACHE_SIZE, we will need to do contact reduction while we are storing the chosen manifold contacts from the manifold contact list to the manifold contact // buffer. void PersistentContactManifold::addBatchManifoldContacts(const PersistentContact* manifoldContacts, PxU32 numPoints, PxReal toleranceLength) { if(numPoints <= GU_MANIFOLD_CACHE_SIZE) { for(PxU32 i=0; i<numPoints; ++i) { mContactPoints[i].mLocalPointA = manifoldContacts[i].mLocalPointA; mContactPoints[i].mLocalPointB = manifoldContacts[i].mLocalPointB; mContactPoints[i].mLocalNormalPen = manifoldContacts[i].mLocalNormalPen; } mNumContacts = PxTo8(numPoints); } else { reduceBatchContacts(manifoldContacts, numPoints, toleranceLength); mNumContacts = GU_MANIFOLD_CACHE_SIZE; } } // This function is for the plane and box contact gen. If the number of points passed in is more than 4, we need to do contact reduction void PersistentContactManifold::addBatchManifoldContactsCluster(const PersistentContact* manifoldContacts, PxU32 numPoints) { if(numPoints <= GU_MANIFOLD_CACHE_SIZE) { for(PxU32 i=0; i<numPoints; ++i) { mContactPoints[i].mLocalPointA = manifoldContacts[i].mLocalPointA; mContactPoints[i].mLocalPointB = manifoldContacts[i].mLocalPointB; mContactPoints[i].mLocalNormalPen = manifoldContacts[i].mLocalNormalPen; } mNumContacts = PxTo8(numPoints); } else { reduceBatchContactsCluster(manifoldContacts, numPoints); mNumContacts = GU_MANIFOLD_CACHE_SIZE; } } // This function is called by addBatchManifoldContactCluster. The logic in this funtion is: // (1)get the depest-penetrated contacts and store it in mContactPoints[0] // (2)get the furthest away point from mContactPoints[0] and store in mContactPoints[1] // (3)calculate the min and max distance point away the segment (mContactPoints[0] and mContactPoints[1]) and store the max distance point to mContactPoints[2] // (4)if the min and max distance on the same side of the segment, we need to chose the min distance point again and store this point to mContactPoints[3]; // (5)cluster around that 4 points and chose the deepest points // (6)reassign contact points void PersistentContactManifold::reduceBatchContactsCluster(const PersistentContact* manifoldPoints, PxU32 numPoints) { //get the deepest points bool chosen[64]; PxMemZero(chosen, sizeof(bool)*numPoints); const FloatV max = FMax(); const FloatV nmax = FNeg(max); FloatV maxDist = max; PxU32 index = 0; PxU32 indices[4]; //get the deepest point for(PxU32 i=0; i<numPoints; ++i) { const FloatV dist = V4GetW(manifoldPoints[i].mLocalNormalPen); if(FAllGrtr(maxDist, dist)) { maxDist = dist; index = i; } } //keep the furthest points in the first position mContactPoints[0] = manifoldPoints[index]; chosen[index] = true; indices[0] = index; //calculate the furthest away points from mContactPoints[0] Vec3V v = V3Sub(manifoldPoints[0].mLocalPointB, mContactPoints[0].mLocalPointB); maxDist = V3Dot(v, v); index = 0; for(PxU32 i=1; i<numPoints; ++i) { v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB); const FloatV d = V3Dot(v, v); if(FAllGrtr(d, maxDist)) { maxDist = d; index = i; } } //PX_ASSERT(chosen[index] == false); mContactPoints[1] = manifoldPoints[index]; chosen[index] = true; indices[1] = index; maxDist = nmax; index = GU_MANIFOLD_INVALID_INDEX; v = V3Sub(mContactPoints[1].mLocalPointB, mContactPoints[0].mLocalPointB); const Vec3V cn0 = Vec3V_From_Vec4V(mContactPoints[0].mLocalNormalPen); Vec3V norm = V3Cross(v, cn0); const FloatV sqLen = V3Dot(norm, norm); norm = V3Sel(FIsGrtr(sqLen, FZero()), V3ScaleInv(norm, FSqrt(sqLen)), cn0); FloatV minDist = max; PxU32 index1 = GU_MANIFOLD_INVALID_INDEX; //calculate the min and max point away from the segment for(PxU32 i=0; i<numPoints; ++i) { if(!chosen[i]) { v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDist)) { maxDist = d; index = i; } if(FAllGrtr(minDist, d)) { minDist = d; index1 = i; } } } //PX_ASSERT(chosen[index] == false && chosen[index1] == false); mContactPoints[2] = manifoldPoints[index]; chosen[index] = true; indices[2] = index; //if min and max in the same side, chose again const FloatV temp = FMul(minDist, maxDist); if(FAllGrtr(temp, FZero())) { //chose again maxDist = nmax; for(PxU32 i=0; i<numPoints; ++i) { if(!chosen[i]) { v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDist)) { maxDist = d; index1 = i; } } } } mContactPoints[3] = manifoldPoints[index1]; chosen[index1] = true; indices[3] = index1; //cluster around that 4 points and chose the deepest points for(PxU32 i=0; i<numPoints; ++i) { if(!chosen[i]) { maxDist = max; const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen); index = 0; for(PxU32 j=0; j<4; ++j) { const Vec3V v1 = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[j].mLocalPointB); const FloatV dist = V3Dot(v1, v1); if(FAllGrtr(maxDist, dist)) { maxDist = dist; index = j; } } //check to see whether the penetration is deeper than the point in mContactPoints const FloatV tempPen = V4GetW(manifoldPoints[indices[index]].mLocalNormalPen); if(FAllGrtr(tempPen, pen)) { //swap the indices indices[index] = i; } } } mContactPoints[0] = manifoldPoints[indices[0]]; mContactPoints[1] = manifoldPoints[indices[1]]; mContactPoints[2] = manifoldPoints[indices[2]]; mContactPoints[3] = manifoldPoints[indices[3]]; } // This function is for box/convexhull full contact generation. If the numPoints > 4, we will reduce the contact points to 4 void PersistentContactManifold::reduceBatchContacts(const PersistentContact* manifoldPoints, PxU32 numPoints, PxReal tolereanceLength) { PxU8 chosenIndices[4]; PxU8 candidates[64]; const FloatV zero = FZero(); const FloatV max = FMax(); const FloatV nmax = FNeg(max); FloatV maxPen = V4GetW(manifoldPoints[0].mLocalNormalPen); FloatV minPen = maxPen; PxU32 index = 0; candidates[0] = 0; PxU32 candidateIndex = 0; PxU32 nbCandiates = numPoints; //keep the deepest point, candidateIndex will be the same as index for(PxU32 i = 1; i<numPoints; ++i) { //at the begining candidates and indices will be the same candidates[i] = PxU8(i); const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen); minPen = FMax(minPen, pen); if(FAllGrtr(maxPen, pen)) { maxPen = pen; index = i; candidateIndex = i; } } //keep the deepest points in the first position chosenIndices[0] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; //indices[index] = nbCandiates; //calculate the furthest away points Vec3V v = V3Sub(manifoldPoints[candidates[0]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB); FloatV maxDist = V3Dot(v, v); index = candidates[0]; candidateIndex = 0; for(PxU32 i = 1; i<nbCandiates; ++i) { v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB); const FloatV d = V3Dot(v, v); if(FAllGrtr(d, maxDist)) { maxDist = d; index = candidates[i]; candidateIndex = i; } } chosenIndices[1] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; v = V3Sub(manifoldPoints[chosenIndices[1]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB); const Vec3V cn0 = Vec3V_From_Vec4V(manifoldPoints[chosenIndices[0]].mLocalNormalPen); Vec3V norm = V3Cross(v, cn0); const FloatV sqLen = V3Dot(norm, norm); norm = V3Sel(FIsGrtr(sqLen, zero), V3ScaleInv(norm, FSqrt(sqLen)), cn0); //reset maxDist and index maxDist = nmax; index = GU_MANIFOLD_INVALID_INDEX; candidateIndex = GU_MANIFOLD_INVALID_INDEX; FloatV minDist = max; PxU32 index1 = GU_MANIFOLD_INVALID_INDEX; PxU32 candidateIndex1 = GU_MANIFOLD_INVALID_INDEX; //calculate the min and max point away from the segment for(PxU32 i = 0; i<nbCandiates; ++i) { v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDist)) { maxDist = d; index = candidates[i]; candidateIndex = i; } if(FAllGrtr(minDist, d)) { minDist = d; index1 = candidates[i]; candidateIndex1 = i; } } chosenIndices[2] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; if(nbCandiates == candidateIndex1) candidateIndex1 = candidateIndex; //if min and max in the same side, chose again const FloatV temp = FMul(minDist, maxDist); if(FAllGrtr(temp, zero)) { //chose again maxDist = nmax; for(PxU32 i = 0; i < nbCandiates; ++i) { v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDist)) { maxDist = d; index1 = candidates[i]; candidateIndex1 = i; } } } chosenIndices[3] = PxU8(index1); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex1] = candidates[nbCandiates]; const FloatV eps = FLoad(tolereanceLength * 0.02f); const BoolV con = BAnd(FIsGrtr(eps, maxPen), FIsGrtr(minPen, eps)); if(BAllEqTTTT(con)) { //post process for(PxU32 i = 0; i < 4; ++i) { FloatV pen = V4GetW(manifoldPoints[chosenIndices[i]].mLocalNormalPen); if(FAllGrtr(pen, eps)) { candidateIndex = GU_MANIFOLD_INVALID_INDEX; for(PxU32 j = 0; j < nbCandiates; ++j) { const FloatV pen1 = V4GetW(manifoldPoints[candidates[j]].mLocalNormalPen); if(FAllGrtr(pen, pen1) && FAllGrtr(eps, pen1)) { pen = pen1; candidateIndex = j; } } if(candidateIndex < nbCandiates) { const PxU8 originalIndex = chosenIndices[i]; chosenIndices[i] = candidates[candidateIndex]; candidates[candidateIndex] = originalIndex; } } mContactPoints[i] = manifoldPoints[chosenIndices[i]]; } } else { for(PxU32 i = 0; i < 4; ++i) { mContactPoints[i] = manifoldPoints[chosenIndices[i]]; } } } // This function is for capsule full contact generation. If the numPoints > 2, we will reduce the contact points to 2 void PersistentContactManifold::reduceBatchContacts2(const PersistentContact* manifoldPoints, PxU32 numPoints) { PX_ASSERT(numPoints < 64); bool chosen[64]; PxMemZero(chosen, sizeof(bool)*numPoints); FloatV maxDis = V4GetW(manifoldPoints[0].mLocalNormalPen); PxI32 index = 0; //keep the deepest point for(PxU32 i=1; i<numPoints; ++i) { const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen); if(FAllGrtr(maxDis, pen)) { maxDis = pen; index = PxI32(i); } } //keep the deepest points in the first position mContactPoints[0] = manifoldPoints[index]; chosen[index] = true; //calculate the furthest away points Vec3V v = V3Sub(manifoldPoints[0].mLocalPointB, mContactPoints[0].mLocalPointB); maxDis = V3Dot(v, v); index = 0; for(PxU32 i=1; i<numPoints; ++i) { v = V3Sub(manifoldPoints[i].mLocalPointB, mContactPoints[0].mLocalPointB); const FloatV d = V3Dot(v, v); if(FAllGrtr(d, maxDis)) { maxDis = d; index = PxI32(i); } } //PX_ASSERT(chosen[index] == false); mContactPoints[1] = manifoldPoints[index]; chosen[index] = true; PxI32 secondIndex = index; FloatV maxDepth = V4GetW(manifoldPoints[index].mLocalNormalPen); for(PxU32 i = 0; i < numPoints; ++i) { if(!chosen[i]) { const Vec3V d0 = V3Sub(mContactPoints[0].mLocalPointB, manifoldPoints[i].mLocalPointB); const Vec3V d1 = V3Sub(mContactPoints[1].mLocalPointB, manifoldPoints[i].mLocalPointB); const FloatV dd0 = V3Dot(d0, d0); const FloatV dd1 = V3Dot(d1, d1); if(FAllGrtr(dd0, dd1)) { //This clusters to point 1 if(FAllGrtr(maxDepth, V4GetW(manifoldPoints[i].mLocalNormalPen))) { secondIndex = PxI32(i); } } } } if(secondIndex != index) { mContactPoints[1] = manifoldPoints[secondIndex]; } } PxU32 PersistentContactManifold::addManifoldPoint(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen, const FloatVArg replaceBreakingThreshold) { if(replaceManifoldPoint(localPointA, localPointB, localNormalPen, replaceBreakingThreshold)) //replace the new point with the old one return 0; switch(mNumContacts) { case 0: case 1: case 2: case 3: mContactPoints[mNumContacts].mLocalPointA = localPointA; mContactPoints[mNumContacts].mLocalPointB = localPointB; mContactPoints[mNumContacts++].mLocalNormalPen = localNormalPen; return 1; default: return reduceContactsForPCM(localPointA, localPointB, localNormalPen);//should be always return zero }; } // This function is for capsule vs other primitives. If the manifold originally has contacts and we can incrementally add a point at a time, we will // use this function to add a point to manifold. If the number of contacts inside the manifold is more than 2, we will reduce contacts to 2 points. PxU32 PersistentContactManifold::addManifoldPoint2(const Vec3VArg localPointA, const Vec3VArg localPointB, const Vec4VArg localNormalPen, const FloatVArg replaceBreakingThreshold) { if(replaceManifoldPoint(localPointA, localPointB, localNormalPen, replaceBreakingThreshold)) //replace the new point with the old one return 0; switch(mNumContacts) { case 0: case 1: mContactPoints[mNumContacts].mLocalPointA = localPointA; mContactPoints[mNumContacts].mLocalPointB = localPointB; mContactPoints[mNumContacts++].mLocalNormalPen = localNormalPen; return 1; case 2: return reduceContactSegment(localPointA, localPointB, localNormalPen); default: PX_ASSERT(0); }; return 0; } // This function is used in the capsule full manifold contact genenation. We will pass in a list of manifold contacts. If the number of contacts are more than // 2, we will need to do contact reduction while we are storing the chosen manifold contacts from the manifold contact list to the manifold contact buffer. void PersistentContactManifold::addBatchManifoldContacts2(const PersistentContact* manifoldContacts, PxU32 numPoints) { if(numPoints <= 2) { for(PxU32 i=0; i<numPoints; ++i) { mContactPoints[i].mLocalPointA = manifoldContacts[i].mLocalPointA; mContactPoints[i].mLocalPointB = manifoldContacts[i].mLocalPointB; mContactPoints[i].mLocalNormalPen = manifoldContacts[i].mLocalNormalPen; } mNumContacts = PxTo8(numPoints); } else { reduceBatchContacts2(manifoldContacts, numPoints); mNumContacts = 2; } } // If the patch total number of manifold contacts are less than or equal to GU_SINGLE_MANIFOLD_CACHE_SIZE, we will add the manifold contacts in the contact stream to the manifold contact buffer // which is associated to this single persistent contact manifold. Otherwise, we will reduce the manifold contacts to GU_SINGLE_MANIFOLD_CACHE_SIZE. FloatV SinglePersistentContactManifold::addBatchManifoldContactsConvex(const MeshPersistentContact* manifoldContact, PxU32 numContactExt, PCMContactPatch& patch, const FloatVArg replaceBreakingThreshold) { PX_UNUSED(replaceBreakingThreshold); if(patch.mTotalSize <= GU_SINGLE_MANIFOLD_CACHE_SIZE) { PCMContactPatch* currentPatch = &patch; //this is because we already add the manifold contacts into manifoldContact array PxU32 tempNumContacts = 0; while(currentPatch) { for(PxU32 j=currentPatch->mStartIndex; j<currentPatch->mEndIndex; ++j) { mContactPoints[tempNumContacts++] = manifoldContact[j]; } currentPatch = currentPatch->mNextPatch; } mNumContacts = tempNumContacts; return patch.mPatchMaxPen; } else { //contact reduction const FloatV maxPen = reduceBatchContactsConvex(manifoldContact, numContactExt, patch); mNumContacts = GU_SINGLE_MANIFOLD_CACHE_SIZE; return maxPen; } } FloatV SinglePersistentContactManifold::addBatchManifoldContactsSphere(const MeshPersistentContact* manifoldContact, PxU32 numContactExt, PCMContactPatch& patch, const FloatVArg replaceBreakingThreshold) { PX_UNUSED(replaceBreakingThreshold); const FloatV maxPen = reduceBatchContactsSphere(manifoldContact, numContactExt, patch); mNumContacts = 1; return maxPen; } FloatV SinglePersistentContactManifold::addBatchManifoldContactsCapsule(const MeshPersistentContact* manifoldContact, PxU32 numContactExt, PCMContactPatch& patch, const FloatVArg replaceBreakingThreshold) { PX_UNUSED(replaceBreakingThreshold); if(patch.mTotalSize <=GU_CAPSULE_MANIFOLD_CACHE_SIZE) { PCMContactPatch* currentPatch = &patch; //this is because we already add the manifold contacts into manifoldContact array PxU32 tempNumContacts = 0; while(currentPatch) { for(PxU32 j=currentPatch->mStartIndex; j<currentPatch->mEndIndex; ++j) { mContactPoints[tempNumContacts++] = manifoldContact[j]; } currentPatch = currentPatch->mNextPatch; } mNumContacts = tempNumContacts; return patch.mPatchMaxPen; } else { const FloatV maxPen = reduceBatchContactsCapsule(manifoldContact, numContactExt, patch); mNumContacts = GU_CAPSULE_MANIFOLD_CACHE_SIZE; return maxPen; } } FloatV SinglePersistentContactManifold::reduceBatchContactsSphere(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch) { PX_UNUSED(numContacts); FloatV max = FMax(); FloatV maxDist = max; PxI32 index = -1; PCMContactPatch* currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen); if(FAllGrtr(maxDist, pen)) { maxDist = pen; index = PxI32(i); } } currentPatch = currentPatch->mNextPatch; } PX_ASSERT(index!=-1); mContactPoints[0] = manifoldContactExt[index]; return maxDist; } FloatV SinglePersistentContactManifold::reduceBatchContactsCapsule(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch) { bool* chosen = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*numContacts)); PxMemZero(chosen, sizeof(bool)*numContacts); const FloatV max = FMax(); FloatV maxDis = max; PxI32 index = -1; FloatV maxPen = max; PCMContactPatch* currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen); if(FAllGrtr(maxDis, pen)) { maxDis = pen; index = PxI32(i); } } currentPatch = currentPatch->mNextPatch; } chosen[index] = true; mContactPoints[0] = manifoldContactExt[index]; maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen)); //calculate the furthest away points Vec3V v = V3Sub(manifoldContactExt[patch.mStartIndex].mLocalPointB, mContactPoints[0].mLocalPointB); maxDis = V3Dot(v, v); index = PxI32(patch.mStartIndex); currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { v = V3Sub(manifoldContactExt[i].mLocalPointB, mContactPoints[0].mLocalPointB); const FloatV d = V3Dot(v, v); if(FAllGrtr(d, maxDis)) { maxDis = d; index = PxI32(i); } } currentPatch = currentPatch->mNextPatch; } //PX_ASSERT(chosen[index] == false); chosen[index] = true; mContactPoints[1] = manifoldContactExt[index]; maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen)); //keep the second deepest point maxDis = max; currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { if(!chosen[i]) { const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen); //const FloatV v = V3Dot(manifoldContactExt[i].mLocalPointB, manifoldContactExt[i].mLocalPointB); if(FAllGrtr(maxDis, pen)) { maxDis = pen; index = PxI32(i); } } } currentPatch = currentPatch->mNextPatch; } //PX_ASSERT(chosen[index] == false); chosen[index] = true; mContactPoints[2] = manifoldContactExt[index]; maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen)); return maxPen; } FloatV SinglePersistentContactManifold::reduceBatchContactsConvex(const MeshPersistentContact* manifoldContactExt, PxU32 numContacts, PCMContactPatch& patch) { bool* chosen = reinterpret_cast<bool*>(PxAlloca(sizeof(bool)*numContacts)); PxMemZero(chosen, sizeof(bool)*numContacts); const FloatV max = FMax(); const FloatV nmax = FNeg(max); FloatV maxDis = nmax; PxU32 index = GU_MANIFOLD_INVALID_INDEX; PCMContactPatch* currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { //const FloatV pen = V4GetW(manifoldContactExt[i].localNormalPen); const FloatV v = V3Dot(manifoldContactExt[i].mLocalPointB, manifoldContactExt[i].mLocalPointB); if(FAllGrtr(v, maxDis)) { maxDis = v; index = i; } } currentPatch = currentPatch->mNextPatch; } chosen[index] = true; const Vec3V contact0 = manifoldContactExt[index].mLocalPointB; mContactPoints[0] = manifoldContactExt[index]; FloatV maxPen = V4GetW(manifoldContactExt[index].mLocalNormalPen); //calculate the furthest away points Vec3V v = V3Sub(manifoldContactExt[patch.mStartIndex].mLocalPointB, contact0); maxDis = V3Dot(v, v); index = patch.mStartIndex; currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { v = V3Sub(manifoldContactExt[i].mLocalPointB, contact0); const FloatV d = V3Dot(v, v); if(FAllGrtr(d, maxDis)) { maxDis = d; index = i; } } currentPatch = currentPatch->mNextPatch; } //PX_ASSERT(chosen[index] == false); chosen[index] = true; const Vec3V contact1 = manifoldContactExt[index].mLocalPointB; mContactPoints[1] = manifoldContactExt[index]; maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen)); maxDis = nmax; index = GU_MANIFOLD_INVALID_INDEX; v = V3Sub(contact1, contact0); const Vec3V cn0 = Vec3V_From_Vec4V(mContactPoints[0].mLocalNormalPen); Vec3V norm = V3Cross(v, cn0); const FloatV sqLen = V3Dot(norm, norm); norm = V3Sel(FIsGrtr(sqLen, FZero()), V3ScaleInv(norm, FSqrt(sqLen)), cn0); FloatV minDis = max; PxU32 index1 = GU_MANIFOLD_INVALID_INDEX; //calculate the point furthest way to the segment currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { if(!chosen[i]) { v = V3Sub(manifoldContactExt[i].mLocalPointB, contact0); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDis)) { maxDis = d; index = i; } if(FAllGrtr(minDis, d)) { minDis = d; index1 = i; } } } currentPatch = currentPatch->mNextPatch; } //PX_ASSERT(chosen[index] == false); chosen[index] = true; mContactPoints[2] = manifoldContactExt[index]; maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index].mLocalNormalPen)); //if min and max in the same side, choose again const FloatV temp = FMul(minDis, maxDis); if(FAllGrtr(temp, FZero())) { //choose again maxDis = nmax; //calculate the point furthest way to the segment currentPatch = &patch; while(currentPatch) { for(PxU32 i=currentPatch->mStartIndex; i<currentPatch->mEndIndex; ++i) { if(!chosen[i]) { v = V3Sub(manifoldContactExt[i].mLocalPointB, contact0); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDis)) { maxDis = d; index1 = i; } } } currentPatch = currentPatch->mNextPatch; } } //PX_ASSERT(chosen[index1] == false); chosen[index1] = true; mContactPoints[3] = manifoldContactExt[index1]; maxPen = FMin(maxPen, V4GetW(manifoldContactExt[index1].mLocalNormalPen)); const PxU32 NB_TO_ADD = GU_SINGLE_MANIFOLD_CACHE_SIZE - 4; FloatV pens[NB_TO_ADD]; PxU32 inds[NB_TO_ADD]; for(PxU32 a = 0; a < NB_TO_ADD; ++a) { pens[a] = FMax(); inds[a] = 0; } { currentPatch = &patch; while(currentPatch) { for(PxU32 i = currentPatch->mStartIndex; i < currentPatch->mEndIndex; ++i) { if(!chosen[i]) { const FloatV pen = V4GetW(manifoldContactExt[i].mLocalNormalPen); for(PxU32 a = 0; a < NB_TO_ADD; ++a) { if(FAllGrtr(pens[a], pen)) { for(PxU32 b = a + 1; b < NB_TO_ADD; ++b) { pens[b] = pens[b - 1]; inds[b] = inds[b - 1]; } pens[a] = pen; inds[a] = i; break; } } } } currentPatch = currentPatch->mNextPatch; } for(PxU32 i = 0; i < NB_TO_ADD; ++i) { mContactPoints[i + 4] = manifoldContactExt[inds[i]]; maxPen = FMin(maxPen, pens[i]); } } return maxPen; } PxU32 SinglePersistentContactManifold::reduceContacts(MeshPersistentContact* manifoldPoints, PxU32 numPoints) { PxU8 chosenIndices[GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE]; PxU8* candidates = reinterpret_cast<PxU8*>(PxAlloca(sizeof(PxU8) * numPoints)); //(1) Remove duplicates... for(PxU32 i = 0; i < numPoints; ++i) { Vec3V localPointB = manifoldPoints[i].mLocalPointB; for(PxU32 j = i+1; j < numPoints; ++j) { if(V3AllGrtr(V3Eps(), V3Abs(V3Sub(localPointB, manifoldPoints[j].mLocalPointB)))) { manifoldPoints[j] = manifoldPoints[numPoints - 1]; j--; numPoints--; } } } if(numPoints <= GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE) return numPoints; const FloatV max = FMax(); const FloatV nmax = FNeg(max); FloatV maxPen = V4GetW(manifoldPoints[0].mLocalNormalPen); PxU32 index = 0; candidates[0] = 0; PxU32 candidateIndex = 0; PxU32 nbCandiates = numPoints; MeshPersistentContact newManifold[GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE]; //keep the deepest point for(PxU32 i = 1; i<numPoints; ++i) { //at the begining candidates and indices will be the same candidates[i] = PxU8(i); const FloatV pen = V4GetW(manifoldPoints[i].mLocalNormalPen); if(FAllGrtr(maxPen, pen)) { maxPen = pen; index = i; candidateIndex = i; } } //keep the deepest points in the first position chosenIndices[0] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; //keep the deepest points in the first position newManifold[0] = manifoldPoints[chosenIndices[0]]; //calculate the furthest away points Vec3V v = V3Sub(manifoldPoints[candidates[0]].mLocalPointB, newManifold[0].mLocalPointB); maxPen = V3Dot(v, v); index = candidates[0]; candidateIndex = 0; for(PxU32 i = 1; i<nbCandiates; ++i) { v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, manifoldPoints[chosenIndices[0]].mLocalPointB); const FloatV d = V3Dot(v, v); if(FAllGrtr(d, maxPen)) { maxPen = d; index = candidates[i]; candidateIndex = i; } } chosenIndices[1] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; newManifold[1] = manifoldPoints[chosenIndices[1]]; v = V3Sub(newManifold[1].mLocalPointB, newManifold[0].mLocalPointB); const Vec3V cn0 = Vec3V_From_Vec4V(newManifold[0].mLocalNormalPen); Vec3V norm = V3Cross(v, cn0); FloatV maxDist = nmax; FloatV minDist = max; index = GU_MANIFOLD_INVALID_INDEX; PxU32 index1 = GU_MANIFOLD_INVALID_INDEX; PxU32 candidateIndex1 = GU_MANIFOLD_INVALID_INDEX; //calculate the point furthest way to the segment for(PxU32 i = 0; i<nbCandiates; ++i) { v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, newManifold[0].mLocalPointB); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDist)) { maxDist = d; index = candidates[i]; candidateIndex = i; } if(FAllGrtr(minDist, d)) { minDist = d; index1 = candidates[i]; candidateIndex1 = i; } } chosenIndices[2] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; newManifold[2] = manifoldPoints[chosenIndices[2]]; if(nbCandiates == candidateIndex1) candidateIndex1 = candidateIndex; const FloatV temp = FMul(minDist, maxDist); if(FAllGrtr(temp, FZero())) { //chose again maxDist = nmax; for(PxU32 i = 0; i < nbCandiates; ++i) { v = V3Sub(manifoldPoints[candidates[i]].mLocalPointB, newManifold[0].mLocalPointB); const FloatV d = V3Dot(v, norm); if(FAllGrtr(d, maxDist)) { maxDist = d; index1 = candidates[i]; candidateIndex1 = i; } } } chosenIndices[3] = PxU8(index1); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex1] = candidates[nbCandiates]; newManifold[3] = manifoldPoints[chosenIndices[3]]; maxDist = max; index = GU_MANIFOLD_INVALID_INDEX; candidateIndex = GU_MANIFOLD_INVALID_INDEX; //choose the 5 point, second deepest in the left overlap point for(PxU32 i = 0; i < nbCandiates; ++i) { const FloatV pen = V4GetW(manifoldPoints[candidates[i]].mLocalNormalPen); if(FAllGrtr(maxDist, pen)) { maxDist = pen; index = candidates[i]; candidateIndex = i; } } chosenIndices[4] = PxU8(index); //move the chosen indices out of the candidates indices nbCandiates = nbCandiates - 1; candidates[candidateIndex] = candidates[nbCandiates]; newManifold[4] = manifoldPoints[chosenIndices[4]]; //copy the new manifold back for(PxU32 i = 0; i<GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; ++i) { manifoldPoints[i] = newManifold[i]; } return GU_SINGLE_MANIFOLD_SINGLE_POLYGONE_CACHE_SIZE; } FloatV SinglePersistentContactManifold::refreshContactPoints(const PxMatTransformV& aToB, const FloatVArg projectBreakingThreshold, const FloatVArg /*contactOffset*/) { const FloatV sqProjectBreakingThreshold = FMul(projectBreakingThreshold, projectBreakingThreshold); FloatV maxPen = FZero(); // first refresh worldspace positions and distance for(PxU32 i=mNumContacts; i > 0; --i) { MeshPersistentContact& manifoldPoint = mContactPoints[i-1]; const Vec3V localAInB = aToB.transform( manifoldPoint.mLocalPointA ); // from a to b const Vec3V localBInB = manifoldPoint.mLocalPointB; const Vec3V v = V3Sub(localAInB, localBInB); const Vec3V localNormal = Vec3V_From_Vec4V(manifoldPoint.mLocalNormalPen); // normal in b space const FloatV dist= V3Dot(v, localNormal); const Vec3V projectedPoint = V3NegScaleSub(localNormal, dist, localAInB);//manifoldPoint.worldPointA - manifoldPoint.worldPointB * manifoldPoint.m_distance1; const Vec3V projectedDifference = V3Sub(localBInB, projectedPoint); const FloatV distance2d = V3Dot(projectedDifference, projectedDifference); //const BoolV con = BOr(FIsGrtr(dist, contactOffset), FIsGrtr(distance2d, sqProjectBreakingThreshold)); const BoolV con = FIsGrtr(distance2d, sqProjectBreakingThreshold); if(BAllEqTTTT(con)) { removeContactPoint(i-1); } else { manifoldPoint.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), dist); maxPen = FMin(maxPen, dist); } } return maxPen; } void SinglePersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b; V3StoreU(trA.p, a); V3StoreU(trB.p, b); for(PxU32 i = 0; i< mNumContacts; ++i) { const MeshPersistentContact& m = mContactPoints[i]; drawManifoldPoint(m, trA, trB, out, gColors[i]); } #else PX_UNUSED(out); PX_UNUSED(trA); PX_UNUSED(trB); #endif } void MultiplePersistentContactManifold::drawManifold(PxRenderOutput& out, const PxTransformV& trA, const PxTransformV& trB) const { for(PxU32 i=0; i<mNumManifolds; ++i) { const SinglePersistentContactManifold* manifold = getManifold(i); manifold->drawManifold(out, trA, trB); } } void MultiplePersistentContactManifold::drawLine(PxRenderOutput& out, const Vec3VArg p0, const Vec3VArg p1, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT PxVec3 a, b; V3StoreU(p0, a); V3StoreU(p1, b); PxMat44 m = PxMat44(PxIdentity); out << color << m << PxRenderOutput::LINES << a << b; #else PX_UNUSED(out); PX_UNUSED(p0); PX_UNUSED(p1); PX_UNUSED(color); #endif } void MultiplePersistentContactManifold::drawLine(PxRenderOutput& out, const PxVec3 p0, const PxVec3 p1, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT PxMat44 m = PxMat44(PxIdentity); out << color << m << PxRenderOutput::LINES << p0 << p1; #else PX_UNUSED(out); PX_UNUSED(p0); PX_UNUSED(p1); PX_UNUSED(color); #endif } void MultiplePersistentContactManifold::drawPoint(PxRenderOutput& out, const Vec3VArg p, const PxF32 size, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT const PxVec3 up(0.f, size, 0.f); const PxVec3 right(size, 0.f, 0.f); const PxVec3 forwards(0.f, 0.f, size); PxVec3 a; V3StoreU(p, a); PxMat44 m = PxMat44(PxIdentity); out << color << m << PxRenderOutput::LINES << a + up << a - up; out << color << m << PxRenderOutput::LINES << a + right << a - right; out << color << m << PxRenderOutput::LINES << a + forwards << a - forwards; #else PX_UNUSED(out); PX_UNUSED(p); PX_UNUSED(size); PX_UNUSED(color); #endif } void MultiplePersistentContactManifold::drawPolygon(PxRenderOutput& out, const PxTransformV& transform, Vec3V* points, PxU32 numVerts, PxU32 color) { #if VISUALIZE_PERSISTENT_CONTACT for(PxU32 i=0; i<numVerts; ++i) { Vec3V tempV0 = points[i == 0 ? numVerts-1 : i-1]; Vec3V tempV1 = points[i]; drawLine(out, transform.transform(tempV0), transform.transform(tempV1), color); } #else PX_UNUSED(out); PX_UNUSED(transform); PX_UNUSED(points); PX_UNUSED(numVerts); PX_UNUSED(color); #endif } static FloatV addBatchManifoldContactsToSingleManifold(SinglePersistentContactManifold* manifold, MeshPersistentContact* manifoldContact, PxU32 numManifoldContacts, PCMContactPatch* patch, const FloatVArg sqReplaceBreakingThreshold, PxU8 maxContactsPerManifold) { switch(maxContactsPerManifold) { case GU_SPHERE_MANIFOLD_CACHE_SIZE://sphere return manifold->addBatchManifoldContactsSphere(manifoldContact, numManifoldContacts, *patch, sqReplaceBreakingThreshold); case GU_CAPSULE_MANIFOLD_CACHE_SIZE://capsule, need to implement keep two deepest return manifold->addBatchManifoldContactsCapsule(manifoldContact, numManifoldContacts, *patch, sqReplaceBreakingThreshold); default://cache size GU_SINGLE_MANIFOLD_CACHE_SIZE return manifold->addBatchManifoldContactsConvex(manifoldContact, numManifoldContacts, *patch, sqReplaceBreakingThreshold); }; } // This function adds the manifold contacts with different patches into the corresponding single persistent contact manifold void MultiplePersistentContactManifold::addManifoldContactPoints(MeshPersistentContact* manifoldContact, PxU32 numManifoldContacts, PCMContactPatch** contactPatch, PxU32 numPatch, const FloatVArg sqReplaceBreakingThreshold, const FloatVArg acceptanceEpsilon, PxU8 maxContactsPerManifold) { if(mNumManifolds == 0) { for(PxU32 i=0; i<numPatch; ++i) { PCMContactPatch* patch = contactPatch[i]; //this mean the patch hasn't been add to the manifold if(patch->mRoot == patch) { SinglePersistentContactManifold* manifold = getEmptyManifold(); if(manifold) { const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(manifold, manifoldContact, numManifoldContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold); FStore(_maxPen, &mMaxPen[mManifoldIndices[mNumManifolds]]); mNumManifolds++; } else { //We already pre-sorted the patches so we know we can return here return; } } } } else { //we do processContacts() when the number of contacts are more than 16, such that, we might call processContacts() multiple times when we have very detailed mesh //or very large contact offset/objects. In this case, the mNumManifolds will be large than 0. PCMContactPatch tempPatch; for(PxU32 i=0; i<numPatch; ++i) { bool found = false; PCMContactPatch* patch = contactPatch[i]; //this mean the patch has't been add to the manifold if(patch->mRoot == patch) { PX_ASSERT(mNumManifolds <= GU_MAX_MANIFOLD_SIZE); for(PxU32 j=0; j<mNumManifolds; ++j) { PX_ASSERT(mManifoldIndices[j] < GU_MAX_MANIFOLD_SIZE); SinglePersistentContactManifold& manifold = *getManifold(j); const Vec3V pNor = manifold.getLocalNormal(); const FloatV d = V3Dot(patch->mPatchNormal, pNor); if(FAllGrtrOrEq(d, acceptanceEpsilon)) { //appending the existing contacts to the manifold contact stream for(PxU32 k=0; k< manifold.mNumContacts; ++k) { PxU32 index = k + numManifoldContacts; //not duplicate point PX_ASSERT(index < 64); manifoldContact[index] = manifold.mContactPoints[k]; } //create a new patch for the exiting manifold tempPatch.mStartIndex = numManifoldContacts; tempPatch.mEndIndex = numManifoldContacts + manifold.mNumContacts; tempPatch.mPatchNormal = pNor;//manifold.getLocalNormal(); tempPatch.mRoot = patch; tempPatch.mNextPatch = NULL; patch->mEndPatch->mNextPatch = &tempPatch; //numManifoldContacts += manifold.numContacts; patch->mTotalSize += manifold.mNumContacts; patch->mPatchMaxPen = FMin(patch->mPatchMaxPen, FLoad(mMaxPen[mManifoldIndices[j]])); //manifold.numContacts = 0; PX_ASSERT((numManifoldContacts+manifold.mNumContacts) <= 64); const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(&manifold, manifoldContact, numManifoldContacts+manifold.mNumContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold); FStore(_maxPen, &mMaxPen[mManifoldIndices[j]]); found = true; break; } } if(!found)// && numManifolds < 4) { SinglePersistentContactManifold* manifold = getEmptyManifold(); //we still have slot to create a new manifold if(manifold) { const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(manifold, manifoldContact, numManifoldContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold); FStore(_maxPen, &mMaxPen[mManifoldIndices[mNumManifolds]]); mNumManifolds++; } else { //we can't allocate a new manifold and no existing manifold has the same normal as this patch, we need to find the shallowest penetration manifold. If this manifold is shallower than //the current patch, replace the manifold with the current patch PxU32 index = 0; for(PxU32 j=1; j<mNumManifolds; ++j) { //if(FAllGrtr(mMaxPen[mManifoldIndices[i]], mMaxPen[mManifoldIndices[index]])) if(mMaxPen[mManifoldIndices[j]] > mMaxPen[mManifoldIndices[index]]) { index = j; } } if(FAllGrtr(FLoad(mMaxPen[mManifoldIndices[index]]), patch->mPatchMaxPen)) { manifold = getManifold(index); manifold->mNumContacts = 0; const FloatV _maxPen = addBatchManifoldContactsToSingleManifold(manifold, manifoldContact, numManifoldContacts, patch, sqReplaceBreakingThreshold, maxContactsPerManifold); FStore(_maxPen, &mMaxPen[mManifoldIndices[index]]); } return; } } } } } } //This function adds the multi manifold contacts to the contact buffer for box/convexhull bool MultiplePersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const PxTransformV& meshTransform) { PxU32 contactCount = 0; PxU32 numContacts = 0; mNumTotalContacts = 0; //drawManifold(*gRenderOutPut, convexTransform, meshTransform); for(PxU32 i=0; i < mNumManifolds; ++i) { SinglePersistentContactManifold& manifold = *getManifold(i); numContacts = manifold.getNumContacts(); PX_ASSERT(mNumTotalContacts + numContacts <= 0xFF); mNumTotalContacts += PxTo8(numContacts); const Vec3V normal = manifold.getWorldNormal(meshTransform); for(PxU32 j=0; (j< numContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++j) { const MeshPersistentContact& p = manifold.getContactPoint(j); const Vec3V worldP =meshTransform.transform(p.mLocalPointB); const FloatV dist = V4GetW(p.mLocalNormalPen); outputPCMContact(contactBuffer, contactCount, worldP, normal, dist, p.mFaceIndex); } } PX_ASSERT(contactCount <= PxContactBuffer::MAX_CONTACTS); contactBuffer.count = contactCount; return contactCount > 0; } //This function adds the multi manifold contacts to the contact buffer for sphere and capsule, radius is corresponding to the sphere radius/capsule radius bool MultiplePersistentContactManifold::addManifoldContactsToContactBuffer(PxContactBuffer& contactBuffer, const PxTransformV& trA, const PxTransformV& trB, const FloatVArg radius) { PxU32 contactCount = 0; PxU32 numContacts = 0; mNumTotalContacts = 0; for(PxU32 i=0; i < mNumManifolds; ++i) { //get a single manifold SinglePersistentContactManifold& manifold = *getManifold(i); numContacts = manifold.getNumContacts(); PX_ASSERT(mNumTotalContacts + numContacts <= 0xFF); mNumTotalContacts += PxTo8(numContacts); const Vec3V normal = manifold.getWorldNormal(trB); //iterate all the contacts in this single manifold and add contacts to the contact buffer //each manifold contact point store two points which are in each other's local space. In this //case, mLocalPointA is stored as the center of sphere/a point in the segment for capsule for(PxU32 j=0; (j< numContacts) & (contactCount < PxContactBuffer::MAX_CONTACTS); ++j) { const MeshPersistentContact& p = manifold.getContactPoint(j); const Vec3V worldP = V3NegScaleSub(normal, radius, trA.transform(p.mLocalPointA)); const FloatV dist = FSub(V4GetW(p.mLocalNormalPen), radius); outputPCMContact(contactBuffer, contactCount, worldP, normal, dist, p.mFaceIndex); } } PX_ASSERT(contactCount <= PxContactBuffer::MAX_CONTACTS); contactBuffer.count = contactCount; return contactCount > 0; } // This function copies the mesh persistent contact from compress buffer(NpCacheStreamPair in the PxcNpThreadContext) to the multiple manifold // PT: function moved to cpp to go around a compiler bug on PS4 void MultiplePersistentContactManifold::fromBuffer(PxU8* PX_RESTRICT buffer) { PxU32 numManifolds = 0; if (buffer != NULL) { PX_ASSERT(((uintptr_t(buffer)) & 0xF) == 0); PxU8* PX_RESTRICT buff = buffer; MultiPersistentManifoldHeader* PX_RESTRICT header = reinterpret_cast<MultiPersistentManifoldHeader*>(buff); buff += sizeof(MultiPersistentManifoldHeader); numManifolds = header->mNumManifolds; PX_ASSERT(numManifolds <= GU_MAX_MANIFOLD_SIZE); mRelativeTransform = header->mRelativeTransform; for (PxU32 a = 0; a < numManifolds; ++a) { mManifoldIndices[a] = PxU8(a); SingleManifoldHeader* PX_RESTRICT manHeader = reinterpret_cast<SingleManifoldHeader*>(buff); buff += sizeof(SingleManifoldHeader); PxU32 numContacts = manHeader->mNumContacts; PX_ASSERT(numContacts <= GU_SINGLE_MANIFOLD_CACHE_SIZE); SinglePersistentContactManifold& manifold = mManifolds[a]; manifold.mNumContacts = numContacts; PX_ASSERT((uintptr_t(buff) & 0xf) == 0); CachedMeshPersistentContact* contacts = reinterpret_cast<CachedMeshPersistentContact*>(buff); for (PxU32 b = 0; b < manifold.mNumContacts; ++b) { manifold.mContactPoints[b].mLocalPointA = Vec3V_From_Vec4V(V4LoadA(&contacts[b].mLocalPointA.x)); manifold.mContactPoints[b].mLocalPointB = Vec3V_From_Vec4V(V4LoadA(&contacts[b].mLocalPointB.x)); manifold.mContactPoints[b].mLocalNormalPen = V4LoadA(&contacts[b].mLocalNormal.x); manifold.mContactPoints[b].mFaceIndex = contacts[b].mFaceIndex; } buff += sizeof(CachedMeshPersistentContact) * numContacts; } } else { mRelativeTransform.invalidate(); } mNumManifolds = PxU8(numManifolds); for (PxU32 a = numManifolds; a < GU_MAX_MANIFOLD_SIZE; ++a) { mManifoldIndices[a] = PxU8(a); } } // This function copies the mesh persistent contact from the multiple manifold to compress buffer(NpCacheStreamPair in the PxcNpThreadContext) void MultiplePersistentContactManifold::toBuffer(PxU8* PX_RESTRICT buffer) const { PxU8* buff = buffer; PX_ASSERT(((uintptr_t(buff)) & 0xF) == 0); MultiPersistentManifoldHeader* PX_RESTRICT header = reinterpret_cast<MultiPersistentManifoldHeader*>(buff); buff += sizeof(MultiPersistentManifoldHeader); PX_ASSERT(mNumManifolds <= GU_MAX_MANIFOLD_SIZE); header->mNumManifolds = mNumManifolds; header->mRelativeTransform = mRelativeTransform; for(PxU32 a = 0; a < mNumManifolds; ++a) { SingleManifoldHeader* manHeader = reinterpret_cast<SingleManifoldHeader*>(buff); buff += sizeof(SingleManifoldHeader); const SinglePersistentContactManifold& manifold = *getManifold(a); manHeader->mNumContacts = manifold.mNumContacts; PX_ASSERT((uintptr_t(buff) & 0xf) == 0); CachedMeshPersistentContact* contacts = reinterpret_cast<CachedMeshPersistentContact*>(buff); //convert the mesh persistent contact to cached mesh persistent contact to save 16 byte memory per contact for(PxU32 b = 0; b<manifold.mNumContacts; ++b) { V4StoreA(Vec4V_From_Vec3V(manifold.mContactPoints[b].mLocalPointA), &contacts[b].mLocalPointA.x); V4StoreA(Vec4V_From_Vec3V(manifold.mContactPoints[b].mLocalPointB), &contacts[b].mLocalPointB.x); V4StoreA(manifold.mContactPoints[b].mLocalNormalPen, &contacts[b].mLocalNormal.x); //Note - this must be written last because we just wrote mLocalPointA to this memory so need to make sure //that face index is written after that. contacts[b].mFaceIndex = manifold.mContactPoints[b].mFaceIndex; } buff += sizeof(CachedMeshPersistentContact) * manifold.mNumContacts; } } void Gu::addManifoldPoint(PersistentContact* manifoldContacts, PersistentContactManifold& manifold, GjkOutput& output, const PxMatTransformV& aToB, const FloatV replaceBreakingThreshold) { const Vec3V localPointA = aToB.transformInv(output.closestA); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); //Add contact to contact stream manifoldContacts[0].mLocalPointA = localPointA; manifoldContacts[0].mLocalPointB = output.closestB; manifoldContacts[0].mLocalNormalPen = localNormalPen; //Add contact to manifold manifold.addManifoldPoint(localPointA, output.closestB, localNormalPen, replaceBreakingThreshold); }
72,749
C++
30.740838
287
0.71836
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactPlaneConvex.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 "geomutils/PxContactBuffer.h" #include "GuVecConvexHull.h" #include "GuContactMethodImpl.h" #include "GuPersistentContactManifold.h" using namespace physx; bool Gu::pcmContactPlaneConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(shape0); PX_UNUSED(renderOutput); using namespace aos; PersistentContactManifold& manifold = cache.getManifold(); PxPrefetchLine(&manifold, 256); // Get actual shape data const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); const PxTransformV transf0 = loadTransformA(transform1);//convex transform const PxTransformV transf1 = loadTransformA(transform0);//plane transform //convex to plane const PxTransformV curTransf(transf1.transformInv(transf0)); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const ConvexHullData* hullData = _getHullData(shapeConvex); const PxReal toleranceLength = params.mToleranceLength; const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength); //in world space const Vec3V planeNormal = V3Normalize(QuatGetBasisVector0(transf1.q)); const Vec3V negPlaneNormal = V3Neg(planeNormal); const FloatV contactDist = FLoad(params.mContactDistance); //const FloatV replaceBreakingThreshold = FMul(convexMargin, FLoad(0.001f)); const FloatV projectBreakingThreshold = FMul(convexMargin, FLoad(0.2f)); const PxU32 initialContacts = manifold.mNumContacts; manifold.refreshContactPoints(curTransf, projectBreakingThreshold, contactDist); const PxU32 newContacts = manifold.mNumContacts; const bool bLostContacts = (newContacts != initialContacts);//((initialContacts == 0) || (newContacts != initialContacts)); if(bLostContacts || manifold.invalidate_PrimitivesPlane(curTransf, convexMargin, FLoad(0.2f))) { const PxMatTransformV aToB(curTransf); const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const Mat33V vertex2Shape = ConstructVertex2ShapeMatrix(vScale, vQuat); //ML:localNormal is the local space of plane normal, however, because shape1 is box and shape0 is plane, we need to use the reverse of contact normal(which will be the plane normal) to make the refreshContactPoints //work out the correct pentration for points const Vec3V localNormal = V3UnitX(); manifold.mNumContacts = 0; manifold.setRelativeTransform(curTransf); const PxVec3* PX_RESTRICT verts = hullData->getHullVertices(); const PxU32 nbPolygons = hullData->mNbPolygons; const Vec3V n = V3Normalize(M33MulV3(vertex2Shape, aToB.rotateInv(localNormal))); const Vec3V nnormal = V3Neg(n); const FloatV zero = FZero(); PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); PxU32 numContacts = 0; const PxMatTransformV aToBVertexSpace(aToB.p, M33MulM33(aToB.rot, vertex2Shape)); FloatV minProj = FMax(); PxU32 closestFaceIndex = 0; PxU32 polyIndex2 = 0xFFFFFFFF; for (PxU32 i = 0; i < nbPolygons; ++i) { const HullPolygonData& polyData = hullData->mPolygons[i]; const Vec3V planeN = V3LoadU_SafeReadW(polyData.mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const FloatV proj = V3Dot(n, planeN); if (FAllGrtr(minProj, proj)) { minProj = proj; closestFaceIndex = PxI32(i); } } const PxU32 numEdges = hullData->mNbEdges; const PxU8* const edgeToFace = hullData->getFacesByEdges8(); //Loop through edges PxU32 closestEdge = 0xffffffff; //We subtract a small bias to increase the chances of selecting an edge below minProj = FSub(minProj, FLoad(5e-4f)); FloatV maxDpSq = FMul(minProj, minProj); for (PxU32 i = 0; i < numEdges; ++i)//, inc = VecI32V_Add(inc, vOne)) { const PxU32 index = i * 2; const PxU8 f0 = edgeToFace[index]; const PxU8 f1 = edgeToFace[index + 1]; const Vec3V planeNormal0 = V3LoadU_SafeReadW(hullData->mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const Vec3V planeNormal1 = V3LoadU_SafeReadW(hullData->mPolygons[f1].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class // unnormalized edge normal const Vec3V edgeNormal = V3Add(planeNormal0, planeNormal1);//polys[f0].mPlane.n + polys[f1].mPlane.n; const FloatV enMagSq = V3Dot(edgeNormal, edgeNormal);//edgeNormal.magnitudeSquared(); //Test normal of current edge - squared test is valid if dp and maxDp both >= 0 const FloatV dp = V3Dot(edgeNormal, nnormal);//edgeNormal.dot(normal); const FloatV sqDp = FMul(dp, dp); const BoolV con0 = FIsGrtrOrEq(dp, zero); const BoolV con1 = FIsGrtr(sqDp, FMul(maxDpSq, enMagSq)); const BoolV con = BAnd(con0, con1); if (BAllEqTTTT(con)) { maxDpSq = FDiv(sqDp, enMagSq); closestEdge = i; } } if (closestEdge != 0xffffffff) { const PxU8* FBE = edgeToFace; const PxU32 index = closestEdge * 2; const PxU32 f0 = FBE[index]; const PxU32 f1 = FBE[index + 1]; const Vec3V planeNormal0 = V3LoadU_SafeReadW(hullData->mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const Vec3V planeNormal1 = V3LoadU_SafeReadW(hullData->mPolygons[f1].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const FloatV dp0 = V3Dot(planeNormal0, nnormal); const FloatV dp1 = V3Dot(planeNormal1, nnormal); if (FAllGrtr(dp0, dp1)) { closestFaceIndex = PxI32(f0); polyIndex2 = PxI32(f1); } else { closestFaceIndex = PxI32(f1); polyIndex2 = PxI32(f0); } } for (PxU32 index = closestFaceIndex; index != 0xFFFFFFFF; index = polyIndex2, polyIndex2 = 0xFFFFFFFF) { const HullPolygonData& face = hullData->mPolygons[closestFaceIndex]; const PxU32 nbFaceVerts = face.mNbVerts; const PxU8* vertInds = hullData->getVertexData8() + face.mVRef8; for (PxU32 i = 0; i < nbFaceVerts; ++i) { const Vec3V pInVertexSpace = V3LoadU(verts[vertInds[i]]); //transform p into plane space const Vec3V pInPlaneSpace = aToBVertexSpace.transform(pInVertexSpace);//V3Add(aToB.p, M33MulV3(temp1, pInVertexSpace)); const FloatV signDist = V3GetX(pInPlaneSpace); if (FAllGrtr(contactDist, signDist)) { //transform p into shape space const Vec3V pInShapeSpace = M33MulV3(vertex2Shape, pInVertexSpace); //add to manifold manifoldContacts[numContacts].mLocalPointA = pInShapeSpace; manifoldContacts[numContacts].mLocalPointB = V3NegScaleSub(localNormal, signDist, pInPlaneSpace); manifoldContacts[numContacts++].mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), signDist); if (numContacts == 64) { manifold.reduceBatchContactsCluster(manifoldContacts, numContacts); numContacts = GU_MANIFOLD_CACHE_SIZE; for (PxU32 c = 0; c < GU_MANIFOLD_CACHE_SIZE; ++c) manifoldContacts[c] = manifold.mContactPoints[c]; } } } } //reduce contacts //manifold.addBatchManifoldContactsCluster(manifoldContacts, numContacts); manifold.addBatchManifoldContacts(manifoldContacts, numContacts, toleranceLength); } manifold.addManifoldContactsToContactBuffer(contactBuffer, negPlaneNormal, transf1, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return manifold.getNumContacts() > 0; }
8,992
C++
38.442982
216
0.739101
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereConvex.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 "geomutils/PxContactBuffer.h" #include "GuGJKPenetration.h" #include "GuEPA.h" #include "GuVecCapsule.h" #include "GuVecConvexHull.h" #include "GuVecConvexHullNoScale.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" #include "GuPCMContactGenUtil.h" using namespace physx; using namespace Gu; using namespace aos; static void addToContactBuffer(PxContactBuffer& contactBuffer, const Vec3VArg worldNormal, const Vec3VArg worldPoint, const FloatVArg penDep) { outputSimplePCMContact(contactBuffer, worldPoint, worldNormal, penDep); } static bool fullContactsGenerationSphereConvex(const CapsuleV& capsule, const ConvexHullV& convexHull, const PxTransformV& transf0, const PxTransformV& transf1, PersistentContact* manifoldContacts, PxContactBuffer& contactBuffer, const bool idtScale, PersistentContactManifold& manifold, Vec3VArg normal, const FloatVArg contactDist, bool doOverlapTest, PxRenderOutput* renderOutput) { PX_UNUSED(renderOutput); PolygonalData polyData; getPCMConvexData(convexHull,idtScale, polyData); PX_ALIGN(16, PxU8 buff[sizeof(SupportLocalImpl<ConvexHullV>)]); SupportLocal* map = (idtScale ? static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullNoScaleV>)(static_cast<const ConvexHullNoScaleV&>(convexHull), transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale)) : static_cast<SupportLocal*>(PX_PLACEMENT_NEW(buff, SupportLocalImpl<ConvexHullV>)(convexHull, transf1, convexHull.vertex2Shape, convexHull.shape2Vertex, idtScale))); PxU32 numContacts = 0; if(generateSphereFullContactManifold(capsule, polyData, map, manifoldContacts, numContacts, contactDist, normal, doOverlapTest)) { if(numContacts > 0) { PersistentContact& p = manifold.getContactPoint(0); p.mLocalPointA = manifoldContacts[0].mLocalPointA; p.mLocalPointB = manifoldContacts[0].mLocalPointB; p.mLocalNormalPen = manifoldContacts[0].mLocalNormalPen; manifold.mNumContacts =1; //transform normal to world space const Vec3V worldNormal = transf1.rotate(normal); const Vec3V worldP = V3NegScaleSub(worldNormal, capsule.radius, transf0.p); const FloatV penDep = FSub(V4GetW(manifoldContacts[0].mLocalNormalPen), capsule.radius); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1, capsule.radius); #endif addToContactBuffer(contactBuffer, worldNormal, worldP, penDep); return true; } } return false; } bool Gu::pcmContactSphereConvex(GU_CONTACT_METHOD_ARGS) { PX_ASSERT(transform1.q.isSane()); PX_ASSERT(transform0.q.isSane()); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); PersistentContactManifold& manifold = cache.getManifold(); const Vec3V zeroV = V3Zero(); const ConvexHullData* hullData = _getHullData(shapeConvex); PxPrefetchLine(hullData); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const FloatV sphereRadius = FLoad(shapeSphere.radius); const FloatV contactDist = FLoad(params.mContactDistance); //Transfer A into the local space of B const PxTransformV transf0 = loadTransformA(transform0); const PxTransformV transf1 = loadTransformA(transform1); const PxTransformV curRTrans(transf1.transformInv(transf0)); const PxMatTransformV aToB(curRTrans); const PxReal toleranceLength = params.mToleranceLength; const FloatV convexMargin = CalculatePCMConvexMargin(hullData, vScale, toleranceLength); const PxU32 initialContacts = manifold.mNumContacts; const FloatV minMargin = FMin(convexMargin, sphereRadius); const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.05f)); const FloatV refreshDistance = FAdd(sphereRadius, contactDist); manifold.refreshContactPoints(aToB, projectBreakingThreshold, refreshDistance); //ML: after refreshContactPoints, we might lose some contacts const bool bLostContacts = (manifold.mNumContacts != initialContacts); if(bLostContacts || manifold.invalidate_SphereCapsule(curRTrans, minMargin)) { GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT; manifold.setRelativeTransform(curRTrans); const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const bool idtScale = shapeConvex.scale.isIdentity(); //use the original shape const ConvexHullV convexHull(hullData, V3LoadU(hullData->mCenterOfMass), vScale, vQuat, idtScale); //transform capsule into the local space of convexHull const CapsuleV capsule(aToB.p, sphereRadius); GjkOutput output; const LocalConvex<CapsuleV> convexA(capsule); const Vec3V initialSearchDir = V3Sub(capsule.getCenter(), convexHull.getCenter()); if(idtScale) { const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull)); status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullNoScaleV> >(convexA, convexB, initialSearchDir, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); } else { const LocalConvex<ConvexHullV> convexB(convexHull); status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<ConvexHullV> >(convexA, convexB, initialSearchDir, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); } if(status == GJK_NON_INTERSECT) { return false; } else if(status == GJK_CONTACT) { PersistentContact& p = manifold.getContactPoint(0); p.mLocalPointA = zeroV;//sphere center p.mLocalPointB = output.closestB; p.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); manifold.mNumContacts =1; #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1, capsule.radius); #endif //transform normal to world space const Vec3V worldNormal = transf1.rotate(output.normal); const Vec3V worldP = V3NegScaleSub(worldNormal, sphereRadius, transf0.p); const FloatV penDep = FSub(output.penDep, sphereRadius); addToContactBuffer(contactBuffer, worldNormal, worldP, penDep); return true; } else if(status == GJK_DEGENERATE) { PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); return fullContactsGenerationSphereConvex(capsule, convexHull, transf0, transf1, manifoldContacts, contactBuffer, idtScale, manifold, output.normal, contactDist, true, renderOutput); } else if (status == EPA_CONTACT) { if (idtScale) { const LocalConvex<ConvexHullNoScaleV> convexB(*PX_CONVEX_TO_NOSCALECONVEX(&convexHull)); status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, FLoad(toleranceLength), output); } else { const LocalConvex<ConvexHullV> convexB(convexHull); status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, FLoad(toleranceLength), output); } if (status == EPA_CONTACT) { PersistentContact& p = manifold.getContactPoint(0); p.mLocalPointA = zeroV;//sphere center p.mLocalPointB = output.closestB; p.mLocalNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); manifold.mNumContacts = 1; #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1, capsule.radius); #endif //transform normal to world space const Vec3V worldNormal = transf1.rotate(output.normal); const Vec3V worldP = V3NegScaleSub(worldNormal, sphereRadius, transf0.p); const FloatV penDep = FSub(output.penDep, sphereRadius); addToContactBuffer(contactBuffer, worldNormal, worldP, penDep); return true; } else { PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); return fullContactsGenerationSphereConvex(capsule, convexHull, transf0, transf1, manifoldContacts, contactBuffer, idtScale, manifold, output.normal, contactDist, true, renderOutput); } } } else if(manifold.mNumContacts > 0) { //ML:: the manifold originally has contacts PersistentContact& p = manifold.getContactPoint(0); const Vec3V worldNormal = transf1.rotate(Vec3V_From_Vec4V(p.mLocalNormalPen)); const Vec3V worldP = V3NegScaleSub(worldNormal, sphereRadius, transf0.p); const FloatV penDep = FSub(V4GetW(p.mLocalNormalPen), sphereRadius); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1, sphereRadius); #endif addToContactBuffer(contactBuffer, worldNormal, worldP, penDep); return true; } return false; }
10,364
C++
40.963563
245
0.770069
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleBox.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 "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuVecCapsule.h" #include "GuContactMethodImpl.h" #include "GuPCMContactGen.h" #include "GuPCMShapeConvex.h" #include "GuGJKPenetration.h" #include "GuEPA.h" using namespace physx; using namespace Gu; using namespace aos; static bool fullContactsGenerationCapsuleBox(const CapsuleV& capsule, const BoxV& box, const PxVec3& halfExtents, const PxMatTransformV& aToB, const PxTransformV& transf0, const PxTransformV& transf1, PersistentContact* manifoldContacts, PxU32& numContacts, PxContactBuffer& contactBuffer, PersistentContactManifold& manifold, Vec3V& normal, const Vec3VArg closest, PxReal boxMargin, const FloatVArg contactDist, bool doOverlapTest, PxReal toleranceScale, PxRenderOutput* renderOutput) { PolygonalData polyData; PCMPolygonalBox polyBox(halfExtents); polyBox.getPolygonalData(&polyData); const Mat33V identity = M33Identity(); SupportLocalImpl<BoxV> map(box, transf1, identity, identity); PxU32 origContacts = numContacts; if(!generateCapsuleBoxFullContactManifold(capsule, polyData, &map, aToB, manifoldContacts, numContacts, contactDist, normal, closest, boxMargin, doOverlapTest, toleranceScale, renderOutput)) return false; //EPA has contacts and we have new contacts, we discard the EPA contacts if(origContacts != 0 && numContacts != origContacts) { numContacts--; manifoldContacts++; } manifold.addBatchManifoldContacts2(manifoldContacts, numContacts); normal = transf1.rotate(normal); manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsule.radius, contactDist); return true; } bool Gu::pcmContactCapsuleBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_ASSERT(transform1.q.isSane()); PX_ASSERT(transform0.q.isSane()); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); PersistentContactManifold& manifold = cache.getManifold(); PxPrefetchLine(&manifold, 256); const Vec3V boxExtents = V3LoadU(shapeBox.halfExtents); const FloatV contactDist = FLoad(params.mContactDistance); const PxTransformV transf0 = loadTransformA(transform0); const PxTransformV transf1 = loadTransformA(transform1); const PxTransformV curRTrans = transf1.transformInv(transf0); const PxMatTransformV aToB_(curRTrans); const FloatV capsuleRadius = FLoad(shapeCapsule.radius); const FloatV capsuleHalfHeight = FLoad(shapeCapsule.halfHeight); const PxU32 initialContacts = manifold.mNumContacts; const PxReal toleranceLength = params.mToleranceLength; const FloatV boxMargin = CalculatePCMBoxMargin(boxExtents, toleranceLength); const FloatV minMargin = FMin(boxMargin, capsuleRadius); const FloatV projectBreakingThreshold = FMul(minMargin, FLoad(0.8f)); const FloatV refreshDist = FAdd(contactDist, capsuleRadius); //refreshContactPoints remove invalid contacts from the manifold and update the number correspondingly manifold.refreshContactPoints(aToB_, projectBreakingThreshold, refreshDist); const bool bLostContacts = (manifold.mNumContacts != initialContacts); if(bLostContacts || manifold.invalidate_SphereCapsule(curRTrans, minMargin)) { GjkStatus status = manifold.mNumContacts > 0 ? GJK_UNDEFINED : GJK_NON_INTERSECT; manifold.setRelativeTransform(curRTrans); const PxMatTransformV aToB(curRTrans); const BoxV box(transf1.p, boxExtents); //transform capsule into the local space of box const CapsuleV capsule(aToB.p, aToB.rotate(V3Scale(V3UnitX(), capsuleHalfHeight)), capsuleRadius); const LocalConvex<CapsuleV> convexA(capsule); const LocalConvex<BoxV> convexB(box); GjkOutput output; const Vec3V initialSearchDir = V3Sub(capsule.getCenter(), box.getCenter()); status = gjkPenetration<LocalConvex<CapsuleV>, LocalConvex<BoxV> >(convexA, convexB, initialSearchDir, contactDist, true, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, output); PersistentContact* manifoldContacts = PX_CP_TO_PCP(contactBuffer.contacts); PxU32 numContacts = 0; bool doOverlapTest = false; if(status == GJK_NON_INTERSECT) { return false; } else if(status == GJK_DEGENERATE) { return fullContactsGenerationCapsuleBox(capsule, box, shapeBox.halfExtents, aToB, transf0, transf1, manifoldContacts, numContacts, contactBuffer, manifold, output.normal, output.closestB, box.getMarginF(), contactDist, true, params.mToleranceLength, renderOutput); } else { if(status == GJK_CONTACT) { const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); //Add contact to contact stream manifoldContacts[numContacts].mLocalPointA = localPointA; manifoldContacts[numContacts].mLocalPointB = output.closestB; manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } else { PX_ASSERT(status == EPA_CONTACT); status = epaPenetration(convexA, convexB, manifold.mAIndice, manifold.mBIndice, manifold.mNumWarmStartPoints, true, FLoad(toleranceLength), output); if(status == EPA_CONTACT) { const Vec3V localPointA = aToB.transformInv(output.closestA);//curRTrans.transformInv(closestA); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); //Add contact to contact stream manifoldContacts[numContacts].mLocalPointA = localPointA; manifoldContacts[numContacts].mLocalPointB = output.closestB; manifoldContacts[numContacts++].mLocalNormalPen = localNormalPen; } else { doOverlapTest = true; } } if(initialContacts == 0 || bLostContacts || doOverlapTest) { return fullContactsGenerationCapsuleBox(capsule, box, shapeBox.halfExtents, aToB, transf0, transf1, manifoldContacts, numContacts, contactBuffer, manifold, output.normal, output.closestB, box.getMarginF(), contactDist, doOverlapTest, params.mToleranceLength, renderOutput); } else { //The contacts is either come from GJK or EPA const FloatV replaceBreakingThreshold = FMul(minMargin, FLoad(0.1f)); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(output.normal), output.penDep); manifold.addManifoldPoint2(curRTrans.transformInv(output.closestA), output.closestB, localNormalPen, replaceBreakingThreshold); const Vec3V normal = transf1.rotate(output.normal); manifold.addManifoldContactsToContactBuffer(contactBuffer, normal, normal, transf0, capsuleRadius, contactDist); return true; } } } else if(manifold.getNumContacts() > 0) { const Vec3V worldNormal = manifold.getWorldNormal(transf1); manifold.addManifoldContactsToContactBuffer(contactBuffer, worldNormal, worldNormal, transf0, capsuleRadius, contactDist); return true; } return false; }
8,636
C++
41.546798
200
0.770148
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCustomGeometry.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 "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuBounds.h" #include "GuContactMethodImpl.h" #include "GuPCMShapeConvex.h" #include "GuPCMContactGen.h" using namespace physx; using namespace aos; using namespace Gu; static bool pcmContactCustomGeometryGeometry(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); const PxCustomGeometry& customGeom = checkedCast<PxCustomGeometry>(shape0); const PxGeometry& otherGeom = shape1; float breakingThreshold = 0.01f * params.mToleranceLength; bool usePCM = customGeom.callbacks->usePersistentContactManifold(customGeom, breakingThreshold); if (otherGeom.getType() == PxGeometryType::eCUSTOM) { float breakingThreshold1 = breakingThreshold; if (checkedCast<PxCustomGeometry>(shape1).callbacks->usePersistentContactManifold(otherGeom, breakingThreshold1)) { breakingThreshold = PxMin(breakingThreshold, breakingThreshold1); usePCM = true; } } else if (otherGeom.getType() > PxGeometryType::eCONVEXMESH) { usePCM = true; } if (usePCM) { MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const PxTransformV transf0 = loadTransformA(transform0), transf1 = loadTransformA(transform1); const PxTransformV curRTrans = transf1.transformInv(transf0); const FloatV cos5 = FLoad(0.9962f); // Cos of 5 degrees if (multiManifold.invalidate(curRTrans, FLoad(breakingThreshold))) { customGeom.callbacks->generateContacts(customGeom, otherGeom, transform0, transform1, params.mContactDistance, params.mMeshContactMargin, params.mToleranceLength, contactBuffer); multiManifold.initialize(); multiManifold.setRelativeTransform(curRTrans); for (PxU32 ci = 0; ci < contactBuffer.count; ++ci) { const PxContactPoint& c = contactBuffer.contacts[ci]; const Vec3V cP = V3LoadU(c.point); const Vec3V cN = V3LoadU(c.normal); const FloatV cD = FLoad(c.separation); SinglePersistentContactManifold* manifold = NULL; for (PxU8 mi = 0; mi < multiManifold.mNumManifolds; ++mi) { const Vec3V mN = multiManifold.mManifolds[mi].getWorldNormal(transf1); const BoolV cmp = FIsGrtr(V3Dot(cN, mN), cos5); if (BAllEqTTTT(cmp)) { manifold = &multiManifold.mManifolds[mi]; break; } } if (!manifold) { manifold = multiManifold.getEmptyManifold(); if (manifold) multiManifold.mNumManifolds++; } if (manifold) { SinglePersistentContactManifold& m = *manifold; MeshPersistentContact pc; pc.mLocalPointA = transf0.transformInv(cP); pc.mLocalPointB = transf1.transformInv(cP); pc.mLocalNormalPen = V4SetW(transf1.rotateInv(cN), cD); pc.mFaceIndex = c.internalFaceIndex1; m.mContactPoints[m.mNumContacts++] = pc; m.mNumContacts = SinglePersistentContactManifold::reduceContacts(m.mContactPoints, m.mNumContacts); } } contactBuffer.count = 0; } #if PCM_LOW_LEVEL_DEBUG multiManifold.drawManifold(*renderOutput, transf0, transf1); #endif return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, transf1); } return customGeom.callbacks->generateContacts(customGeom, otherGeom, transform0, transform1, params.mContactDistance, params.mMeshContactMargin, params.mToleranceLength, contactBuffer); } bool Gu::pcmContactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS) { bool res = pcmContactCustomGeometryGeometry(shape1, shape0, transform1, transform0, params, cache, contactBuffer, renderOutput); for (PxU32 i = 0; i < contactBuffer.count; ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; return res; }
5,328
C++
36.794326
129
0.75244
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleCapsule.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 "geomutils/PxContactBuffer.h" #include "GuVecCapsule.h" #include "GuContactMethodImpl.h" #include "GuDistanceSegmentSegment.h" #include "GuPCMContactGenUtil.h" using namespace physx; using namespace Gu; using namespace aos; static Vec4V pcmDistancePointSegmentTValue22( const Vec3VArg a0, const Vec3VArg b0, const Vec3VArg a1, const Vec3VArg b1, const Vec3VArg p0, const Vec3VArg p1, const Vec3VArg p2, const Vec3VArg p3) { const Vec4V zero = V4Zero(); const Vec3V ap00 = V3Sub(p0, a0); const Vec3V ap10 = V3Sub(p1, a0); const Vec3V ap01 = V3Sub(p2, a1); const Vec3V ap11 = V3Sub(p3, a1); const Vec3V ab0 = V3Sub(b0, a0); const Vec3V ab1 = V3Sub(b1, a1); /* const FloatV nom00 = V3Dot(ap00, ab0); const FloatV nom10 = V3Dot(ap10, ab0); const FloatV nom01 = V3Dot(ap01, ab1); const FloatV nom11 = V3Dot(ap11, ab1);*/ const Vec4V combinedDot = V3Dot4(ap00, ab0, ap10, ab0, ap01, ab1, ap11, ab1); const FloatV nom00 = V4GetX(combinedDot); const FloatV nom10 = V4GetY(combinedDot); const FloatV nom01 = V4GetZ(combinedDot); const FloatV nom11 = V4GetW(combinedDot); const FloatV denom0 = V3Dot(ab0, ab0); const FloatV denom1 = V3Dot(ab1, ab1); const Vec4V nom = V4Merge(nom00, nom10, nom01, nom11); const Vec4V denom = V4Merge(denom0, denom0, denom1, denom1); const Vec4V tValue = V4Div(nom, denom); return V4Sel(V4IsEq(denom, zero), zero, tValue); } static void storeContact(const Vec3VArg contact, const Vec3VArg normal, const FloatVArg separation, PxContactBuffer& buffer) { outputSimplePCMContact(buffer, contact, normal, separation); } bool Gu::pcmContactCapsuleCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_ASSERT(transform1.q.isSane()); PX_ASSERT(transform0.q.isSane()); // Get actual shape data const PxCapsuleGeometry& shapeCapsule0 = checkedCast<PxCapsuleGeometry>(shape0); const PxCapsuleGeometry& shapeCapsule1 = checkedCast<PxCapsuleGeometry>(shape1); const Vec3V _p0 = V3LoadA(&transform0.p.x); const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V _p1 = V3LoadA(&transform1.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); /*PsTransformV transf0(p0, q0); PsTransformV transf1(p1, q1);*/ const FloatV r0 = FLoad(shapeCapsule0.radius); const FloatV halfHeight0 = FLoad(shapeCapsule0.halfHeight); const FloatV r1 = FLoad(shapeCapsule1.radius); const FloatV halfHeight1 = FLoad(shapeCapsule1.halfHeight); const FloatV cDist = FLoad(params.mContactDistance); const Vec3V positionOffset = V3Scale(V3Add(_p0, _p1), FHalf()); const Vec3V p0 = V3Sub(_p0, positionOffset); const Vec3V p1 = V3Sub(_p1, positionOffset); const FloatV zero = FZero(); //const FloatV one = FOne(); const Vec3V zeroV = V3Zero(); /*const Vec3V positionOffset = V3Scale(V3Add(transf0.p, transf1.p), FloatV_From_F32(0.5f)); transf0.p = V3Sub(transf0.p, positionOffset); transf1.p = V3Sub(transf1.p, positionOffset);*/ const Vec3V basisVector0 = QuatGetBasisVector0(q0); const Vec3V tmp0 = V3Scale(basisVector0, halfHeight0); const Vec3V s0 = V3Add(p0, tmp0); const Vec3V e0 = V3Sub(p0, tmp0); const Vec3V d0 = V3Sub(e0, s0); const Vec3V basisVector1 = QuatGetBasisVector0(q1); const Vec3V tmp1 = V3Scale(basisVector1, halfHeight1); const Vec3V s1 = V3Add(p1, tmp1); const Vec3V e1 = V3Sub(p1, tmp1); const Vec3V d1 = V3Sub(e1, s1); const FloatV sumRadius = FAdd(r0, r1); const FloatV inflatedSum = FAdd(sumRadius, cDist); const FloatV inflatedSumSquared = FMul(inflatedSum, inflatedSum); const FloatV a = V3Dot(d0, d0);//squared length of segment1 const FloatV e = V3Dot(d1, d1);//squared length of segment2 const FloatV eps = FLoad(1e-6f);//FEps(); FloatV t0, t1; const FloatV sqDist0 = distanceSegmentSegmentSquared(s0, d0, s1, d1, t0, t1); if(FAllGrtrOrEq(inflatedSumSquared, sqDist0)) { const Vec4V zeroV4 = V4Zero(); const Vec4V oneV4 = V4One(); //check to see whether these two capsule are paralle const FloatV parallelTolerance = FLoad(0.9998f); const BoolV con0 = FIsGrtr(eps, a); const BoolV con1 = FIsGrtr(eps, e); const Vec3V dir0 = V3Sel(con0, zeroV, V3ScaleInv(d0, FSqrt(a))); const Vec3V dir1 = V3Sel(con1, zeroV, V3ScaleInv(d1, FSqrt(e))); const FloatV cos = FAbs(V3Dot(dir0, dir1)); if(FAllGrtr(cos, parallelTolerance))//paralle { //project s, e into s1e1 const Vec4V t= pcmDistancePointSegmentTValue22(s0, e0, s1, e1, s1, e1, s0, e0); const BoolV con = BAnd(V4IsGrtrOrEq(t, zeroV4), V4IsGrtrOrEq(oneV4, t)); const BoolV con00 = BGetX(con); const BoolV con01 = BGetY(con); const BoolV con10 = BGetZ(con); const BoolV con11 = BGetW(con); /* PX_ALIGN(16, PxU32 conditions[4]); F32Array_Aligned_From_Vec4V(con, (PxF32*)conditions);*/ PxU32 numContact=0; if(BAllEqTTTT(con00)) { const Vec3V projS1 = V3ScaleAdd(d0, V4GetX(t), s0); const Vec3V v = V3Sub(projS1, s1); const FloatV sqDist = V3Dot(v, v); const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist)); if(BAllEqTTTT(bCon)) { const FloatV dist = FSqrt(sqDist); const FloatV pen = FSub(dist, sumRadius); const Vec3V normal = V3ScaleInv(v, dist); PX_ASSERT(isFiniteVec3V(normal)); const Vec3V _p = V3NegScaleSub(normal, r0, projS1); const Vec3V p = V3Add(_p, positionOffset); storeContact(p, normal, pen, contactBuffer); numContact++; } } if(BAllEqTTTT(con01)) { const Vec3V projE1 = V3ScaleAdd(d0, V4GetY(t), s0); const Vec3V v = V3Sub(projE1, e1); const FloatV sqDist = V3Dot(v, v); const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist)); if(BAllEqTTTT(bCon)) { const FloatV dist = FSqrt(sqDist); const FloatV pen = FSub(dist, sumRadius); const Vec3V normal = V3ScaleInv(v, dist); PX_ASSERT(isFiniteVec3V(normal)); const Vec3V _p = V3NegScaleSub(normal, r0, projE1); const Vec3V p = V3Add(_p, positionOffset); storeContact(p, normal, pen, contactBuffer); numContact++; } } if(BAllEqTTTT(con10)) { const Vec3V projS0 = V3ScaleAdd(d1, V4GetZ(t), s1); const Vec3V v = V3Sub(s0, projS0); const FloatV sqDist = V3Dot(v, v); const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist)); if(BAllEqTTTT(bCon)) { const FloatV dist = FSqrt(sqDist); const FloatV pen = FSub(dist, sumRadius); const Vec3V normal = V3ScaleInv(v, dist); PX_ASSERT(isFiniteVec3V(normal)); const Vec3V _p = V3NegScaleSub(normal, r0, s0); const Vec3V p = V3Add(_p, positionOffset); //const Vec3V p = V3ScaleAdd(normal, r0, s0); storeContact(p, normal, pen, contactBuffer); numContact++; } } if(BAllEqTTTT(con11)) { const Vec3V projE0 = V3ScaleAdd(d1, V4GetW(t), s1); const Vec3V v = V3Sub(e0, projE0); const FloatV sqDist = V3Dot(v, v); const BoolV bCon = BAnd(FIsGrtr(sqDist, eps), FIsGrtr(inflatedSumSquared, sqDist)); if(BAllEqTTTT(bCon)) { const FloatV dist = FSqrt(sqDist); const FloatV pen = FSub(dist, sumRadius); const Vec3V normal = V3ScaleInv(v, dist); PX_ASSERT(isFiniteVec3V(normal)); const Vec3V _p = V3NegScaleSub(normal, r0, e0); const Vec3V p = V3Add(_p, positionOffset); //const Vec3V p = V3ScaleAdd(normal, r0, e0); storeContact(p, normal, pen, contactBuffer); numContact++; } } if(numContact) return true; } const Vec3V closestA = V3ScaleAdd(d0, t0, s0); const Vec3V closestB = V3ScaleAdd(d1, t1, s1); const BoolV con = FIsGrtr(eps, sqDist0); //const Vec3V normal = V3Sel(FIsEq(dist, zero), V3Sel(FIsGrtr(a, eps), V3Normalise(d0), V3Scale(V3Sub(closestA, closestB), FRecip(dist))); const Vec3V _normal = V3Sel(con, V3Sel(FIsGrtr(a, eps), d0, V3UnitX()), V3Sub(closestA, closestB)); const Vec3V normal = V3Normalize(_normal); PX_ASSERT(isFiniteVec3V(normal)); const Vec3V _point = V3NegScaleSub(normal, r0, closestA); const Vec3V p = V3Add(_point, positionOffset); const FloatV dist = FSel(con, zero, FSqrt(sqDist0)); const FloatV pen = FSub(dist, sumRadius); //PX_ASSERT(FAllGrtrOrEq(zero, pen)); storeContact(p, normal, pen, contactBuffer); return true; } return false; }
10,034
C++
35.358696
140
0.701216
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMShapeConvex.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 "GuPCMShapeConvex.h" #include "GuVecConvexHull.h" #include "GuPCMContactGen.h" #include "common/PxRenderOutput.h" using namespace physx; using namespace Gu; using namespace aos; namespace physx { namespace Gu { const PxU8 gPCMBoxPolygonData[24] = { 0, 3, 2, 1, 1, 2, 6, 5, 5, 6, 7, 4, 4, 7, 3, 0, 3, 7, 6, 2, 4, 0, 1, 5, }; } } PCMPolygonalBox::PCMPolygonalBox(const PxVec3& halfSide) : mHalfSide(halfSide) { //Precompute the convex data // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ PxVec3 minimum = -mHalfSide; PxVec3 maximum = mHalfSide; // Generate 8 corners of the bbox mVertices[0] = PxVec3(minimum.x, minimum.y, minimum.z); mVertices[1] = PxVec3(maximum.x, minimum.y, minimum.z); mVertices[2] = PxVec3(maximum.x, maximum.y, minimum.z); mVertices[3] = PxVec3(minimum.x, maximum.y, minimum.z); mVertices[4] = PxVec3(minimum.x, minimum.y, maximum.z); mVertices[5] = PxVec3(maximum.x, minimum.y, maximum.z); mVertices[6] = PxVec3(maximum.x, maximum.y, maximum.z); mVertices[7] = PxVec3(minimum.x, maximum.y, maximum.z); //Setup the polygons for(PxU8 i=0; i < 6; i++) { mPolygons[i].mNbVerts = 4; mPolygons[i].mVRef8 = PxU16(i*4); } // ### planes needs *very* careful checks // X axis mPolygons[1].mPlane.n = PxVec3(1.0f, 0.0f, 0.0f); mPolygons[1].mPlane.d = -mHalfSide.x; mPolygons[3].mPlane.n = PxVec3(-1.0f, 0.0f, 0.0f); mPolygons[3].mPlane.d = -mHalfSide.x; mPolygons[1].mMinIndex = 0; mPolygons[3].mMinIndex = 1; PX_ASSERT(mPolygons[1].getMin(mVertices) == -mHalfSide.x); PX_ASSERT(mPolygons[3].getMin(mVertices) == -mHalfSide.x); // Y axis mPolygons[4].mPlane.n = PxVec3(0.f, 1.0f, 0.0f); mPolygons[4].mPlane.d = -mHalfSide.y; mPolygons[5].mPlane.n = PxVec3(0.0f, -1.0f, 0.0f); mPolygons[5].mPlane.d = -mHalfSide.y; mPolygons[4].mMinIndex = 0; mPolygons[5].mMinIndex = 2; PX_ASSERT(mPolygons[4].getMin(mVertices) == -mHalfSide.y); PX_ASSERT(mPolygons[5].getMin(mVertices) == -mHalfSide.y); // Z axis mPolygons[2].mPlane.n = PxVec3(0.f, 0.0f, 1.0f); mPolygons[2].mPlane.d = -mHalfSide.z; mPolygons[0].mPlane.n = PxVec3(0.0f, 0.0f, -1.0f); mPolygons[0].mPlane.d = -mHalfSide.z; mPolygons[2].mMinIndex = 0; mPolygons[0].mMinIndex = 4; PX_ASSERT(mPolygons[2].getMin(mVertices) == -mHalfSide.z); PX_ASSERT(mPolygons[0].getMin(mVertices) == -mHalfSide.z); } void PCMPolygonalBox::getPolygonalData(PolygonalData* PX_RESTRICT dst) const { dst->mCenter = PxVec3(0.0f, 0.0f, 0.0f); dst->mNbVerts = 8; dst->mNbPolygons = 6; dst->mPolygons = mPolygons; dst->mNbEdges = 0; dst->mVerts = mVertices; dst->mPolygonVertexRefs = gPCMBoxPolygonData; dst->mFacesByEdges = NULL; dst->mVerticesByEdges = NULL; dst->mBigData = NULL; dst->mInternal.mRadius = 0.0f; dst->mInternal.mExtents[0] = mHalfSide.x; dst->mInternal.mExtents[1] = mHalfSide.y; dst->mInternal.mExtents[2] = mHalfSide.z; dst->mScale = PxMeshScale(); } static void getPCMPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const ConvexHullData* PX_RESTRICT src, const Mat33V& vertexToShape) { using namespace aos; const Vec3V vertexSpaceCenterOfMass = V3LoadU(src->mCenterOfMass); const Vec3V shapeSpaceCenterOfMass = M33MulV3(vertexToShape, vertexSpaceCenterOfMass); V3StoreU(shapeSpaceCenterOfMass, dst->mCenter); dst->mNbVerts = src->mNbHullVertices; dst->mNbPolygons = src->mNbPolygons; dst->mNbEdges = src->mNbEdges; dst->mPolygons = src->mPolygons; dst->mVerts = src->getHullVertices(); dst->mPolygonVertexRefs = src->getVertexData8(); dst->mFacesByEdges = src->getFacesByEdges8(); dst->mVerticesByEdges = src->getVerticesByEdges16(); dst->mBigData = src->mBigConvexRawData; dst->mInternal = src->mInternal; dst->mScale = PxMeshScale(); } static void getPCMPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const ConvexHullData* PX_RESTRICT src, const Cm::FastVertex2ShapeScaling& scaling, const PxMeshScale& convexScale) { dst->mCenter = scaling * src->mCenterOfMass; dst->mNbVerts = src->mNbHullVertices; dst->mNbPolygons = src->mNbPolygons; dst->mNbEdges = src->mNbEdges; dst->mPolygons = src->mPolygons; dst->mVerts = src->getHullVertices(); dst->mPolygonVertexRefs = src->getVertexData8(); dst->mFacesByEdges = src->getFacesByEdges8(); dst->mVerticesByEdges = src->getVerticesByEdges16(); dst->mBigData = src->mBigConvexRawData; dst->mInternal = src->mInternal; dst->mScale = convexScale; } void Gu::getPCMConvexData(const ConvexHullV& convexHull, bool idtScale, PolygonalData& polyData) { PX_ASSERT(!convexHull.hullData->mAABB.isEmpty()); //this is used to calculate the convex hull's center of mass getPCMPolygonalData_Convex(&polyData, convexHull.hullData, convexHull.vertex2Shape); if(!idtScale) polyData.mInternal.reset(); } bool Gu::getPCMConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData) { const bool idtScale = shapeConvex.scale.isIdentity(); if(!idtScale) scaling.init(shapeConvex.scale); const ConvexHullData* hullData = _getHullData(shapeConvex); PX_ASSERT(!hullData->mAABB.isEmpty()); bounds = hullData->mAABB.transformFast(scaling.getVertex2ShapeSkew()); getPCMPolygonalData_Convex(&polyData, hullData, scaling, shapeConvex.scale); return idtScale; }
7,251
C++
33.698564
148
0.7028
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactCapsuleHeightField.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxTriangleMesh.h" #include "geomutils/PxContactBuffer.h" #include "foundation/PxVecMath.h" #include "foundation/PxVecTransform.h" #include "GuVecTriangle.h" #include "GuContactMethodImpl.h" #include "GuHeightField.h" #include "GuPCMContactConvexCommon.h" #include "GuSegment.h" #include "GuInternal.h" #include "GuPCMContactMeshCallback.h" using namespace physx; using namespace Gu; using namespace aos; struct PCMCapsuleVsHeightfieldContactGenerationCallback : PCMHeightfieldContactGenerationCallback<PCMCapsuleVsHeightfieldContactGenerationCallback> { PCMCapsuleVsHeightfieldContactGenerationCallback& operator=(const PCMCapsuleVsHeightfieldContactGenerationCallback&); PCMCapsuleVsMeshContactGeneration mGeneration; PCMCapsuleVsHeightfieldContactGenerationCallback( const CapsuleV& capsule, const FloatVArg contactDistance, const FloatVArg replaceBreakingThreshold, const PxTransformV& capsuleTransform, const PxTransformV& heightfieldTransform, const PxTransform& heightfieldTransform1, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, HeightFieldUtil& hfUtil ) : PCMHeightfieldContactGenerationCallback<PCMCapsuleVsHeightfieldContactGenerationCallback>(hfUtil, heightfieldTransform1), mGeneration(capsule, contactDistance, replaceBreakingThreshold, capsuleTransform, heightfieldTransform, multiManifold, contactBuffer, deferredContacts) { } template<PxU32 CacheSize> void processTriangleCache(TriangleCache<CacheSize>& cache) { mGeneration.processTriangleCache<CacheSize, PCMCapsuleVsMeshContactGeneration>(cache); } }; bool Gu::pcmContactCapsuleHeightField(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxHeightFieldGeometry& shapeHeight = checkedCast<PxHeightFieldGeometry>(shape1); MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const FloatV capsuleRadius = FLoad(shapeCapsule.radius); const FloatV contactDist = FLoad(params.mContactDistance); const PxTransformV capsuleTransform = loadTransformA(transform0);//capsule transform const PxTransformV heightfieldTransform = loadTransformA(transform1);//height feild const PxTransformV curTransform = heightfieldTransform.transformInv(capsuleTransform); const FloatV replaceBreakingThreshold = FMul(capsuleRadius, FLoad(0.001f)); if(multiManifold.invalidate(curTransform, capsuleRadius, FLoad(0.02f))) { multiManifold.mNumManifolds = 0; multiManifold.setRelativeTransform(curTransform); HeightFieldUtil hfUtil(shapeHeight); const PxVec3 tmp = getCapsuleHalfHeightVector(transform0, shapeCapsule); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; const PxVec3 capsuleCenterInMesh = transform1.transformInv(transform0.p); const PxVec3 capsuleDirInMesh = transform1.rotateInv(tmp); const CapsuleV capsule(V3LoadU(capsuleCenterInMesh), V3LoadU(capsuleDirInMesh), capsuleRadius); PCMCapsuleVsHeightfieldContactGenerationCallback callback( capsule, contactDist, replaceBreakingThreshold, capsuleTransform, heightfieldTransform, transform1, multiManifold, contactBuffer, NULL, hfUtil ); // PT: TODO: improve these bounds - see computeCapsuleBounds hfUtil.overlapAABBTriangles(transform0, transform1, getLocalCapsuleBounds(inflatedRadius, shapeCapsule.halfHeight), callback); callback.mGeneration.processContacts(GU_CAPSULE_MANIFOLD_CACHE_SIZE, false); } else { const PxMatTransformV aToB(curTransform); // We must be in local space to use the cache const FloatV projectBreakingThreshold = FMul(capsuleRadius, FLoad(0.05f)); const FloatV refereshDistance = FAdd(capsuleRadius, contactDist); multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance); } return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, capsuleTransform, heightfieldTransform, capsuleRadius); }
5,765
C++
40.482014
147
0.807632
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactPlaneCapsule.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 "geomutils/PxContactBuffer.h" #include "GuVecCapsule.h" #include "GuContactMethodImpl.h" #include "GuPersistentContactManifold.h" using namespace physx; bool Gu::pcmContactPlaneCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(shape0); PX_UNUSED(renderOutput); using namespace aos; PersistentContactManifold& manifold = cache.getManifold(); PxPrefetchLine(&manifold, 256); // Get actual shape data const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape1); const PxTransformV transf0 = loadTransformA(transform1);//capsule transform const PxTransformV transf1 = loadTransformA(transform0);//plane transform //capsule to plane const PxTransformV aToB(transf1.transformInv(transf0)); //in world space const Vec3V planeNormal = V3Normalize(QuatGetBasisVector0(transf1.q)); const Vec3V contactNormal = V3Neg(planeNormal); //ML:localNormal is the local space of plane normal, however, because shape1 is capulse and shape0 is plane, we need to use the reverse of contact normal(which will be the plane normal) to make the refreshContactPoints //work out the correct pentration for points const Vec3V localNormal = V3UnitX(); const FloatV contactDist = FLoad(params.mContactDistance); const FloatV radius = FLoad(shapeCapsule.radius); const FloatV halfHeight = FLoad(shapeCapsule.halfHeight); //capsule is in the local space of plane(n = (1.f, 0.f, 0.f), d=0.f) const Vec3V basisVector = QuatGetBasisVector0(aToB.q); const Vec3V tmp = V3Scale(basisVector, halfHeight); const Vec3V s = V3Add(aToB.p, tmp); const Vec3V e = V3Sub(aToB.p, tmp); const FloatV inflatedRadius = FAdd(radius, contactDist); const FloatV replaceBreakingThreshold = FMul(radius, FLoad(0.001f)); const FloatV projectBreakingThreshold = FMul(radius, FLoad(0.05f)); const PxU32 initialContacts = manifold.mNumContacts; //manifold.refreshContactPoints(curRTrans, projectBreakingThreshold, contactDist); const FloatV refreshDist = FAdd(contactDist, radius); manifold.refreshContactPoints(aToB, projectBreakingThreshold, refreshDist); const PxU32 newContacts = manifold.mNumContacts; const bool bLostContacts = (newContacts != initialContacts);//((initialContacts == 0) || (newContacts != initialContacts)); if(bLostContacts || manifold.invalidate_PrimitivesPlane(aToB, radius, FLoad(0.02f))) { manifold.mNumContacts = 0; manifold.setRelativeTransform(aToB); //calculate the distance from s to the plane const FloatV signDist0 = V3GetX(s);//V3Dot(localNormal, s); if(FAllGrtr(inflatedRadius, signDist0)) { const Vec3V localPointA = aToB.transformInv(s); const Vec3V localPointB = V3NegScaleSub(localNormal, signDist0, s); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), signDist0); //add to manifold manifold.addManifoldPoint2(localPointA, localPointB, localNormalPen, replaceBreakingThreshold); } const FloatV signDist1 = V3GetX(e);//V3Dot(localNormal, e); if(FAllGrtr(inflatedRadius, signDist1)) { const Vec3V localPointA = aToB.transformInv(e); const Vec3V localPointB = V3NegScaleSub(localNormal, signDist1, e); const Vec4V localNormalPen = V4SetW(Vec4V_From_Vec3V(localNormal), signDist1); //add to manifold manifold.addManifoldPoint2(localPointA, localPointB, localNormalPen, replaceBreakingThreshold); } manifold.addManifoldContactsToContactBuffer(contactBuffer, contactNormal, planeNormal, transf0, radius, contactDist); #if PCM_LOW_LEVEL_DEBUG manifold.drawManifold(*renderOutput, transf0, transf1); #endif return manifold.getNumContacts() > 0; } else { manifold.addManifoldContactsToContactBuffer(contactBuffer, contactNormal, planeNormal, transf0, radius, contactDist); return manifold.getNumContacts() > 0; } }
5,449
C++
42.951613
219
0.772619
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenUtil.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 "GuPCMContactGenUtil.h" using namespace physx; using namespace Gu; using namespace aos; bool Gu::contains(Vec3V* verts, PxU32 numVerts, const Vec3VArg p, const Vec3VArg min, const Vec3VArg max) { const BoolV tempCon = BOr(V3IsGrtr(min, p), V3IsGrtr(p, max)); const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon)); if (BAllEqTTTT(con)) return false; const FloatV tx = V3GetX(p); const FloatV ty = V3GetY(p); const FloatV eps = FEps(); const FloatV zero = FZero(); PxU32 intersectionPoints = 0; PxU32 i = 0, j = numVerts - 1; for (; i < numVerts; j = i++) { const FloatV jy = V3GetY(verts[j]); const FloatV iy = V3GetY(verts[i]); const FloatV jx = V3GetX(verts[j]); const FloatV ix = V3GetX(verts[i]); //if p is one of the end point, we will return intersect const BoolV con0 = BAnd(FIsEq(tx, jx), FIsEq(ty, jy)); const BoolV con1 = BAnd(FIsEq(tx, ix), FIsEq(ty, iy)); if (BAllEqTTTT(BOr(con0, con1))) return true; //(verts[i].y > test.y) != (points[j].y > test.y) const PxU32 yflag0 = FAllGrtr(jy, ty); const PxU32 yflag1 = FAllGrtr(iy, ty); //ML: the only case the ray will intersect this segment is when the p's y is in between two segments y if (yflag0 != yflag1) { //ML: choose ray, which start at p and every points in the ray will have the same y component //t1 = (yp - yj)/(yi - yj) //qx = xj + t1*(xi-xj) //t = qx - xp > 0 for the ray and segment intersection happen const FloatV jix = FSub(ix, jx); const FloatV jiy = FSub(iy, jy); //const FloatV jtx = FSub(tx, jy); const FloatV jty = FSub(ty, jy); const FloatV part1 = FMul(jty, jix); //const FloatV part2 = FMul(jx, jiy); //const FloatV part3 = FMul(V3Sub(tx, eps), jiy); const FloatV part2 = FMul(FAdd(jx, eps), jiy); const FloatV part3 = FMul(tx, jiy); const BoolV comp = FIsGrtr(jiy, zero); const FloatV tmp = FAdd(part1, part2); const FloatV comp1 = FSel(comp, tmp, part3); const FloatV comp2 = FSel(comp, part3, tmp); if (FAllGrtrOrEq(comp1, comp2)) { if (intersectionPoints == 1) return false; intersectionPoints++; } } } return intersectionPoints> 0; } PxI32 Gu::getPolygonIndex(const PolygonalData& polyData, const SupportLocal* map, const Vec3VArg normal, PxI32& polyIndex2) { //normal is in shape space, need to transform the vertex space const Vec3V n = M33TrnspsMulV3(map->vertex2Shape, normal); const Vec3V nnormal = V3Neg(n); const Vec3V planeN_ = V3LoadU_SafeReadW(polyData.mPolygons[0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class FloatV minProj = V3Dot(n, planeN_); const FloatV zero = FZero(); PxI32 closestFaceIndex = 0; polyIndex2 = -1; for (PxU32 i = 1; i < polyData.mNbPolygons; ++i) { const Vec3V planeN = V3LoadU_SafeReadW(polyData.mPolygons[i].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const FloatV proj = V3Dot(n, planeN); if (FAllGrtr(minProj, proj)) { minProj = proj; closestFaceIndex = PxI32(i); } } const PxU32 numEdges = polyData.mNbEdges; const PxU8* const edgeToFace = polyData.mFacesByEdges; //Loop through edges PxU32 closestEdge = 0xffffffff; FloatV maxDpSq = FMul(minProj, minProj); FloatV maxDpSq2 = FLoad(-10.0f); for (PxU32 i = 0; i < numEdges; ++i)//, inc = VecI32V_Add(inc, vOne)) { const PxU32 index = i * 2; const PxU8 f0 = edgeToFace[index]; const PxU8 f1 = edgeToFace[index + 1]; const Vec3V planeNormal0 = V3LoadU_SafeReadW(polyData.mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const Vec3V planeNormal1 = V3LoadU_SafeReadW(polyData.mPolygons[f1].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class // unnormalized edge normal const Vec3V edgeNormal = V3Add(planeNormal0, planeNormal1);//polys[f0].mPlane.n + polys[f1].mPlane.n; const FloatV enMagSq = V3Dot(edgeNormal, edgeNormal);//edgeNormal.magnitudeSquared(); //Test normal of current edge - squared test is valid if dp and maxDp both >= 0 const FloatV dp = V3Dot(edgeNormal, nnormal);//edgeNormal.dot(normal); const FloatV sqDp = FMul(dp, dp); if(f0==closestFaceIndex || f1==closestFaceIndex) { if(BAllEqTTTT(FIsGrtrOrEq(sqDp, maxDpSq2))) { maxDpSq2 = sqDp; polyIndex2 = f0==closestFaceIndex ? PxI32(f1) : PxI32(f0); } } const BoolV con0 = FIsGrtrOrEq(dp, zero); const BoolV con1 = FIsGrtr(sqDp, FMul(maxDpSq, enMagSq)); const BoolV con = BAnd(con0, con1); if (BAllEqTTTT(con)) { maxDpSq = FDiv(sqDp, enMagSq); closestEdge = i; } } if (closestEdge != 0xffffffff) { const PxU8* FBE = edgeToFace; const PxU32 index = closestEdge * 2; const PxU32 f0 = FBE[index]; const PxU32 f1 = FBE[index + 1]; const Vec3V planeNormal0 = V3LoadU_SafeReadW(polyData.mPolygons[f0].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const Vec3V planeNormal1 = V3LoadU_SafeReadW(polyData.mPolygons[f1].mPlane.n); // PT: safe because 'd' follows 'n' in the plane class const FloatV dp0 = V3Dot(planeNormal0, nnormal); const FloatV dp1 = V3Dot(planeNormal1, nnormal); if (FAllGrtr(dp0, dp1)) { closestFaceIndex = PxI32(f0); polyIndex2 = PxI32(f1); } else { closestFaceIndex = PxI32(f1); polyIndex2 = PxI32(f0); } } return closestFaceIndex; } PxU32 Gu::getWitnessPolygonIndex(const PolygonalData& polyData, const SupportLocal* map, const Vec3VArg normal, const Vec3VArg closest, PxReal tolerance) { PxReal pd[256]; //first pass : calculate the smallest distance from the closest point to the polygon face //transform the closest p to vertex space const Vec3V p = M33MulV3(map->shape2Vertex, closest); PxU32 closestFaceIndex = 0; PxVec3 closestP; V3StoreU(p, closestP); const PxReal eps = -tolerance; PxPlane plane = polyData.mPolygons[0].mPlane; PxReal dist = plane.distance(closestP); PxReal minDist = dist >= eps ? PxAbs(dist) : PX_MAX_F32; pd[0] = minDist; PxReal maxDist = dist; PxU32 maxFaceIndex = 0; for (PxU32 i = 1; i < polyData.mNbPolygons; ++i) { plane = polyData.mPolygons[i].mPlane; dist = plane.distance(closestP); pd[i] = dist >= eps ? PxAbs(dist) : PX_MAX_F32; if (minDist > pd[i]) { minDist = pd[i]; closestFaceIndex = i; } if (dist > maxDist) { maxDist = dist; maxFaceIndex = i; } } if (minDist == PX_MAX_F32) return maxFaceIndex; //second pass : select the face which has the normal most close to the gjk/epa normal Vec4V plane4 = V4LoadU(&polyData.mPolygons[closestFaceIndex].mPlane.n.x); Vec3V n = Vec3V_From_Vec4V(plane4); n = V3Normalize(M33TrnspsMulV3(map->shape2Vertex, n)); FloatV bestProj = V3Dot(n, normal); const PxU32 firstPassIndex = closestFaceIndex; for (PxU32 i = 0; i< polyData.mNbPolygons; ++i) { //if the difference between the minimum distance and the distance of p to plane i is within tolerance, we use the normal to chose the best plane if ((tolerance >(pd[i] - minDist)) && (firstPassIndex != i)) { plane4 = V4LoadU(&polyData.mPolygons[i].mPlane.n.x); n = Vec3V_From_Vec4V(plane4); //rotate the plane normal to shape space. We can roate normal into the vertex space. The reason for //that is because it will lose some numerical precision if the object has large scale and this algorithm //will choose different face n = V3Normalize(M33TrnspsMulV3(map->shape2Vertex, n)); FloatV proj = V3Dot(n, normal); if (FAllGrtr(bestProj, proj)) { closestFaceIndex = i; bestProj = proj; } } } return closestFaceIndex; } /* PX_FORCE_INLINE bool boxContainsInXY(const FloatVArg x, const FloatVArg y, const Vec3VArg p, const Vec3V* verts, const Vec3VArg min, const Vec3VArg max) { using namespace aos; const BoolV tempCon = BOr(V3IsGrtr(min, p), V3IsGrtr(p, max)); const BoolV con = BOr(BGetX(tempCon), BGetY(tempCon)); if(BAllEqTTTT(con)) return false; const FloatV zero = FZero(); FloatV PreviousX = V3GetX(verts[3]); FloatV PreviousY = V3GetY(verts[3]); // Loop through quad vertices for(PxI32 i=0; i<4; i++) { const FloatV CurrentX = V3GetX(verts[i]); const FloatV CurrentY = V3GetY(verts[i]); // |CurrentX - PreviousX x - PreviousX| // |CurrentY - PreviousY y - PreviousY| // => similar to backface culling, check each one of the 4 triangles are consistent, in which case // the point is within the parallelogram. const FloatV v00 = FSub(CurrentX, PreviousX); const FloatV v01 = FSub(y, PreviousY); const FloatV v10 = FSub(CurrentY, PreviousY); const FloatV v11 = FSub(x, PreviousX); const FloatV temp0 = FMul(v00, v01); const FloatV temp1 = FMul(v10, v11); if(FAllGrtrOrEq(FSub(temp0, temp1), zero)) return false; PreviousX = CurrentX; PreviousY = CurrentY; } return true; } */
10,488
C++
32.298413
155
0.69508
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactSphereHeightField.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "geometry/PxTriangleMesh.h" #include "geomutils/PxContactBuffer.h" #include "GuVecBox.h" #include "GuVecConvexHull.h" #include "GuVecConvexHullNoScale.h" #include "GuVecTriangle.h" #include "GuContactMethodImpl.h" #include "GuHeightField.h" #include "GuPCMContactConvexCommon.h" #include "GuPCMContactMeshCallback.h" using namespace physx; using namespace Gu; using namespace aos; namespace { struct PCMSphereVsHeightfieldContactGenerationCallback : PCMHeightfieldContactGenerationCallback<PCMSphereVsHeightfieldContactGenerationCallback> { PCMSphereVsMeshContactGeneration mGeneration; PCMSphereVsHeightfieldContactGenerationCallback( const Vec3VArg sphereCenter, const FloatVArg sphereRadius, const FloatVArg contactDistance, const FloatVArg replaceBreakingThreshold, const PxTransformV& sphereTransform, const PxTransformV& heightfieldTransform, const PxTransform& heightfieldTransform1, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, HeightFieldUtil& hfUtil ) : PCMHeightfieldContactGenerationCallback<PCMSphereVsHeightfieldContactGenerationCallback>(hfUtil, heightfieldTransform1), mGeneration(sphereCenter, sphereRadius, contactDistance, replaceBreakingThreshold, sphereTransform, heightfieldTransform, multiManifold, contactBuffer, deferredContacts) { } template<PxU32 CacheSize> void processTriangleCache(TriangleCache<CacheSize>& cache) { mGeneration.processTriangleCache<CacheSize, PCMSphereVsMeshContactGeneration>(cache); } }; } bool Gu::pcmContactSphereHeightField(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxHeightFieldGeometry& shapeHeight = checkedCast<PxHeightFieldGeometry>(shape1); MultiplePersistentContactManifold& multiManifold = cache.getMultipleManifold(); const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&transform0.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&transform1.p.x); const FloatV sphereRadius = FLoad(shapeSphere.radius); const FloatV contactDist = FLoad(params.mContactDistance); const PxTransformV sphereTransform(p0, q0);//sphere transform const PxTransformV heightfieldTransform(p1, q1);//height feild const PxTransformV curTransform = heightfieldTransform.transformInv(sphereTransform); // We must be in local space to use the cache if(multiManifold.invalidate(curTransform, sphereRadius, FLoad(0.02f))) { multiManifold.mNumManifolds = 0; multiManifold.setRelativeTransform(curTransform); const FloatV replaceBreakingThreshold = FMul(sphereRadius, FLoad(0.001f)); HeightFieldUtil hfUtil(shapeHeight); PxBounds3 localBounds; const PxVec3 localSphereCenter = getLocalSphereData(localBounds, transform0, transform1, shapeSphere.radius + params.mContactDistance); const Vec3V sphereCenter = V3LoadU(localSphereCenter); PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE> delayedContacts; PCMSphereVsHeightfieldContactGenerationCallback blockCallback( sphereCenter, sphereRadius, contactDist, replaceBreakingThreshold, sphereTransform, heightfieldTransform, transform1, multiManifold, contactBuffer, &delayedContacts, hfUtil); hfUtil.overlapAABBTriangles(localBounds, blockCallback); blockCallback.mGeneration.generateLastContacts(); blockCallback.mGeneration.processContacts(GU_SPHERE_MANIFOLD_CACHE_SIZE, false); } else { const PxMatTransformV aToB(curTransform); const FloatV projectBreakingThreshold = FMul(sphereRadius, FLoad(0.05f)); const FloatV refereshDistance = FAdd(sphereRadius, contactDist); multiManifold.refreshManifold(aToB, projectBreakingThreshold, refereshDistance); } return multiManifold.addManifoldContactsToContactBuffer(contactBuffer, sphereTransform, heightfieldTransform, sphereRadius); }
5,651
C++
38.25
145
0.801805
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactConvexCommon.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_PCM_CONTACT_CONVEX_COMMON_H #define GU_PCM_CONTACT_CONVEX_COMMON_H #define PCM_MAX_CONTACTPATCH_SIZE 32 #include "geomutils/PxContactBuffer.h" #include "GuVecCapsule.h" #include "GuPCMTriangleContactGen.h" #include "GuTriangleCache.h" #include "foundation/PxInlineArray.h" namespace physx { namespace Gu { #define MAX_CACHE_SIZE 128 //sizeof(PCMDeferredPolyData)/sizeof(PxU32) = 15, 960/15 = 64 triangles in the local array #define LOCAL_PCM_CONTACTS_SIZE 960 class PCMMeshContactGeneration { PX_NOCOPY(PCMMeshContactGeneration) public: PCMContactPatch mContactPatch[PCM_MAX_CONTACTPATCH_SIZE]; PCMContactPatch* mContactPatchPtr[PCM_MAX_CONTACTPATCH_SIZE]; const aos::FloatV mContactDist; const aos::FloatV mReplaceBreakingThreshold; const aos::PxTransformV& mConvexTransform; const aos::PxTransformV& mMeshTransform; Gu::MultiplePersistentContactManifold& mMultiManifold; PxContactBuffer& mContactBuffer; aos::FloatV mAcceptanceEpsilon; aos::FloatV mSqReplaceBreakingThreshold; aos::PxMatTransformV mMeshToConvex; Gu::MeshPersistentContact* mManifoldContacts; PxU32 mNumContacts; PxU32 mNumContactPatch; PxU32 mNumCalls; Gu::CacheMap<Gu::CachedEdge, MAX_CACHE_SIZE> mEdgeCache; Gu::CacheMap<Gu::CachedVertex, MAX_CACHE_SIZE> mVertexCache; PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* mDeferredContacts; PxRenderOutput* mRenderOutput; PCMMeshContactGeneration( const aos::FloatVArg contactDist, const aos::FloatVArg replaceBreakingThreshold, const aos::PxTransformV& convexTransform, const aos::PxTransformV& meshTransform, Gu::MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, PxRenderOutput* renderOutput ) : mContactDist(contactDist), mReplaceBreakingThreshold(replaceBreakingThreshold), mConvexTransform(convexTransform), mMeshTransform(meshTransform), mMultiManifold(multiManifold), mContactBuffer(contactBuffer), mDeferredContacts(deferredContacts), mRenderOutput(renderOutput) { using namespace aos; mNumContactPatch = 0; mNumContacts = 0; mNumCalls = 0; mMeshToConvex = mConvexTransform.transformInv(mMeshTransform); //Assign the PCMContactPatch to the PCMContactPathPtr for(PxU32 i=0; i<PCM_MAX_CONTACTPATCH_SIZE; ++i) { mContactPatchPtr[i] = &mContactPatch[i]; } mManifoldContacts = PX_CP_TO_MPCP(contactBuffer.contacts); mSqReplaceBreakingThreshold = FMul(replaceBreakingThreshold, replaceBreakingThreshold); mAcceptanceEpsilon = FLoad(0.996f);//5 degree //mAcceptanceEpsilon = FloatV_From_F32(0.9999);//5 degree } template <PxU32 TriangleCount, typename Derived> bool processTriangleCache(Gu::TriangleCache<TriangleCount>& cache) { PxU32 count = cache.mNumTriangles; PxVec3* verts = cache.mVertices; PxU32* vertInds = cache.mIndices; PxU32* triInds = cache.mTriangleIndex; PxU8* edgeFlags = cache.mEdgeFlags; while(count--) { (static_cast<Derived*>(this))->processTriangle(verts, *triInds, *edgeFlags, vertInds); verts += 3; vertInds += 3; triInds++; edgeFlags++; } return true; } void prioritizeContactPatches(); void addManifoldPointToPatch(const aos::Vec3VArg currentPatchNormal, const aos::FloatVArg maxPen, PxU32 previousNumContacts); void processContacts(PxU8 maxContactPerManifold, const bool isNotLastPatch = true); }; // This function is based on the current patch normal to either create a new patch or merge the manifold contacts in this patch with the manifold contacts in the last existing // patch. This means there might be more than GU_SINGLE_MANIFOLD_CACHE_SIZE in a SinglePersistentContactManifold. PX_FORCE_INLINE void PCMMeshContactGeneration::addManifoldPointToPatch(const aos::Vec3VArg currentPatchNormal, const aos::FloatVArg maxPen, PxU32 previousNumContacts) { using namespace aos; bool foundPatch = false; //we have existing patch if(mNumContactPatch > 0) { //if the direction between the last existing patch normal and the current patch normal are within acceptance epsilon, which means we will be //able to merge the last patch's contacts with the current patch's contacts. This is just to avoid to create an extra patch. We have some logic //later to refine the patch again if(FAllGrtr(V3Dot(mContactPatch[mNumContactPatch-1].mPatchNormal, currentPatchNormal), mAcceptanceEpsilon)) { //get the last patch PCMContactPatch& patch = mContactPatch[mNumContactPatch-1]; //remove duplicate contacts for(PxU32 i = patch.mStartIndex; i<patch.mEndIndex; ++i) { for(PxU32 j = previousNumContacts; j<mNumContacts; ++j) { Vec3V dif = V3Sub(mManifoldContacts[j].mLocalPointB, mManifoldContacts[i].mLocalPointB); FloatV d = V3Dot(dif, dif); if(FAllGrtr(mSqReplaceBreakingThreshold, d)) { if(FAllGrtr(V4GetW(mManifoldContacts[i].mLocalNormalPen), V4GetW(mManifoldContacts[j].mLocalNormalPen))) { //The new contact is deeper than the old contact so we keep the deeper contact mManifoldContacts[i] = mManifoldContacts[j]; } mManifoldContacts[j] = mManifoldContacts[mNumContacts-1]; mNumContacts--; j--; } } } patch.mEndIndex = mNumContacts; patch.mPatchMaxPen = FMin(patch.mPatchMaxPen, maxPen); foundPatch = true; } } //If there are no existing patch which match the currentPatchNormal, we will create a new patch if(!foundPatch) { mContactPatch[mNumContactPatch].mStartIndex = previousNumContacts; mContactPatch[mNumContactPatch].mEndIndex = mNumContacts; mContactPatch[mNumContactPatch].mPatchMaxPen = maxPen; mContactPatch[mNumContactPatch++].mPatchNormal = currentPatchNormal; } } // This function sort the contact patch based on the max penetration so that deepest penetration contact patch will be in front of the less penetration contact // patch PX_FORCE_INLINE void PCMMeshContactGeneration::prioritizeContactPatches() { //we are using insertion sort to prioritize contact patchs using namespace aos; //sort the contact patch based on the max penetration for(PxU32 i=1; i<mNumContactPatch; ++i) { const PxU32 indexi = i-1; if(FAllGrtr(mContactPatchPtr[indexi]->mPatchMaxPen, mContactPatchPtr[i]->mPatchMaxPen)) { //swap PCMContactPatch* tmp = mContactPatchPtr[indexi]; mContactPatchPtr[indexi] = mContactPatchPtr[i]; mContactPatchPtr[i] = tmp; for(PxI32 j=PxI32(i-2); j>=0; j--) { const PxU32 indexj = PxU32(j+1); if(FAllGrtrOrEq(mContactPatchPtr[indexj]->mPatchMaxPen, mContactPatchPtr[j]->mPatchMaxPen)) break; //swap PCMContactPatch* temp = mContactPatchPtr[indexj]; mContactPatchPtr[indexj] = mContactPatchPtr[j]; mContactPatchPtr[j] = temp; } } } } PX_FORCE_INLINE void PCMMeshContactGeneration::processContacts(PxU8 maxContactPerManifold, bool isNotLastPatch) { using namespace aos; if(mNumContacts != 0) { //reorder the contact patches based on the max penetration prioritizeContactPatches(); //connect the patches which's angle between patch normals are within 5 degree mMultiManifold.refineContactPatchConnective(mContactPatchPtr, mNumContactPatch, mManifoldContacts, mAcceptanceEpsilon); //get rid of duplicate manifold contacts in connected contact patches mMultiManifold.reduceManifoldContactsInDifferentPatches(mContactPatchPtr, mNumContactPatch, mManifoldContacts, mNumContacts, mSqReplaceBreakingThreshold); //add the manifold contact to the corresponding manifold mMultiManifold.addManifoldContactPoints(mManifoldContacts, mNumContacts, mContactPatchPtr, mNumContactPatch, mSqReplaceBreakingThreshold, mAcceptanceEpsilon, maxContactPerManifold); mNumContacts = 0; mNumContactPatch = 0; if(isNotLastPatch) { //remap the contact patch pointer to contact patch for(PxU32 i=0; i<PCM_MAX_CONTACTPATCH_SIZE; ++i) { mContactPatchPtr[i] = &mContactPatch[i]; } } } } struct PCMDeferredPolyData { public: PxVec3 mVerts[3]; //36 PxU32 mInds[3]; //48 PxU32 mTriangleIndex; //52 PxU32 mFeatureIndex; //56 PxU32 triFlags32; //60 }; #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class PCMConvexVsMeshContactGeneration : public PCMMeshContactGeneration { PCMConvexVsMeshContactGeneration &operator=(PCMConvexVsMeshContactGeneration &); public: aos::Vec3V mHullCenterMesh; const Gu::PolygonalData& mPolyData; const SupportLocal* mPolyMap; const Cm::FastVertex2ShapeScaling& mConvexScaling; bool mIdtConvexScale; bool mSilhouetteEdgesAreActive; PCMConvexVsMeshContactGeneration( const aos::FloatVArg contactDistance, const aos::FloatVArg replaceBreakingThreshold, const aos::PxTransformV& convexTransform, const aos::PxTransformV& meshTransform, Gu::MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, const Gu::PolygonalData& polyData, const SupportLocal* polyMap, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* delayedContacts, const Cm::FastVertex2ShapeScaling& convexScaling, bool idtConvexScale, bool silhouetteEdgesAreActive, PxRenderOutput* renderOutput ) : PCMMeshContactGeneration(contactDistance, replaceBreakingThreshold, convexTransform, meshTransform, multiManifold, contactBuffer, delayedContacts, renderOutput), mPolyData(polyData), mPolyMap(polyMap), mConvexScaling(convexScaling), mIdtConvexScale(idtConvexScale), mSilhouetteEdgesAreActive(silhouetteEdgesAreActive) { using namespace aos; // Hull center in local space const Vec3V hullCenterLocal = V3LoadU(mPolyData.mCenter); // Hull center in mesh space mHullCenterMesh = mMeshToConvex.transformInv(hullCenterLocal); } bool generateTriangleFullContactManifold(const Gu::TriangleV& localTriangle, PxU32 triangleIndex, const PxU32* triIndices, PxU8 triFlags, const Gu::PolygonalData& polyData, const Gu::SupportLocalImpl<Gu::TriangleV>* localTriMap, const Gu::SupportLocal* polyMap, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& patchNormal); bool generatePolyDataContactManifold(const Gu::TriangleV& localTriangle, PxU32 featureIndex, PxU32 triangleIndex, PxU8 triFlags, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& patchNormal); void generateLastContacts(); void addContactsToPatch(const aos::Vec3VArg patchNormal, PxU32 previousNumContacts); bool processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds); static bool generateTriangleFullContactManifold(const Gu::TriangleV& localTriangle, PxU32 triangleIndex, PxU8 triFlags, const Gu::PolygonalData& polyData, const Gu::SupportLocalImpl<Gu::TriangleV>* localTriMap, const Gu::SupportLocal* polyMap, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& patchNormal, PxRenderOutput* renderOutput = NULL); static bool processTriangle(const Gu::PolygonalData& polyData, const SupportLocal* polyMap, const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const aos::FloatVArg inflation, bool isDoubleSided, const aos::PxTransformV& convexTransform, const aos::PxMatTransformV& meshToConvex, Gu::MeshPersistentContact* manifoldContact, PxU32& numContacts); }; #if PX_VC #pragma warning(pop) #endif struct SortedTriangle { aos::FloatV mSquareDist; PxU32 mIndex; PX_FORCE_INLINE bool operator < (const SortedTriangle& data) const { return aos::FAllGrtrOrEq(mSquareDist, data.mSquareDist) ==0; } }; class PCMSphereVsMeshContactGeneration : public PCMMeshContactGeneration { public: aos::Vec3V mSphereCenter; aos::FloatV mSphereRadius; aos::FloatV mSqInflatedSphereRadius; PxInlineArray<SortedTriangle, 64> mSortedTriangle; PCMSphereVsMeshContactGeneration( const aos::Vec3VArg sphereCenter, const aos::FloatVArg sphereRadius, const aos::FloatVArg contactDist, const aos::FloatVArg replaceBreakingThreshold, const aos::PxTransformV& sphereTransform, const aos::PxTransformV& meshTransform, MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, PxRenderOutput* renderOutput = NULL ) : PCMMeshContactGeneration(contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer, deferredContacts, renderOutput), mSphereCenter(sphereCenter), mSphereRadius(sphereRadius) { using namespace aos; const FloatV inflatedSphereRadius = FAdd(sphereRadius, contactDist); mSqInflatedSphereRadius = FMul(inflatedSphereRadius, inflatedSphereRadius); } bool processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds); void generateLastContacts(); void addToPatch(const aos::Vec3VArg contactP, const aos::Vec3VArg patchNormal, const aos::FloatV pen, PxU32 triangleIndex); }; class PCMCapsuleVsMeshContactGeneration : public PCMMeshContactGeneration { PCMCapsuleVsMeshContactGeneration &operator=(PCMCapsuleVsMeshContactGeneration &); public: aos::FloatV mInflatedRadius; aos::FloatV mSqInflatedRadius; const CapsuleV& mCapsule; PCMCapsuleVsMeshContactGeneration( const CapsuleV& capsule, const aos::FloatVArg contactDist, const aos::FloatVArg replaceBreakingThreshold, const aos::PxTransformV& sphereTransform, const aos::PxTransformV& meshTransform, Gu::MultiplePersistentContactManifold& multiManifold, PxContactBuffer& contactBuffer, PxInlineArray<PxU32, LOCAL_PCM_CONTACTS_SIZE>* deferredContacts, PxRenderOutput* renderOutput = NULL ) : PCMMeshContactGeneration(contactDist, replaceBreakingThreshold, sphereTransform, meshTransform, multiManifold, contactBuffer, deferredContacts, renderOutput), mCapsule(capsule) { using namespace aos; mInflatedRadius = FAdd(capsule.radius, contactDist); mSqInflatedRadius = FMul(mInflatedRadius, mInflatedRadius); } void generateEEContacts(const aos::Vec3VArg a, const aos::Vec3VArg b,const aos::Vec3VArg c, const aos::Vec3VArg normal, PxU32 triangleIndex, const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg sqInflatedRadius, PxU32 previousNumContacts, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts); void generateEE(const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg sqInflatedRadius, const aos::Vec3VArg normal, PxU32 triangleIndex, const aos::Vec3VArg a, const aos::Vec3VArg b, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts); static void generateContacts(const aos::Vec3VArg a, const aos::Vec3VArg b,const aos::Vec3VArg c, const aos::Vec3VArg planeNormal, const aos::Vec3VArg normal, PxU32 triangleIndex, const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg inflatedRadius, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts); static void generateEEContactsMTD(const aos::Vec3VArg a, const aos::Vec3VArg b,const aos::Vec3VArg c, const aos::Vec3VArg normal, PxU32 triangleIndex, const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg inflatedRadius, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts); static void generateEEMTD(const aos::Vec3VArg p, const aos::Vec3VArg q, const aos::FloatVArg inflatedRadius, const aos::Vec3VArg normal, PxU32 triangleIndex, const aos::Vec3VArg a, const aos::Vec3VArg b, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts); bool processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds); static bool processTriangle(const TriangleV& triangle, PxU32 triangleIndex, const CapsuleV& capsule, const aos::FloatVArg inflatedRadius, const PxU8 triFlag, Gu::MeshPersistentContact* manifoldContacts, PxU32& numContacts); }; } } #endif
17,770
C
40.715962
327
0.776083
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGenUtil.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_PCM_CONTACT_GEN_UTIL_H #define GU_PCM_CONTACT_GEN_UTIL_H #include "foundation/PxVecMath.h" #include "geomutils/PxContactBuffer.h" #include "GuShapeConvex.h" #include "GuVecCapsule.h" #include "GuConvexSupportTable.h" //The smallest epsilon we will permit (scaled by PxTolerancesScale.length) #define PCM_WITNESS_POINT_LOWER_EPS 1e-2f //The largest epsilon we will permit (scaled by PxTolerancesScale.length) #define PCM_WITNESS_POINT_UPPER_EPS 5e-2f namespace physx { namespace Gu { enum FeatureStatus { POLYDATA0, POLYDATA1, EDGE }; bool contains(aos::Vec3V* verts, PxU32 numVerts, const aos::Vec3VArg p, const aos::Vec3VArg min, const aos::Vec3VArg max); PX_FORCE_INLINE aos::FloatV signed2DTriArea(const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c) { using namespace aos; const Vec3V ca = V3Sub(a, c); const Vec3V cb = V3Sub(b, c); const FloatV t0 = FMul(V3GetX(ca), V3GetY(cb)); const FloatV t1 = FMul(V3GetY(ca), V3GetX(cb)); return FSub(t0, t1); } PxI32 getPolygonIndex(const Gu::PolygonalData& polyData, const SupportLocal* map, const aos::Vec3VArg normal, PxI32& polyIndex2); PX_FORCE_INLINE PxI32 getPolygonIndex(const Gu::PolygonalData& polyData, const SupportLocal* map, const aos::Vec3VArg normal) { using namespace aos; PxI32 index2; return getPolygonIndex(polyData, map, normal, index2); } PxU32 getWitnessPolygonIndex( const Gu::PolygonalData& polyData, const SupportLocal* map, const aos::Vec3VArg normal, const aos::Vec3VArg closest, PxReal tolerance); PX_FORCE_INLINE void outputPCMContact(PxContactBuffer& contactBuffer, PxU32& contactCount, const aos::Vec3VArg point, const aos::Vec3VArg normal, const aos::FloatVArg penetration, PxU32 internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX) { using namespace aos; // PT: TODO: the PCM capsule-capsule code was using this alternative version, is it better? // const Vec4V normalSep = V4SetW(Vec4V_From_Vec3V(normal), separation); // V4StoreA(normalSep, &point.normal.x); // Also aren't we overwriting maxImpulse with the position now? Ok to do so? PX_ASSERT(contactCount < PxContactBuffer::MAX_CONTACTS); PxContactPoint& contact = contactBuffer.contacts[contactCount++]; V4StoreA(Vec4V_From_Vec3V(normal), &contact.normal.x); V4StoreA(Vec4V_From_Vec3V(point), &contact.point.x); FStore(penetration, &contact.separation); PX_ASSERT(contact.point.isFinite()); PX_ASSERT(contact.normal.isFinite()); PX_ASSERT(PxIsFinite(contact.separation)); contact.internalFaceIndex1 = internalFaceIndex1; } PX_FORCE_INLINE bool outputSimplePCMContact(PxContactBuffer& contactBuffer, const aos::Vec3VArg point, const aos::Vec3VArg normal, const aos::FloatVArg penetration, PxU32 internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX) { outputPCMContact(contactBuffer, contactBuffer.count, point, normal, penetration, internalFaceIndex1); return true; } }//Gu }//physx #endif
4,663
C
40.642857
146
0.75638
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/pcm/GuPCMContactGen.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_PCM_CONTACT_GEN_H #define GU_PCM_CONTACT_GEN_H #include "GuConvexSupportTable.h" #include "GuPersistentContactManifold.h" #include "GuShapeConvex.h" #include "GuSeparatingAxes.h" #include "GuGJKType.h" #include "GuGJKUtil.h" namespace physx { namespace Gu { //full contact gen code for box/convexhull vs convexhull bool generateFullContactManifold(const Gu::PolygonalData& polyData0, const Gu::PolygonalData& polyData1, const Gu::SupportLocal* map0, const Gu::SupportLocal* map1, Gu::PersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, const aos::Vec3VArg normal, const aos::Vec3VArg closestA, const aos::Vec3VArg closestB, PxReal toleranceA, PxReal toleranceB, bool doOverlapTest, PxRenderOutput* renderOutput, PxReal toleranceLength); //full contact gen code for capsule vs convexhulll bool generateFullContactManifold(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, const aos::PxMatTransformV& aToB, Gu::PersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& normal, const aos::Vec3VArg closest, PxReal tolerance, bool doOverlapTest, PxReal toleranceScale); //full contact gen code for capsule vs box bool generateCapsuleBoxFullContactManifold(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, const aos::PxMatTransformV& aToB, Gu::PersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& normal, const aos::Vec3VArg closest, PxReal boxMargin, bool doOverlapTest, PxReal toleranceScale, PxRenderOutput* renderOutput); //based on the gjk status to decide whether we should do full contact gen with GJK/EPA normal. Also, this method store //GJK/EPA point to the manifold in case full contact gen doesn't generate any contact bool addGJKEPAContacts(const Gu::GjkConvex* relativeConvex, const Gu::GjkConvex* localConvex, const aos::PxMatTransformV& aToB, Gu::GjkStatus status, Gu::PersistentContact* manifoldContacts, const aos::FloatV replaceBreakingThreshold, const aos::FloatV toleranceLength, GjkOutput& output, Gu::PersistentContactManifold& manifold); //MTD code for box/convexhull vs box/convexhull bool computeMTD(const Gu::PolygonalData& polyData0, const Gu::PolygonalData& polyData1, const SupportLocal* map0, const SupportLocal* map1, aos::FloatV& penDepth, aos::Vec3V& normal); //MTD code for capsule vs box/convexhull bool computeMTD(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, aos::FloatV& penDepth, aos::Vec3V& normal); //full contact gen code for sphere vs convexhull bool generateSphereFullContactManifold(const Gu::CapsuleV& capsule, const Gu::PolygonalData& polyData, const Gu::SupportLocal* map, Gu::PersistentContact* manifoldContacts, PxU32& numContacts, const aos::FloatVArg contactDist, aos::Vec3V& normal, bool doOverlapTest); } } #endif
4,685
C
61.479999
231
0.784205
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexSupportTable.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEX_SUPPORT_TABLE_H #define GU_CONVEX_SUPPORT_TABLE_H #include "common/PxPhysXCommonConfig.h" #include "GuVecConvex.h" #include "foundation/PxVecTransform.h" namespace physx { namespace Gu { class TriangleV; class CapsuleV; class BoxV; class ConvexHullV; class ConvexHullNoScaleV; #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class SupportLocal { public: aos::Vec3V shapeSpaceCenterOfMass; const aos::PxTransformV& transform; const aos::Mat33V& vertex2Shape; const aos::Mat33V& shape2Vertex; const bool isIdentityScale; SupportLocal(const aos::PxTransformV& _transform, const aos::Mat33V& _vertex2Shape, const aos::Mat33V& _shape2Vertex, const bool _isIdentityScale = true): transform(_transform), vertex2Shape(_vertex2Shape), shape2Vertex(_shape2Vertex), isIdentityScale(_isIdentityScale) { } PX_FORCE_INLINE void setShapeSpaceCenterofMass(const aos::Vec3VArg _shapeSpaceCenterOfMass) { shapeSpaceCenterOfMass = _shapeSpaceCenterOfMass; } virtual ~SupportLocal() {} virtual aos::Vec3V doSupport(const aos::Vec3VArg dir) const = 0; virtual void doSupport(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max) const = 0; virtual void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts)const = 0; protected: SupportLocal& operator=(const SupportLocal&); }; #if PX_VC #pragma warning(pop) #endif template <typename Convex> class SupportLocalImpl : public SupportLocal { public: const Convex& conv; SupportLocalImpl(const Convex& _conv, const aos::PxTransformV& _transform, const aos::Mat33V& _vertex2Shape, const aos::Mat33V& _shape2Vertex, const bool _isIdentityScale = true) : SupportLocal(_transform, _vertex2Shape, _shape2Vertex, _isIdentityScale), conv(_conv) { } aos::Vec3V doSupport(const aos::Vec3VArg dir) const { //return conv.supportVertsLocal(dir); return conv.supportLocal(dir); } void doSupport(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max) const { return conv.supportLocal(dir, min, max); } void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts) const { conv.populateVerts(inds, numInds, originalVerts, verts); } protected: SupportLocalImpl& operator=(const SupportLocalImpl&); }; } } #endif
4,185
C
34.777777
183
0.745998
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexMesh.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/PxFoundation.h" #include "GuConvexMesh.h" #include "GuBigConvexData2.h" #include "GuMeshFactory.h" using namespace physx; using namespace Gu; using namespace Cm; bool ConvexMesh::getPolygonData(PxU32 i, PxHullPolygon& data) const { if(i>=mHullData.mNbPolygons) return false; const HullPolygonData& poly = mHullData.mPolygons[i]; data.mPlane[0] = poly.mPlane.n.x; data.mPlane[1] = poly.mPlane.n.y; data.mPlane[2] = poly.mPlane.n.z; data.mPlane[3] = poly.mPlane.d; data.mNbVerts = poly.mNbVerts; data.mIndexBase = poly.mVRef8; return true; } static void initConvexHullData(ConvexHullData& data) { data.mAABB.setEmpty(); data.mCenterOfMass = PxVec3(0); data.mNbEdges = PxBitAndWord(); data.mNbHullVertices = 0; data.mNbPolygons = 0; data.mPolygons = NULL; data.mBigConvexRawData = NULL; data.mInternal.mRadius = 0.0f; data.mInternal.mExtents[0] = data.mInternal.mExtents[1] = data.mInternal.mExtents[2] = 0.0f; } ConvexMesh::ConvexMesh(MeshFactory* factory) : PxConvexMesh (PxConcreteType::eCONVEX_MESH, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mNb (0), mSdfData (NULL), mBigConvexData (NULL), mMass (0), mInertia (PxMat33(PxIdentity)), mMeshFactory (factory) { initConvexHullData(mHullData); } ConvexMesh::ConvexMesh(MeshFactory* factory, ConvexHullInitData& data) : PxConvexMesh (PxConcreteType::eCONVEX_MESH, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mNb (data.mNb), mSdfData (data.mSdfData), mBigConvexData (data.mBigConvexData), mMass (data.mMass), mInertia (data.mInertia), mMeshFactory (factory) { mHullData = data.mHullData; // this constructor takes ownership of memory from the data object data.mSdfData = NULL; data.mBigConvexData = NULL; } ConvexMesh::~ConvexMesh() { if(getBaseFlags()&PxBaseFlag::eOWNS_MEMORY) { PX_FREE(mHullData.mPolygons); PX_DELETE(mBigConvexData); PX_DELETE(mSdfData); } } bool ConvexMesh::isGpuCompatible() const { return mHullData.mNbHullVertices <= 64 && mHullData.mNbPolygons <= 64 && mHullData.mPolygons[0].mNbVerts <= 32 && mHullData.mNbEdges.isBitSet() && mHullData.checkExtentRadiusRatio(); } void ConvexMesh::exportExtraData(PxSerializationContext& context) { context.alignData(PX_SERIAL_ALIGN); const PxU32 bufferSize = computeBufferSize(mHullData, getNb()); context.writeData(mHullData.mPolygons, bufferSize); if (mSdfData) { context.alignData(PX_SERIAL_ALIGN); context.writeData(mSdfData, sizeof(SDF)); mSdfData->exportExtraData(context); } if(mBigConvexData) { context.alignData(PX_SERIAL_ALIGN); context.writeData(mBigConvexData, sizeof(BigConvexData)); mBigConvexData->exportExtraData(context); } } void ConvexMesh::importExtraData(PxDeserializationContext& context) { const PxU32 bufferSize = computeBufferSize(mHullData, getNb()); mHullData.mPolygons = reinterpret_cast<HullPolygonData*>(context.readExtraData<PxU8, PX_SERIAL_ALIGN>(bufferSize)); if (mSdfData) { mSdfData = context.readExtraData<SDF, PX_SERIAL_ALIGN>(); PX_PLACEMENT_NEW(mSdfData, SDF(PxEmpty)); mSdfData->importExtraData(context); } if(mBigConvexData) { mBigConvexData = context.readExtraData<BigConvexData, PX_SERIAL_ALIGN>(); PX_PLACEMENT_NEW(mBigConvexData, BigConvexData(PxEmpty)); mBigConvexData->importExtraData(context); mHullData.mBigConvexRawData = &mBigConvexData->mData; } } ConvexMesh* ConvexMesh::createObject(PxU8*& address, PxDeserializationContext& context) { ConvexMesh* obj = PX_PLACEMENT_NEW(address, ConvexMesh(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(ConvexMesh); obj->importExtraData(context); obj->resolveReferences(context); return obj; } static bool convexHullLoad(ConvexHullData& data, PxInputStream& stream, PxBitAndDword& bufferSize) { PxU32 version; bool Mismatch; if(!ReadHeader('C', 'L', 'H', 'L', version, Mismatch, stream)) return false; if(version<=8) { if(!ReadHeader('C', 'V', 'H', 'L', version, Mismatch, stream)) return false; } PxU32 Nb; // Import figures { PxU32 tmp[4]; ReadDwordBuffer(tmp, 4, Mismatch, stream); data.mNbHullVertices = PxTo8(tmp[0]); data.mNbEdges = PxTo16(tmp[1]); data.mNbPolygons = PxTo8(tmp[2]); Nb = tmp[3]; } //AM: In practice the old aligner approach wastes 20 bytes and there is no reason to 20 byte align this data. //I changed the code to just 4 align for the time being. //On consoles if anything we will need to make this stuff 16 byte align vectors to have any sense, which will have to be done by padding data structures. PX_ASSERT(sizeof(HullPolygonData) % sizeof(PxReal) == 0); //otherwise please pad it. PX_ASSERT(sizeof(PxVec3) % sizeof(PxReal) == 0); PxU32 bytesNeeded = computeBufferSize(data, Nb); PX_FREE(data.mPolygons); // Load() can be called for an existing convex mesh. In that case we need to free the memory first. bufferSize = Nb; void* mDataMemory = PX_ALLOC(bytesNeeded, "ConvexHullData data"); PxU8* address = reinterpret_cast<PxU8*>(mDataMemory); PX_ASSERT(address); data.mPolygons = reinterpret_cast<HullPolygonData*>(address); address += sizeof(HullPolygonData) * data.mNbPolygons; PxVec3* mDataHullVertices = reinterpret_cast<PxVec3*>(address); address += sizeof(PxVec3) * data.mNbHullVertices; PxU8* mDataFacesByEdges8 = address; address += sizeof(PxU8) * data.mNbEdges * 2; PxU8* mDataFacesByVertices8 = address; address += sizeof(PxU8) * data.mNbHullVertices * 3; PxU16* mEdges = reinterpret_cast<PxU16*>(address); address += data.mNbEdges.isBitSet() ? (sizeof(PxU16) * data.mNbEdges * 2) : 0; PxU8* mDataVertexData8 = address; address += sizeof(PxU8) * Nb; // PT: leave that one last, so that we don't need to serialize "Nb" PX_ASSERT(!(size_t(mDataHullVertices) % sizeof(PxReal))); PX_ASSERT(!(size_t(data.mPolygons) % sizeof(PxReal))); PX_ASSERT(size_t(address)<=size_t(mDataMemory)+bytesNeeded); // Import vertices readFloatBuffer(&mDataHullVertices->x, PxU32(3*data.mNbHullVertices), Mismatch, stream); if(version<=6) { PxU16 useUnquantizedNormals = readWord(Mismatch, stream); PX_UNUSED(useUnquantizedNormals); } // Import polygons stream.read(data.mPolygons, data.mNbPolygons*sizeof(HullPolygonData)); if(Mismatch) { for(PxU32 i=0;i<data.mNbPolygons;i++) flipData(data.mPolygons[i]); } stream.read(mDataVertexData8, Nb); stream.read(mDataFacesByEdges8, PxU32(data.mNbEdges*2)); if(version <= 5) { //KS - we need to compute faces-by-vertices here bool noPlaneShift = false; for(PxU32 i=0; i< data.mNbHullVertices; ++i) { PxU32 count = 0; PxU8 inds[3]; for(PxU32 j=0; j<data.mNbPolygons; ++j) { HullPolygonData& polygon = data.mPolygons[j]; for(PxU32 k=0; k< polygon.mNbVerts; ++k) { PxU8 index = mDataVertexData8[polygon.mVRef8 + k]; if(i == index) { //Found a polygon inds[count++] = PxTo8(j); break; } } if(count == 3) break; } //We have 3 indices //PX_ASSERT(count == 3); //Do something here if(count == 3) { mDataFacesByVertices8[i*3+0] = inds[0]; mDataFacesByVertices8[i*3+1] = inds[1]; mDataFacesByVertices8[i*3+2] = inds[2]; } else { noPlaneShift = true; break; } } if(noPlaneShift) { for(PxU32 a = 0; a < data.mNbHullVertices; ++a) { mDataFacesByVertices8[a*3] = 0xFF; mDataFacesByVertices8[a*3+1] = 0xFF; mDataFacesByVertices8[a*3+2] = 0xFF; } } } else stream.read(mDataFacesByVertices8, PxU32(data.mNbHullVertices * 3)); if (data.mNbEdges.isBitSet()) { if (version <= 7) { for (PxU32 a = 0; a < PxU32(data.mNbEdges * 2); ++a) { mEdges[a] = 0xFFFF; } } else { readWordBuffer(mEdges, PxU32(data.mNbEdges * 2), Mismatch, stream); } } return true; } bool ConvexMesh::load(PxInputStream& stream) { // Import header PxU32 version; bool mismatch; if(!readHeader('C', 'V', 'X', 'M', version, mismatch, stream)) return false; // Check if old (incompatible) mesh format is loaded if (version < PX_CONVEX_VERSION) return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Loading convex mesh failed: Deprecated mesh cooking format."); // Import serialization flags PxU32 serialFlags = readDword(mismatch, stream); PX_UNUSED(serialFlags); if(!convexHullLoad(mHullData, stream, mNb)) return false; // Import local bounds float tmp[8]; readFloatBuffer(tmp, 8, mismatch, stream); // geomEpsilon = tmp[0]; mHullData.mAABB = PxBounds3(PxVec3(tmp[1], tmp[2], tmp[3]), PxVec3(tmp[4],tmp[5],tmp[6])); // Import mass info mMass = tmp[7]; if(mMass!=-1.0f) { readFloatBuffer(&mInertia(0,0), 9, mismatch, stream); readFloatBuffer(&mHullData.mCenterOfMass.x, 3, mismatch, stream); } // Import gaussmaps PxF32 gaussMapFlag = readFloat(mismatch, stream); if(gaussMapFlag != -1.0f) { PX_ASSERT(gaussMapFlag == 1.0f); //otherwise file is corrupt PX_DELETE(mBigConvexData); PX_NEW_SERIALIZED(mBigConvexData, BigConvexData); if(mBigConvexData) { mBigConvexData->Load(stream); mHullData.mBigConvexRawData = &mBigConvexData->mData; } } //Import Sdf data PxF32 sdfFlag = readFloat(mismatch, stream); if (sdfFlag != -1.0f) { PX_ASSERT(sdfFlag == 1.0f); //otherwise file is corrupt PX_DELETE(mSdfData); PX_NEW_SERIALIZED(mSdfData, SDF); if (mSdfData) { // Import sdf values mSdfData->mMeshLower.x = readFloat(mismatch, stream); mSdfData->mMeshLower.y = readFloat(mismatch, stream); mSdfData->mMeshLower.z = readFloat(mismatch, stream); mSdfData->mSpacing = readFloat(mismatch, stream); mSdfData->mDims.x = readDword(mismatch, stream); mSdfData->mDims.y = readDword(mismatch, stream); mSdfData->mDims.z = readDword(mismatch, stream); mSdfData->mNumSdfs = readDword(mismatch, stream); mSdfData->mNumSubgridSdfs = readDword(mismatch, stream); mSdfData->mNumStartSlots = readDword(mismatch, stream); mSdfData->mSubgridSize = readDword(mismatch, stream); mSdfData->mSdfSubgrids3DTexBlockDim.x = readDword(mismatch, stream); mSdfData->mSdfSubgrids3DTexBlockDim.y = readDword(mismatch, stream); mSdfData->mSdfSubgrids3DTexBlockDim.z = readDword(mismatch, stream); mSdfData->mSubgridsMinSdfValue = readFloat(mismatch, stream); mSdfData->mSubgridsMaxSdfValue = readFloat(mismatch, stream); mSdfData->mBytesPerSparsePixel = readDword(mismatch, stream); //allocate sdf mSdfData->allocateSdfs(mSdfData->mMeshLower, mSdfData->mSpacing, mSdfData->mDims.x, mSdfData->mDims.y, mSdfData->mDims.z, mSdfData->mSubgridSize, mSdfData->mSdfSubgrids3DTexBlockDim.x, mSdfData->mSdfSubgrids3DTexBlockDim.y, mSdfData->mSdfSubgrids3DTexBlockDim.z, mSdfData->mSubgridsMinSdfValue, mSdfData->mSubgridsMaxSdfValue, mSdfData->mBytesPerSparsePixel); readFloatBuffer(mSdfData->mSdf, mSdfData->mNumSdfs, mismatch, stream); readByteBuffer(mSdfData->mSubgridSdf, mSdfData->mNumSubgridSdfs, stream); readIntBuffer(mSdfData->mSubgridStartSlots, mSdfData->mNumStartSlots, mismatch, stream); mHullData.mSdfData = mSdfData; } } /* printf("\n\n"); printf("COM: %f %f %f\n", massInfo.centerOfMass.x, massInfo.centerOfMass.y, massInfo.centerOfMass.z); printf("BND: %f %f %f\n", mHullData.aabb.getCenter().x, mHullData.aabb.getCenter().y, mHullData.aabb.getCenter().z); printf("CNT: %f %f %f\n", mHullData.mCenterxx.x, mHullData.mCenterxx.y, mHullData.mCenterxx.z); printf("COM-BND: %f BND-CNT: %f, CNT-COM: %f\n", (massInfo.centerOfMass - mHullData.aabb.getCenter()).magnitude(), (mHullData.aabb.getCenter() - mHullData.mCenterxx).magnitude(), (mHullData.mCenterxx - massInfo.centerOfMass).magnitude()); */ // TEST_INTERNAL_OBJECTS readFloatBuffer(&mHullData.mInternal.mRadius, 4, mismatch, stream); PX_ASSERT(PxVec3(mHullData.mInternal.mExtents[0], mHullData.mInternal.mExtents[1], mHullData.mInternal.mExtents[2]).isFinite()); PX_ASSERT(mHullData.mInternal.mExtents[0] != 0.0f); PX_ASSERT(mHullData.mInternal.mExtents[1] != 0.0f); PX_ASSERT(mHullData.mInternal.mExtents[2] != 0.0f); //~TEST_INTERNAL_OBJECTS return true; } void ConvexMesh::release() { RefCountable_decRefCount(*this); } void ConvexMesh::onRefCountZero() { // when the mesh failed to load properly, it will not have been added to the convex array ::onRefCountZero(this, mMeshFactory, !getBufferSize(), "PxConvexMesh::release: double deletion detected!"); } void ConvexMesh::acquireReference() { RefCountable_incRefCount(*this); } PxU32 ConvexMesh::getReferenceCount() const { return RefCountable_getRefCount(*this); } void ConvexMesh::getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const { mass = ConvexMesh::getMass(); localInertia = ConvexMesh::getInertia(); localCenterOfMass = ConvexMesh::getHull().mCenterOfMass; } PxBounds3 ConvexMesh::getLocalBounds() const { PX_ASSERT(mHullData.mAABB.isValid()); return PxBounds3::centerExtents(mHullData.mAABB.mCenter, mHullData.mAABB.mExtents); } const PxReal* ConvexMesh::getSDF() const { if(mSdfData) return mSdfData->mSdf; return NULL; }
14,811
C++
30.717345
239
0.722841
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuShapeConvex.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 "GuShapeConvex.h" #include "GuBigConvexData.h" #include "GuEdgeList.h" #include "GuInternal.h" #include "foundation/PxMat34.h" #include "GuHillClimbing.h" #include "foundation/PxFPU.h" using namespace physx; using namespace Gu; static PX_FORCE_INLINE PxU32 selectClosestPolygon(PxReal& maxDp_, PxU32 numPolygons, const Gu::HullPolygonData* polys, const PxVec3& axis) { float maxDp = polys[0].mPlane.n.dot(axis); PxU32 closest = 0; // Loop through polygons for(PxU32 i=1; i <numPolygons; i++) { // Catch current polygon and test its plane const PxReal dp = polys[i].mPlane.n.dot(axis); if(dp>maxDp) { maxDp = dp; closest = i; } } maxDp_ = maxDp; return closest; } static PxU32 SelectClosestEdgeCB_Convex(const PolygonalData& data, const Cm::FastVertex2ShapeScaling& scaling, const PxVec3& localSpaceDirection) { //vertex1TOShape1Skew is a symmetric matrix. //it has the property that (vertex1TOShape1Skew * v)|localSpaceDirection == (vertex1TOShape1Skew * localSpaceDirection)|v const PxVec3 vertexSpaceDirection = scaling * localSpaceDirection; const Gu::HullPolygonData* PX_RESTRICT polys = data.mPolygons; PxReal maxDp; // ##might not be needed PxU32 closest = ::selectClosestPolygon(maxDp, data.mNbPolygons, polys, vertexSpaceDirection); // Since the convex is closed, at least some poly must satisfy this PX_ASSERT(maxDp>=0); const PxU32 numEdges = data.mNbEdges; const PxU8* const edgeToFace = data.mFacesByEdges; //Loop through edges PxU32 closestEdge = 0xffffffff; PxReal maxDpSq = maxDp * maxDp; for(PxU32 i=0; i < numEdges; i++) { const PxU8 f0 = edgeToFace[i*2]; const PxU8 f1 = edgeToFace[i*2+1]; // unnormalized edge normal const PxVec3 edgeNormal = polys[f0].mPlane.n + polys[f1].mPlane.n; const PxReal enMagSq = edgeNormal.magnitudeSquared(); //Test normal of current edge - squared test is valid if dp and maxDp both >= 0 const float dp = edgeNormal.dot(vertexSpaceDirection); if(dp>=0.0f && dp*dp>maxDpSq*enMagSq) { maxDpSq = dp*dp/enMagSq; closestEdge = i; } } if(closestEdge!=0xffffffff) { const PxU8* FBE = edgeToFace; const PxU32 f0 = FBE[closestEdge*2]; const PxU32 f1 = FBE[closestEdge*2+1]; const PxReal dp0 = polys[f0].mPlane.n.dot(vertexSpaceDirection); const PxReal dp1 = polys[f1].mPlane.n.dot(vertexSpaceDirection); if(dp0>dp1) closest = f0; else closest = f1; } return closest; } // Hull projection callback for "small" hulls static void HullProjectionCB_SmallConvex(const PolygonalData& data, const PxVec3& dir, const PxMat34& world, const Cm::FastVertex2ShapeScaling& scaling, PxReal& min, PxReal& max) { const PxVec3 localSpaceDirection = world.rotateTranspose(dir); //vertex1TOShape1Skew is a symmetric matrix. //it has the property that (vertex1TOShape1Skew * v)|localSpaceDirection == (vertex1TOShape1Skew * localSpaceDirection)|v const PxVec3 vertexSpaceDirection = scaling * localSpaceDirection; // PT: prevents aliasing PxReal minimum = PX_MAX_REAL; PxReal maximum = -PX_MAX_REAL; //brute-force, localspace { const PxVec3* PX_RESTRICT verts = data.mVerts; PxU32 numVerts = data.mNbVerts; while(numVerts--) { const PxReal dp = (*verts++).dot(vertexSpaceDirection); minimum = physx::intrinsics::selectMin(minimum, dp); maximum = physx::intrinsics::selectMax(maximum, dp); } } const PxReal offset = world.p.dot(dir); min = minimum + offset; max = maximum + offset; } static PxU32 computeNearestOffset(const PxU32 subdiv, const PxVec3& dir) { // ComputeCubemapNearestOffset(const Point& dir, udword subdiv) // PT: ok so why exactly was the code duplicated here? // PxU32 CI = CubemapLookup(dir,u,v) PxU32 index; PxReal coeff; // find largest axis PxReal absNx = PxAbs(dir.x); PxReal absNy = PxAbs(dir.y); PxReal absNz = PxAbs(dir.z); if( absNy > absNx && absNy > absNz) { //y biggest index = 1; coeff = 1.0f/absNy; } else if(absNz > absNx) { index = 2; coeff = 1.0f/absNz; } else { index = 0; coeff = 1.0f/absNx; } union { PxU32 aU32; PxReal aFloat; } conv; conv.aFloat = dir[index]; PxU32 sign = conv.aU32>>31; const PxU32 index2 = PxGetNextIndex3(index); const PxU32 index3 = PxGetNextIndex3(index2); PxReal u = dir[index2] * coeff; PxReal v = dir[index3] * coeff; PxU32 CI = (sign | (index+index)); //Remap to [0, subdiv[ coeff = 0.5f * PxReal(subdiv-1); u += 1.0f; u *= coeff; v += 1.0f; v *= coeff; //Round to nearest PxU32 ui = PxU32(u); PxU32 vi = PxU32(v); PxReal du = u - PxReal(ui); PxReal dv = v - PxReal(vi); if(du>0.5f) ui++; if(dv>0.5f) vi++; //Compute offset return CI*(subdiv*subdiv) + ui*subdiv + vi; } // Hull projection callback for "big" hulls static void HullProjectionCB_BigConvex(const PolygonalData& data, const PxVec3& dir, const PxMat34& world, const Cm::FastVertex2ShapeScaling& scaling, PxReal& minimum, PxReal& maximum) { const PxVec3* PX_RESTRICT verts = data.mVerts; const PxVec3 localSpaceDirection = world.rotateTranspose(dir); //vertex1TOShape1Skew is a symmetric matrix. //it has the property that (vertex1TOShape1Skew * v)|localSpaceDirection == (vertex1TOShape1Skew * localSpaceDirection)|v const PxVec3 vertexSpaceDirection = scaling * localSpaceDirection; //NB: triangles are always shape 1! eek! // This version is better for objects with a lot of vertices const Gu::BigConvexRawData* bigData = data.mBigData; PxU32 minID = 0, maxID = 0; { const PxU32 offset = computeNearestOffset(bigData->mSubdiv, -vertexSpaceDirection); minID = bigData->mSamples[offset]; maxID = bigData->getSamples2()[offset]; } // Do hillclimbing! localSearch(minID, -vertexSpaceDirection, verts, bigData); localSearch(maxID, vertexSpaceDirection, verts, bigData); const PxReal offset = world.p.dot(dir); minimum = offset + verts[minID].dot(vertexSpaceDirection); maximum = offset + verts[maxID].dot(vertexSpaceDirection); PX_ASSERT(maximum >= minimum); } void Gu::getPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const Gu::ConvexHullData* PX_RESTRICT src, const Cm::FastVertex2ShapeScaling& scaling) { dst->mCenter = scaling * src->mCenterOfMass; dst->mNbVerts = src->mNbHullVertices; dst->mNbPolygons = src->mNbPolygons; dst->mNbEdges = src->mNbEdges; dst->mPolygons = src->mPolygons; dst->mVerts = src->getHullVertices(); dst->mPolygonVertexRefs = src->getVertexData8(); dst->mFacesByEdges = src->getFacesByEdges8(); // TEST_INTERNAL_OBJECTS dst->mInternal = src->mInternal; //~TEST_INTERNAL_OBJECTS dst->mBigData = src->mBigConvexRawData; // This threshold test doesnt cost much and many customers cook on PC and use this on 360. // 360 has a much higher threshold than PC(and it makes a big difference) // PT: the cool thing is that this test is now done once by contact generation call, not once by hull projection if(!src->mBigConvexRawData) dst->mProjectHull = HullProjectionCB_SmallConvex; else dst->mProjectHull = HullProjectionCB_BigConvex; dst->mSelectClosestEdgeCB = SelectClosestEdgeCB_Convex; } // Box emulating convex mesh // Face0: 0-1-2-3 // Face1: 1-5-6-2 // Face2: 5-4-7-6 // Face3: 4-0-3-7 // Face4; 3-2-6-7 // Face5: 4-5-1-0 // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ static const PxU8 gPxcBoxPolygonData[] = { 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 4, 5, 1, 0, }; #define INVSQRT2 0.707106781188f //!< 1 / sqrt(2) static PxVec3 gPxcBoxEdgeNormals[] = { PxVec3(0, -INVSQRT2, -INVSQRT2), // 0-1 PxVec3(INVSQRT2, 0, -INVSQRT2), // 1-2 PxVec3(0, INVSQRT2, -INVSQRT2), // 2-3 PxVec3(-INVSQRT2, 0, -INVSQRT2), // 3-0 PxVec3(0, INVSQRT2, INVSQRT2), // 7-6 PxVec3(INVSQRT2, 0, INVSQRT2), // 6-5 PxVec3(0, -INVSQRT2, INVSQRT2), // 5-4 PxVec3(-INVSQRT2, 0, INVSQRT2), // 4-7 PxVec3(INVSQRT2, -INVSQRT2, 0), // 1-5 PxVec3(INVSQRT2, INVSQRT2, 0), // 6-2 PxVec3(-INVSQRT2, INVSQRT2, 0), // 3-7 PxVec3(-INVSQRT2, -INVSQRT2, 0) // 4-0 }; #undef INVSQRT2 // ### needs serious checkings // Flags(16), Count(16), Offset(32); static Gu::EdgeDescData gPxcBoxEdgeDesc[] = { {Gu::PX_EDGE_ACTIVE, 2, 0}, {Gu::PX_EDGE_ACTIVE, 2, 2}, {Gu::PX_EDGE_ACTIVE, 2, 4}, {Gu::PX_EDGE_ACTIVE, 2, 6}, {Gu::PX_EDGE_ACTIVE, 2, 8}, {Gu::PX_EDGE_ACTIVE, 2, 10}, {Gu::PX_EDGE_ACTIVE, 2, 12}, {Gu::PX_EDGE_ACTIVE, 2, 14}, {Gu::PX_EDGE_ACTIVE, 2, 16}, {Gu::PX_EDGE_ACTIVE, 2, 18}, {Gu::PX_EDGE_ACTIVE, 2, 20}, {Gu::PX_EDGE_ACTIVE, 2, 22}, }; // ### needs serious checkings static PxU8 gPxcBoxFaceByEdge[] = { 0,5, // Edge 0-1 0,1, // Edge 1-2 0,4, // Edge 2-3 0,3, // Edge 3-0 2,4, // Edge 7-6 1,2, // Edge 6-5 2,5, // Edge 5-4 2,3, // Edge 4-7 1,5, // Edge 1-5 1,4, // Edge 6-2 3,4, // Edge 3-7 3,5, // Edge 4-0 }; static PxU32 SelectClosestEdgeCB_Box(const PolygonalData& data, const Cm::FastVertex2ShapeScaling& scaling, const PxVec3& localDirection) { PX_UNUSED(scaling); PxReal maxDp; // ##might not be needed PxU32 closest = ::selectClosestPolygon(maxDp, 6, data.mPolygons, localDirection); PxU32 numEdges = 12; const PxVec3* PX_RESTRICT edgeNormals = gPxcBoxEdgeNormals; //Loop through edges PxU32 closestEdge = 0xffffffff; for(PxU32 i=0; i < numEdges; i++) { //Test normal of current edge const float dp = edgeNormals[i].dot(localDirection); if(dp>maxDp) { maxDp = dp; closestEdge = i; } } if(closestEdge!=0xffffffff) { const Gu::EdgeDescData* PX_RESTRICT ED = gPxcBoxEdgeDesc; const PxU8* PX_RESTRICT FBE = gPxcBoxFaceByEdge; PX_ASSERT(ED[closestEdge].Count==2); const PxU32 f0 = FBE[ED[closestEdge].Offset]; const PxU32 f1 = FBE[ED[closestEdge].Offset+1]; const PxReal dp0 = data.mPolygons[f0].mPlane.n.dot(localDirection); const PxReal dp1 = data.mPolygons[f1].mPlane.n.dot(localDirection); if(dp0>dp1) closest = f0; else closest = f1; } return closest; } static PX_FORCE_INLINE void projectBox(PxVec3& p, const PxVec3& localDir, const PxVec3& extents) { // PT: the original code didn't have branches or FPU comparisons. Why rewrite it ? // p.x = (localDir.x >= 0) ? extents.x : -extents.x; // p.y = (localDir.y >= 0) ? extents.y : -extents.y; // p.z = (localDir.z >= 0) ? extents.z : -extents.z; p.x = physx::intrinsics::fsel(localDir.x, extents.x, -extents.x); p.y = physx::intrinsics::fsel(localDir.y, extents.y, -extents.y); p.z = physx::intrinsics::fsel(localDir.z, extents.z, -extents.z); } static void HullProjectionCB_Box(const PolygonalData& data, const PxVec3& dir, const PxMat34& world, const Cm::FastVertex2ShapeScaling& scaling, PxReal& minimum, PxReal& maximum) { PX_UNUSED(scaling); const PxVec3 localDir = world.rotateTranspose(dir); PxVec3 p; projectBox(p, localDir, *data.mHalfSide); const PxReal offset = world.p.dot(dir); const PxReal tmp = p.dot(localDir); maximum = offset + tmp; minimum = offset - tmp; } PolygonalBox::PolygonalBox(const PxVec3& halfSide) : mHalfSide(halfSide) { //Precompute the convex data // 7+------+6 0 = --- // /| /| 1 = +-- // / | / | 2 = ++- // / 4+---/--+5 3 = -+- // 3+------+2 / y z 4 = --+ // | / | / | / 5 = +-+ // |/ |/ |/ 6 = +++ // 0+------+1 *---x 7 = -++ PxVec3 minimum = -mHalfSide; PxVec3 maximum = mHalfSide; // Generate 8 corners of the bbox mVertices[0] = PxVec3(minimum.x, minimum.y, minimum.z); mVertices[1] = PxVec3(maximum.x, minimum.y, minimum.z); mVertices[2] = PxVec3(maximum.x, maximum.y, minimum.z); mVertices[3] = PxVec3(minimum.x, maximum.y, minimum.z); mVertices[4] = PxVec3(minimum.x, minimum.y, maximum.z); mVertices[5] = PxVec3(maximum.x, minimum.y, maximum.z); mVertices[6] = PxVec3(maximum.x, maximum.y, maximum.z); mVertices[7] = PxVec3(minimum.x, maximum.y, maximum.z); //Setup the polygons for(PxU8 i=0; i < 6; i++) { mPolygons[i].mNbVerts = 4; mPolygons[i].mVRef8 = PxU16(i*4); } // ### planes needs *very* careful checks // X axis mPolygons[1].mPlane.n = PxVec3(1.0f, 0.0f, 0.0f); mPolygons[1].mPlane.d = -mHalfSide.x; mPolygons[3].mPlane.n = PxVec3(-1.0f, 0.0f, 0.0f); mPolygons[3].mPlane.d = -mHalfSide.x; mPolygons[1].mMinIndex = 0; mPolygons[3].mMinIndex = 1; // mPolygons[1].mMinObsolete = -mHalfSide.x; // mPolygons[3].mMinObsolete = -mHalfSide.x; PX_ASSERT(mPolygons[1].getMin(mVertices) == -mHalfSide.x); PX_ASSERT(mPolygons[3].getMin(mVertices) == -mHalfSide.x); // Y axis mPolygons[4].mPlane.n = PxVec3(0.f, 1.0f, 0.0f); mPolygons[4].mPlane.d = -mHalfSide.y; mPolygons[5].mPlane.n = PxVec3(0.0f, -1.0f, 0.0f); mPolygons[5].mPlane.d = -mHalfSide.y; mPolygons[4].mMinIndex = 0; mPolygons[5].mMinIndex = 2; // mPolygons[4].mMinObsolete = -mHalfSide.y; // mPolygons[5].mMinObsolete = -mHalfSide.y; PX_ASSERT(mPolygons[4].getMin(mVertices) == -mHalfSide.y); PX_ASSERT(mPolygons[5].getMin(mVertices) == -mHalfSide.y); // Z axis mPolygons[2].mPlane.n = PxVec3(0.f, 0.0f, 1.0f); mPolygons[2].mPlane.d = -mHalfSide.z; mPolygons[0].mPlane.n = PxVec3(0.0f, 0.0f, -1.0f); mPolygons[0].mPlane.d = -mHalfSide.z; mPolygons[2].mMinIndex = 0; mPolygons[0].mMinIndex = 4; // mPolygons[2].mMinObsolete = -mHalfSide.z; // mPolygons[0].mMinObsolete = -mHalfSide.z; PX_ASSERT(mPolygons[2].getMin(mVertices) == -mHalfSide.z); PX_ASSERT(mPolygons[0].getMin(mVertices) == -mHalfSide.z); } void PolygonalBox::getPolygonalData(PolygonalData* PX_RESTRICT dst) const { dst->mCenter = PxVec3(0.0f, 0.0f, 0.0f); dst->mNbVerts = 8; dst->mNbPolygons = 6; dst->mPolygons = mPolygons; dst->mNbEdges = 0; dst->mVerts = mVertices; dst->mPolygonVertexRefs = gPxcBoxPolygonData; dst->mFacesByEdges = NULL; dst->mInternal.mRadius = 0.0f; dst->mInternal.mExtents[0] = 0.0f; dst->mInternal.mExtents[1] = 0.0f; dst->mInternal.mExtents[2] = 0.0f; // dst->mBigData = NULL; dst->mHalfSide = &mHalfSide; dst->mProjectHull = HullProjectionCB_Box; dst->mSelectClosestEdgeCB = SelectClosestEdgeCB_Box; }
15,899
C++
29.813953
184
0.678596
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexMesh.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEX_MESH_H #define GU_CONVEX_MESH_H #include "foundation/PxBitAndData.h" #include "common/PxMetaData.h" #include "geometry/PxConvexMesh.h" #include "geometry/PxConvexMeshGeometry.h" #include "foundation/PxUserAllocated.h" #include "CmRefCountable.h" #include "common/PxRenderOutput.h" #include "GuConvexMeshData.h" namespace physx { class BigConvexData; namespace Gu { class MeshFactory; struct HullPolygonData; PX_INLINE PxU32 computeBufferSize(const Gu::ConvexHullData& data, PxU32 nb) { PxU32 bytesNeeded = sizeof(Gu::HullPolygonData) * data.mNbPolygons; bytesNeeded += sizeof(PxVec3) * data.mNbHullVertices; bytesNeeded += sizeof(PxU8) * data.mNbEdges * 2; // mFacesByEdges8 bytesNeeded += sizeof(PxU8) * data.mNbHullVertices * 3; // mFacesByVertices8; bytesNeeded += data.mNbEdges.isBitSet() ? (sizeof(PxU16) * data.mNbEdges * 2) : 0; // mEdges; bytesNeeded += sizeof(PxU8) * nb; // mVertexData8 //4 align the whole thing! const PxU32 mod = bytesNeeded % sizeof(PxReal); if (mod) bytesNeeded += sizeof(PxReal) - mod; return bytesNeeded; } struct ConvexHullInitData { ConvexHullData mHullData; PxU32 mNb; PxReal mMass; PxMat33 mInertia; BigConvexData* mBigConvexData; SDF* mSdfData; }; // 0: includes raycast map // 1: discarded raycast map // 2: support map not always there // 3: support stackless trees for non-recursive collision queries // 4: no more opcode model // 5: valencies table and gauss map combined, only exported over a vertex count treshold that depends on the platform cooked for. // 6: removed support for edgeData16. // 7: removed support for edge8Data. // 8: removed support for triangles. // 9: removed local sphere. //10: removed geometric center. //11: removed mFlags, and mERef16 from Poly; nbVerts is just a byte. //12: removed explicit minimum, maximum from Poly //13: internal objects //14: SDF #define PX_CONVEX_VERSION 14 class ConvexMesh : public PxConvexMesh, public PxUserAllocated { public: // PX_SERIALIZATION ConvexMesh(PxBaseFlags baseFlags) : PxConvexMesh(baseFlags), mHullData(PxEmpty), mNb(PxEmpty) { mNb.setBit(); } void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } virtual void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); PX_PHYSX_COMMON_API static ConvexMesh* createObject(PxU8*& address, PxDeserializationContext& context); PX_PHYSX_COMMON_API static void getBinaryMetaData(PxOutputStream& stream); void resolveReferences(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&){} //~PX_SERIALIZATION ConvexMesh(MeshFactory* factory); ConvexMesh(MeshFactory* factory, ConvexHullInitData& data); bool load(PxInputStream& stream); // PxBase virtual void onRefCountZero(); //~PxBase // PxRefCounted virtual PxU32 getReferenceCount() const; virtual void acquireReference(); //~PxRefCounted // PxConvexMesh virtual void release(); virtual PxU32 getNbVertices() const { return mHullData.mNbHullVertices; } virtual const PxVec3* getVertices() const { return mHullData.getHullVertices(); } virtual const PxU8* getIndexBuffer() const { return mHullData.getVertexData8(); } virtual PxU32 getNbPolygons() const { return mHullData.mNbPolygons; } virtual bool getPolygonData(PxU32 i, PxHullPolygon& data) const; virtual bool isGpuCompatible() const; virtual void getMassInformation(PxReal& mass, PxMat33& localInertia, PxVec3& localCenterOfMass) const; virtual PxBounds3 getLocalBounds() const; virtual const PxReal* getSDF() const; //~PxConvexMesh PX_FORCE_INLINE PxU32 getNbVerts() const { return mHullData.mNbHullVertices; } PX_FORCE_INLINE const PxVec3* getVerts() const { return mHullData.getHullVertices(); } PX_FORCE_INLINE PxU32 getNbPolygonsFast() const { return mHullData.mNbPolygons; } PX_FORCE_INLINE const HullPolygonData& getPolygon(PxU32 i) const { return mHullData.mPolygons[i]; } PX_FORCE_INLINE const HullPolygonData* getPolygons() const { return mHullData.mPolygons; } PX_FORCE_INLINE PxU32 getNbEdges() const { return mHullData.mNbEdges; } PX_FORCE_INLINE const ConvexHullData& getHull() const { return mHullData; } PX_FORCE_INLINE ConvexHullData& getHull() { return mHullData; } PX_FORCE_INLINE const CenterExtents& getLocalBoundsFast() const { return mHullData.mAABB; } PX_FORCE_INLINE PxReal getMass() const { return mMass; } PX_FORCE_INLINE void setMass(PxReal mass) { mMass = mass; } PX_FORCE_INLINE const PxMat33& getInertia() const { return mInertia; } PX_FORCE_INLINE void setInertia(const PxMat33& inertia) { mInertia = inertia; } PX_FORCE_INLINE BigConvexData* getBigConvexData() const { return mBigConvexData; } PX_FORCE_INLINE void setBigConvexData(BigConvexData* bcd) { mBigConvexData = bcd; } PX_FORCE_INLINE PxU32 getBufferSize() const { return computeBufferSize(mHullData, getNb()); } virtual ~ConvexMesh(); PX_FORCE_INLINE void setMeshFactory(MeshFactory* f) { mMeshFactory = f; } PX_FORCE_INLINE void setNb(PxU32 nb) { mNb = nb; } protected: ConvexHullData mHullData; PxBitAndDword mNb; // ### PT: added for serialization. Try to remove later? SDF* mSdfData; BigConvexData* mBigConvexData; //!< optional, only for large meshes! PT: redundant with ptr in chull data? Could also be end of other buffer PxReal mMass; //this is mass assuming a unit density that can be scaled by instances! PxMat33 mInertia; //in local space of mesh! private: MeshFactory* mMeshFactory; // PT: changed to pointer for serialization PX_FORCE_INLINE PxU32 getNb() const { return mNb; } PX_FORCE_INLINE PxU32 ownsMemory() const { return PxU32(!mNb.isBitSet()); } }; PX_FORCE_INLINE const Gu::ConvexHullData* _getHullData(const PxConvexMeshGeometry& convexGeom) { return &static_cast<const Gu::ConvexMesh*>(convexGeom.convexMesh)->getHull(); } } // namespace Gu } #endif
8,303
C
42.705263
149
0.69505
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuHillClimbing.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/PxVec3.h" #include "foundation/PxAssert.h" #include "foundation/PxUserAllocated.h" #include "GuHillClimbing.h" #include "GuBigConvexData2.h" namespace physx { void localSearch(PxU32& id, const PxVec3& dir, const PxVec3* verts, const Gu::BigConvexRawData* val) { // WARNING: there is a problem on x86 with a naive version of this code, where truncation // of values from 80 bits to 32 bits as they're stored in memory means that iteratively moving to // an adjacent vertex of greater support can go into an infinite loop. So we use a version which // never visits a vertex twice. Note - this might not be enough for GJK, since local // termination of the support function might not be enough to ensure convergence of GJK itself. // if we got here, we'd better have vertices and valencies PX_ASSERT(verts && val); class TinyBitMap { public: PxU32 m[8]; PX_FORCE_INLINE TinyBitMap() { m[0] = m[1] = m[2] = m[3] = m[4] = m[5] = m[6] = m[7] = 0; } PX_FORCE_INLINE void set(PxU8 v) { m[v>>5] |= 1<<(v&31); } PX_FORCE_INLINE bool get(PxU8 v) const { return (m[v>>5] & 1<<(v&31)) != 0; } }; TinyBitMap visited; const Gu::Valency* Valencies = val->mValencies; const PxU8* Adj = val->mAdjacentVerts; PX_ASSERT(Valencies && Adj); // Get the initial value and the initial vertex float MaxVal = dir.dot(verts[id]); PxU32 NextVtx = id; do { PxU16 NbNeighbors = Valencies[NextVtx].mCount; const PxU8* Run = Adj + Valencies[NextVtx].mOffset; id = NextVtx; while(NbNeighbors--) { const PxU8 Neighbor = *Run++; if(!visited.get(Neighbor)) { visited.set(Neighbor); const float CurVal = dir.dot(verts[Neighbor]); if(CurVal>MaxVal) { MaxVal = CurVal; NextVtx = Neighbor; } } } } while(NextVtx!=id); } }
3,521
C++
36.073684
100
0.714002
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexHelper.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEXHELPER_H #define GU_CONVEXHELPER_H #include "GuShapeConvex.h" namespace physx { class PxConvexMeshGeometry; namespace Gu { /////////////////////////////////////////////////////////////////////////// void getScaledConvex( PxVec3*& scaledVertices, PxU8*& scaledIndices, PxVec3* dstVertices, PxU8* dstIndices, bool idtConvexScale, const PxVec3* srcVerts, const PxU8* srcIndices, PxU32 nbVerts, const Cm::FastVertex2ShapeScaling& convexScaling); // PT: calling this correctly isn't trivial so let's macroize it. At least we limit the damage since it immediately calls a real function. #define GET_SCALEX_CONVEX(scaledVertices, stackIndices, idtScaling, nbVerts, scaling, srcVerts, srcIndices) \ getScaledConvex(scaledVertices, stackIndices, \ idtScaling ? NULL : reinterpret_cast<PxVec3*>(PxAlloca(nbVerts * sizeof(PxVec3))), \ idtScaling ? NULL : reinterpret_cast<PxU8*>(PxAlloca(nbVerts * sizeof(PxU8))), \ idtScaling, srcVerts, srcIndices, nbVerts, scaling); bool getConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData); struct ConvexEdge { PxU8 vref0; PxU8 vref1; PxVec3 normal; // warning: non-unit vector! }; PxU32 findUniqueConvexEdges(PxU32 maxNbEdges, ConvexEdge* PX_RESTRICT edges, PxU32 numPolygons, const Gu::HullPolygonData* PX_RESTRICT polygons, const PxU8* PX_RESTRICT vertexData); } } #endif
3,167
C
47.738461
182
0.743606
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuBigConvexData.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/PxIntrinsics.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxAllocator.h" #include "GuBigConvexData2.h" #include "GuCubeIndex.h" #include "CmUtils.h" #include "CmSerialize.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Gu; using namespace Cm; BigConvexData::BigConvexData() : mVBuffer(NULL) { mData.mSubdiv = 0; mData.mNbSamples = 0; mData.mSamples = NULL; ////// mData.mNbVerts = 0; mData.mNbAdjVerts = 0; mData.mValencies = NULL; mData.mAdjacentVerts = NULL; } BigConvexData::~BigConvexData() { PX_FREE(mData.mSamples); /////////// if(mVBuffer) { PX_FREE(mVBuffer); } else { // Allocated from somewhere else!! PX_FREE(mData.mValencies); PX_FREE(mData.mAdjacentVerts); } } void BigConvexData::CreateOffsets() { // Create offsets (radix style) mData.mValencies[0].mOffset = 0; for(PxU32 i=1;i<mData.mNbVerts;i++) mData.mValencies[i].mOffset = PxU16(mData.mValencies[i-1].mOffset + mData.mValencies[i-1].mCount); } bool BigConvexData::VLoad(PxInputStream& stream) { // Import header PxU32 Version; bool Mismatch; if(!ReadHeader('V', 'A', 'L', 'E', Version, Mismatch, stream)) return false; mData.mNbVerts = readDword(Mismatch, stream); mData.mNbAdjVerts = readDword(Mismatch, stream); PX_FREE(mVBuffer); // PT: align Gu::Valency? const PxU32 numVerts = (mData.mNbVerts+3)&~3; const PxU32 TotalSize = sizeof(Gu::Valency)*numVerts + sizeof(PxU8)*mData.mNbAdjVerts; mVBuffer = PX_ALLOC(TotalSize, "BigConvexData data"); mData.mValencies = reinterpret_cast<Gu::Valency*>(mVBuffer); mData.mAdjacentVerts = (reinterpret_cast<PxU8*>(mVBuffer)) + sizeof(Gu::Valency)*numVerts; PX_ASSERT(0 == (size_t(mData.mAdjacentVerts) & 0xf)); PX_ASSERT(Version==2); { PxU16* temp = reinterpret_cast<PxU16*>(mData.mValencies); PxU32 MaxIndex = readDword(Mismatch, stream); ReadIndices(PxTo16(MaxIndex), mData.mNbVerts, temp, stream, Mismatch); // We transform from: // // |5555|4444|3333|2222|1111|----|----|----|----|----| // // to: // // |5555|4444|4444|2222|3333|----|2222|----|1111|----| // for(PxU32 i=0;i<mData.mNbVerts;i++) mData.mValencies[mData.mNbVerts-i-1].mCount = temp[mData.mNbVerts-i-1]; } stream.read(mData.mAdjacentVerts, mData.mNbAdjVerts); // Recreate offsets CreateOffsets(); return true; } PxU32 BigConvexData::ComputeOffset(const PxVec3& dir) const { return ComputeCubemapOffset(dir, mData.mSubdiv); } PxU32 BigConvexData::ComputeNearestOffset(const PxVec3& dir) const { return ComputeCubemapNearestOffset(dir, mData.mSubdiv); } bool BigConvexData::Load(PxInputStream& stream) { // Import header PxU32 Version; bool Mismatch; if(!ReadHeader('S', 'U', 'P', 'M', Version, Mismatch, stream)) return false; // Load base gaussmap // if(!GaussMap::Load(stream)) return false; // Import header if(!ReadHeader('G', 'A', 'U', 'S', Version, Mismatch, stream)) return false; // Import basic info mData.mSubdiv = PxTo16(readDword(Mismatch, stream)); mData.mNbSamples = PxTo16(readDword(Mismatch, stream)); // Load map data mData.mSamples = reinterpret_cast<PxU8*>(PX_ALLOC(sizeof(PxU8)*mData.mNbSamples*2, "BigConvex Samples Data")); // These byte buffers shouldn't need converting stream.read(mData.mSamples, sizeof(PxU8)*mData.mNbSamples*2); //load the valencies return VLoad(stream); } // PX_SERIALIZATION void BigConvexData::exportExtraData(PxSerializationContext& stream) { if(mData.mSamples) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mData.mSamples, sizeof(PxU8)*mData.mNbSamples*2); } if(mData.mValencies) { stream.alignData(PX_SERIAL_ALIGN); PxU32 numVerts = (mData.mNbVerts+3)&~3; const PxU32 TotalSize = sizeof(Gu::Valency)*numVerts + sizeof(PxU8)*mData.mNbAdjVerts; stream.writeData(mData.mValencies, TotalSize); } } void BigConvexData::importExtraData(PxDeserializationContext& context) { if(mData.mSamples) mData.mSamples = context.readExtraData<PxU8, PX_SERIAL_ALIGN>(PxU32(mData.mNbSamples*2)); if(mData.mValencies) { context.alignExtraData(); PxU32 numVerts = (mData.mNbVerts+3)&~3; mData.mValencies = context.readExtraData<Gu::Valency>(numVerts); mData.mAdjacentVerts = context.readExtraData<PxU8>(mData.mNbAdjVerts); } } //~PX_SERIALIZATION
6,006
C++
28.591133
111
0.727439
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuCubeIndex.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CUBE_INDEX_H #define GU_CUBE_INDEX_H #include "foundation/PxVec3.h" #include "foundation/PxFPU.h" namespace physx { enum CubeIndex { CUBE_RIGHT, CUBE_LEFT, CUBE_TOP, CUBE_BOTTOM, CUBE_FRONT, CUBE_BACK, CUBE_FORCE_DWORD = 0x7fffffff }; /* It's pretty straightforwards in concept (though the execution in hardware is a bit crufty and complex). You use a 3D texture coord to look up a texel in a cube map. First you find which of the axis has the largest value (i.e. X,Y,Z), and then the sign of that axis decides which face you are going to use. Which is why the faces are called +X, -X, +Y, -Y, +Z, -Z - after their principle axis. Then you scale the vector so that the largest value is +/-1. Then use the other two as 2D coords to look up your texel (with a 0.5 scale & offset). For example, vector (0.4, -0.2, -0.5). Largest value is the Z axis, and it's -ve, so we're reading from the -Z map. Scale so that this Z axis is +/-1, and you get the vector (0.8, -0.4, -1.0). So now use the other two values to look up your texel. So we look up texel (0.8, -0.4). The scale & offset move the -1->+1 range into the usual 0->1 UV range, so we actually look up texel (0.9, 0.3). The filtering is extremely complex, especially where three maps meet, but that's a hardware problem :-) */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Cubemap lookup function. * * To transform returned uvs into mapping coordinates : * u += 1.0f; u *= 0.5f; * v += 1.0f; v *= 0.5f; * * \fn CubemapLookup(const PxVec3& direction, float& u, float& v) * \param direction [in] a direction vector * \param u [out] impact coordinate on the unit cube, in [-1,1] * \param v [out] impact coordinate on the unit cube, in [-1,1] * \return cubemap texture index */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PX_INLINE CubeIndex CubemapLookup(const PxVec3& direction, float& u, float& v); PX_INLINE PxU32 ComputeCubemapOffset(const PxVec3& dir, PxU32 subdiv) { float u,v; const CubeIndex CI = CubemapLookup(dir, u, v); // Remap to [0, subdiv[ const float Coeff = 0.5f * float(subdiv-1); u += 1.0f; u *= Coeff; v += 1.0f; v *= Coeff; // Compute offset return PxU32(CI)*(subdiv*subdiv) + PxU32(u)*subdiv + PxU32(v); } PX_INLINE PxU32 ComputeCubemapNearestOffset(const PxVec3& dir, PxU32 subdiv) { float u,v; const CubeIndex CI = CubemapLookup(dir, u, v); // Remap to [0, subdiv] const float Coeff = 0.5f * float(subdiv-1); u += 1.0f; u *= Coeff; v += 1.0f; v *= Coeff; // Compute offset return PxU32(CI)*(subdiv*subdiv) + PxU32(u + 0.5f)*subdiv + PxU32(v + 0.5f); } PX_INLINE CubeIndex CubemapLookup(const PxVec3& direction, float& u, float& v) { const PxU32* binary = reinterpret_cast<const PxU32*>(&direction.x); const PxU32 absPx = binary[0] & ~PX_SIGN_BITMASK; const PxU32 absNy = binary[1] & ~PX_SIGN_BITMASK; const PxU32 absNz = binary[2] & ~PX_SIGN_BITMASK; PxU32 Index1 = 0; //x biggest axis PxU32 Index2 = 1; PxU32 Index3 = 2; if( (absNy > absPx) & (absNy > absNz)) { //y biggest Index2 = 2; Index3 = 0; Index1 = 1; } else if(absNz > absPx) { //z biggest Index2 = 0; Index3 = 1; Index1 = 2; } const PxF32* data = &direction.x; const float Coeff = 1.0f / fabsf(data[Index1]); u = data[Index2] * Coeff; v = data[Index3] * Coeff; const PxU32 Sign = binary[Index1]>>31; return CubeIndex(Sign|(Index1+Index1)); } } #endif
5,523
C
34.87013
200
0.637878
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexMeshData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEX_MESH_DATA_H #define GU_CONVEX_MESH_DATA_H #include "foundation/PxPlane.h" #include "foundation/PxBitAndData.h" #include "foundation/PxIntrinsics.h" #include "GuCenterExtents.h" #include "CmSerialize.h" #include "GuSDF.h" // Data definition namespace physx { namespace Gu { struct BigConvexRawData; struct HullPolygonData { // PT: this structure won't be allocated with PX_NEW because polygons aren't allocated alone (with a dedicated alloc). // Instead they are part of a unique allocation/buffer containing all data for the ConvexHullData class (polygons, followed by // hull vertices, edge data, etc). As a result, ctors for embedded classes like PxPlane won't be called. PxPlane mPlane; //!< Plane equation for this polygon //Could drop 4th elem as it can be computed from any vertex as: d = - p.dot(n); PxU16 mVRef8; //!< Offset of vertex references in hull vertex data (CS: can we assume indices are tightly packed and offsets are ascending?? DrawObjects makes and uses this assumption) PxU8 mNbVerts; //!< Number of vertices/edges in the polygon PxU8 mMinIndex; //!< Index of the polygon vertex that has minimal projection along this plane's normal. PX_FORCE_INLINE PxReal getMin(const PxVec3* PX_RESTRICT hullVertices) const //minimum of projection of the hull along this plane normal { return mPlane.n.dot(hullVertices[mMinIndex]); } PX_FORCE_INLINE PxReal getMax() const { return -mPlane.d; } //maximum of projection of the hull along this plane normal }; PX_FORCE_INLINE void flipData(Gu::HullPolygonData& data) { flip(data.mPlane.n.x); flip(data.mPlane.n.y); flip(data.mPlane.n.z); flip(data.mPlane.d); flip(data.mVRef8); } // PT: if this one breaks, please make sure the 'flipData' function is properly updated. PX_COMPILE_TIME_ASSERT(sizeof(Gu::HullPolygonData) == 20); // TEST_INTERNAL_OBJECTS struct InternalObjectsData { PxReal mRadius; PxReal mExtents[3]; PX_FORCE_INLINE void reset() { mRadius = 0.0f; mExtents[0] = 0.0f; mExtents[1] = 0.0f; mExtents[2] = 0.0f; } }; PX_COMPILE_TIME_ASSERT(sizeof(Gu::InternalObjectsData) == 16); //~TEST_INTERNAL_OBJECTS struct ConvexHullData { // PT: WARNING: bounds must be followed by at least 32bits of data for safe SIMD loading CenterExtents mAABB; //!< bounds TODO: compute this on the fly from first 6 vertices in the vertex array. We'll of course need to sort the most extreme ones to the front. PxVec3 mCenterOfMass; //in local space of mesh! // PT: WARNING: mNbHullVertices *must* appear before mBigConvexRawData for ConvX to be able to do "big raw data" surgery PxBitAndWord mNbEdges; //!<the highest bit indicate whether we have grb data, the other 15 bits indicate the number of edges in this convex hull PxU8 mNbHullVertices; //!< Number of vertices in the convex hull PxU8 mNbPolygons; //!< Number of planar polygons composing the hull HullPolygonData* mPolygons; //!< Array of mNbPolygons structures BigConvexRawData* mBigConvexRawData; //!< Hill climbing data, only for large convexes! else NULL. // SDF data SDF* mSdfData; // TEST_INTERNAL_OBJECTS InternalObjectsData mInternal; //~TEST_INTERNAL_OBJECTS PX_FORCE_INLINE ConvexHullData(const PxEMPTY) : mNbEdges(PxEmpty) { } PX_FORCE_INLINE ConvexHullData() { } PX_FORCE_INLINE const CenterExtentsPadded& getPaddedBounds() const { // PT: see compile-time assert at the end of file return static_cast<const CenterExtentsPadded&>(mAABB); } PX_FORCE_INLINE const PxVec3* getHullVertices() const //!< Convex hull vertices { const char* tmp = reinterpret_cast<const char*>(mPolygons); tmp += sizeof(Gu::HullPolygonData) * mNbPolygons; return reinterpret_cast<const PxVec3*>(tmp); } PX_FORCE_INLINE const PxU8* getFacesByEdges8() const //!< for each edge, gives 2 adjacent polygons; used by convex-convex code to come up with all the convex' edge normals. { const char* tmp = reinterpret_cast<const char*>(mPolygons); tmp += sizeof(Gu::HullPolygonData) * mNbPolygons; tmp += sizeof(PxVec3) * mNbHullVertices; return reinterpret_cast<const PxU8*>(tmp); } PX_FORCE_INLINE const PxU8* getFacesByVertices8() const //!< for each edge, gives 2 adjacent polygons; used by convex-convex code to come up with all the convex' edge normals. { const char* tmp = reinterpret_cast<const char*>(mPolygons); tmp += sizeof(Gu::HullPolygonData) * mNbPolygons; tmp += sizeof(PxVec3) * mNbHullVertices; tmp += sizeof(PxU8) * mNbEdges * 2; return reinterpret_cast<const PxU8*>(tmp); } //If we don't build the convex hull with grb data, we will return NULL pointer PX_FORCE_INLINE const PxU16* getVerticesByEdges16() const //!< Vertex indices indexed by unique edges { if (mNbEdges.isBitSet()) { const char* tmp = reinterpret_cast<const char*>(mPolygons); tmp += sizeof(Gu::HullPolygonData) * mNbPolygons; tmp += sizeof(PxVec3) * mNbHullVertices; tmp += sizeof(PxU8) * mNbEdges * 2; tmp += sizeof(PxU8) * mNbHullVertices * 3; return reinterpret_cast<const PxU16*>(tmp); } return NULL; } PX_FORCE_INLINE const PxU8* getVertexData8() const //!< Vertex indices indexed by hull polygons { const char* tmp = reinterpret_cast<const char*>(mPolygons); tmp += sizeof(Gu::HullPolygonData) * mNbPolygons; tmp += sizeof(PxVec3) * mNbHullVertices; tmp += sizeof(PxU8) * mNbEdges * 2; tmp += sizeof(PxU8) * mNbHullVertices * 3; if (mNbEdges.isBitSet()) tmp += sizeof(PxU16) * mNbEdges * 2; return reinterpret_cast<const PxU8*>(tmp); } PX_FORCE_INLINE bool checkExtentRadiusRatio() const { const PxReal maxR = PxMax(mInternal.mExtents[0], PxMax(mInternal.mExtents[1], mInternal.mExtents[2])); const PxReal minR = mInternal.mRadius; const PxReal ratio = maxR/minR; return ratio < 100.f; } }; #if PX_P64_FAMILY PX_COMPILE_TIME_ASSERT(sizeof(Gu::ConvexHullData) == 80); #else PX_COMPILE_TIME_ASSERT(sizeof(Gu::ConvexHullData) == 68); #endif // PT: 'getPaddedBounds()' is only safe if we make sure the bounds member is followed by at least 32bits of data PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(Gu::ConvexHullData, mCenterOfMass)>=PX_OFFSET_OF(Gu::ConvexHullData, mAABB)+4); } // namespace Gu } //#pragma PX_POP_PACK #endif
8,057
C
37.555024
188
0.723967
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuShapeConvex.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_SHAPECONVEX_H #define GU_SHAPECONVEX_H #include "GuConvexMeshData.h" #include "CmScaling.h" namespace physx { namespace Gu { struct PolygonalData; typedef void (*HullPrefetchCB) (PxU32 numVerts, const PxVec3* PX_RESTRICT verts); typedef void (*HullProjectionCB) (const PolygonalData& data, const PxVec3& dir, const PxMat34& world2hull, const Cm::FastVertex2ShapeScaling& scaling, PxReal& minimum, PxReal& maximum); typedef PxU32 (*SelectClosestEdgeCB) (const PolygonalData& data, const Cm::FastVertex2ShapeScaling& scaling, const PxVec3& localDirection); struct PolygonalData { // Data Gu::InternalObjectsData mInternal; PxMeshScale mScale; PxVec3 mCenter; PxU32 mNbVerts; PxU32 mNbPolygons; PxU32 mNbEdges; const Gu::HullPolygonData* mPolygons; const PxVec3* mVerts; const PxU8* mPolygonVertexRefs; const PxU8* mFacesByEdges; const PxU16* mVerticesByEdges; union { const Gu::BigConvexRawData* mBigData; // Only for big convexes const PxVec3* mHalfSide; // Only for boxes }; // Code HullProjectionCB mProjectHull; SelectClosestEdgeCB mSelectClosestEdgeCB; PX_FORCE_INLINE const PxU8* getPolygonVertexRefs(const Gu::HullPolygonData& poly) const { return mPolygonVertexRefs + poly.mVRef8; } }; #if PX_VC #pragma warning(push) #pragma warning( disable : 4251 ) // class needs to have dll-interface to be used by clients of class #endif class PX_PHYSX_COMMON_API PolygonalBox { public: PolygonalBox(const PxVec3& halfSide); void getPolygonalData(PolygonalData* PX_RESTRICT dst) const; const PxVec3& mHalfSide; PxVec3 mVertices[8]; Gu::HullPolygonData mPolygons[6]; private: PolygonalBox& operator=(const PolygonalBox&); }; #if PX_VC #pragma warning(pop) #endif void getPolygonalData_Convex(PolygonalData* PX_RESTRICT dst, const Gu::ConvexHullData* PX_RESTRICT src, const Cm::FastVertex2ShapeScaling& scaling); } } #endif
3,727
C
35.910891
187
0.738395
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexUtilsInternal.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/PxBounds3.h" #include "geometry/PxConvexMeshGeometry.h" #include "GuConvexUtilsInternal.h" #include "GuBoxConversion.h" #include "GuConvexMesh.h" #include "CmScaling.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; void Gu::computeHullOBB(Box& hullOBB, const PxBounds3& hullAABB, float offset, const PxMat34& convexPose, const PxMat34& meshPose, const FastVertex2ShapeScaling& meshScaling, bool idtScaleMesh) { // transform bounds = mesh space const PxMat34 m0to1 = meshPose.transformTranspose(convexPose); hullOBB.extents = hullAABB.getExtents() + PxVec3(offset); hullOBB.center = m0to1.transform(hullAABB.getCenter()); hullOBB.rot = m0to1.m; if(!idtScaleMesh) meshScaling.transformQueryBounds(hullOBB.center, hullOBB.extents, hullOBB.rot); } void Gu::computeVertexSpaceOBB(Box& dst, const Box& src, const PxTransform& meshPose, const PxMeshScale& meshScale) { // AP scaffold failure in x64 debug in GuConvexUtilsInternal.cpp //PX_ASSERT("Performance warning - this path shouldn't execute for identity mesh scale." && !meshScale.isIdentity()); dst = transform(meshScale.getInverse() * Matrix34FromTransform(meshPose.getInverse()), src); } void Gu::computeOBBAroundConvex( Box& obb, const PxConvexMeshGeometry& convexGeom, const PxConvexMesh* cm, const PxTransform& convexPose) { const CenterExtents& aabb = static_cast<const Gu::ConvexMesh*>(cm)->getLocalBoundsFast(); if(convexGeom.scale.isIdentity()) { const PxMat33Padded m(convexPose.q); obb = Gu::Box(m.transform(aabb.mCenter) + convexPose.p, aabb.mExtents, m); } else { obb = transform(Matrix34FromTransform(convexPose) * toMat33(convexGeom.scale), Box(aabb.mCenter, aabb.mExtents, PxMat33(PxIdentity))); } }
3,474
C++
42.987341
136
0.764824
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexHelper.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/PxUtilities.h" #include "GuConvexHelper.h" #include "GuInternal.h" #include "GuConvexMesh.h" using namespace physx; using namespace Gu; // PT: we can't call alloca in a function and we want to avoid defines or duplicating the code. This makes it a bit tricky to write. void Gu::getScaledConvex( PxVec3*& scaledVertices, PxU8*& scaledIndices, PxVec3* dstVertices, PxU8* dstIndices, bool idtConvexScale, const PxVec3* srcVerts, const PxU8* srcIndices, PxU32 nbVerts, const Cm::FastVertex2ShapeScaling& convexScaling) { //pretransform convex polygon if we have scaling! if(idtConvexScale) // PT: the scale is always 1 for boxes so no need to test the type { scaledVertices = const_cast<PxVec3*>(srcVerts); scaledIndices = const_cast<PxU8*>(srcIndices); } else { scaledIndices = dstIndices; scaledVertices = dstVertices; for(PxU32 i=0; i<nbVerts; i++) { scaledIndices[i] = PxTo8(i); //generate trivial indexing. scaledVertices[i] = convexScaling * srcVerts[srcIndices[i]]; } } } bool Gu::getConvexData(const PxConvexMeshGeometry& shapeConvex, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData) { const bool idtScale = shapeConvex.scale.isIdentity(); if(!idtScale) scaling.init(shapeConvex.scale); // PT: this version removes all the FCMPs and almost all LHS. This is temporary until // the legacy 3x3 matrix totally vanishes but meanwhile do NOT do useless matrix conversions, // it's a perfect recipe for LHS. const ConvexHullData* hullData = _getHullData(shapeConvex); PX_ASSERT(!hullData->mAABB.isEmpty()); bounds = hullData->mAABB.transformFast(scaling.getVertex2ShapeSkew()); getPolygonalData_Convex(&polyData, hullData, scaling); // PT: non-uniform scaling invalidates the "internal objects" optimization, since our internal sphere // might become an ellipsoid or something. Just disable the optimization if scaling is used... if(!idtScale) polyData.mInternal.reset(); return idtScale; } PxU32 Gu::findUniqueConvexEdges(PxU32 maxNbEdges, ConvexEdge* PX_RESTRICT edges, PxU32 numPolygons, const Gu::HullPolygonData* PX_RESTRICT polygons, const PxU8* PX_RESTRICT vertexData) { PxU32 nbEdges = 0; while(numPolygons--) { const HullPolygonData& polygon = *polygons++; const PxU8* vRefBase = vertexData + polygon.mVRef8; PxU32 numEdges = polygon.mNbVerts; PxU32 a = numEdges - 1; PxU32 b = 0; while(numEdges--) { PxU8 vi0 = vRefBase[a]; PxU8 vi1 = vRefBase[b]; if(vi1 < vi0) { PxU8 tmp = vi0; vi0 = vi1; vi1 = tmp; } bool found=false; for(PxU32 i=0;i<nbEdges;i++) { if(edges[i].vref0==vi0 && edges[i].vref1==vi1) { found = true; edges[i].normal += polygon.mPlane.n; break; } } if(!found) { if(nbEdges==maxNbEdges) { PX_ALWAYS_ASSERT_MESSAGE("Internal error: max nb edges reached. This shouldn't be possible..."); return nbEdges; } edges[nbEdges].vref0 = vi0; edges[nbEdges].vref1 = vi1; edges[nbEdges].normal = polygon.mPlane.n; nbEdges++; } a = b; b++; } } return nbEdges; }
4,828
C++
34.507353
184
0.725973
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/convex/GuConvexEdgeFlags.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEX_EDGE_FLAGS_H #define GU_CONVEX_EDGE_FLAGS_H #include "foundation/PxSimpleTypes.h" namespace physx { namespace Gu { enum ExtraTrigDataFlag { ETD_SILHOUETTE_EDGE_01 = (1 << 0), //First edge is a silhouette edge ETD_SILHOUETTE_EDGE_12 = (1 << 1), //Second edge is a silhouette edge ETD_SILHOUETTE_EDGE_20 = (1 << 2), //Third edge is a silhouette edge ETD_CONVEX_EDGE_01 = (1<<3), // PT: important value, don't change ETD_CONVEX_EDGE_12 = (1<<4), // PT: important value, don't change ETD_CONVEX_EDGE_20 = (1<<5), // PT: important value, don't change ETD_CONVEX_EDGE_ALL = ETD_CONVEX_EDGE_01|ETD_CONVEX_EDGE_12|ETD_CONVEX_EDGE_20 }; // PT: helper function to make sure we use the proper default flags everywhere PX_FORCE_INLINE PxU8 getConvexEdgeFlags(const PxU8* extraTrigData, PxU32 triangleIndex) { return extraTrigData ? extraTrigData[triangleIndex] : PxU8(ETD_CONVEX_EDGE_ALL); } PX_FORCE_INLINE void flipConvexEdgeFlags(PxU8& extraData) { // PT: this is a fix for PX-2327. When we flip the winding we also need to flip the precomputed edge flags. // 01 => 02 // 12 => 21 // 20 => 10 const PxU8 convex01 = extraData & Gu::ETD_CONVEX_EDGE_01; const PxU8 convex12 = extraData & Gu::ETD_CONVEX_EDGE_12; const PxU8 convex20 = extraData & Gu::ETD_CONVEX_EDGE_20; const PxU8 silhouette01 = extraData & Gu::ETD_SILHOUETTE_EDGE_01; const PxU8 silhouette12 = extraData & Gu::ETD_SILHOUETTE_EDGE_12; const PxU8 silhouette20 = extraData & Gu::ETD_SILHOUETTE_EDGE_20; extraData = convex12|silhouette12; if(convex01) extraData |= Gu::ETD_CONVEX_EDGE_20; if(convex20) extraData |= Gu::ETD_CONVEX_EDGE_01; if(silhouette01) extraData |= Gu::ETD_SILHOUETTE_EDGE_20; if(silhouette20) extraData |= Gu::ETD_SILHOUETTE_EDGE_01; } } } #endif
3,511
C
41.313253
109
0.733979
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/ccd/GuCCDSweepPrimitives.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 "GuVecCapsule.h" #include "GuVecBox.h" #include "GuVecConvexHull.h" #include "GuVecTriangle.h" #include "GuGJKRaycast.h" #include "GuCCDSweepConvexMesh.h" #include "GuGJKType.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxCustomGeometry.h" //#define USE_VIRTUAL_GJK namespace physx { namespace Gu { using namespace aos; template<typename Geom> PX_FORCE_INLINE PxReal getRadius(const PxGeometry&) { return 0; } template<> PX_FORCE_INLINE PxReal getRadius<CapsuleV>(const PxGeometry& g) { PX_ASSERT(g.getType() == PxGeometryType::eCAPSULE || g.getType() == PxGeometryType::eSPHERE); PX_COMPILE_TIME_ASSERT(PX_OFFSET_OF(PxSphereGeometry, radius) == PX_OFFSET_OF(PxCapsuleGeometry, radius)); return static_cast<const PxSphereGeometry&>(g).radius; } #ifdef USE_VIRTUAL_GJK static bool virtualGjkRaycastPenetration(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg initialDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal _inflation, const bool initialOverlap) { return gjkRaycastPenetration<GjkConvex, GjkConvex >(a, b, initialDir, initialLambda, s, r, lambda, normal, closestA, _inflation, initialOverlap); } #endif template<class ConvexA, class ConvexB> static PX_FORCE_INLINE PxReal CCDSweep( ConvexA& a, ConvexB& b, const PxTransform32& transform0, const PxTransform32& transform1, const PxTransform32& lastTm0, const PxTransform32& lastTm1, const aos::FloatV& toiEstimate, PxVec3& worldPoint, PxVec3& worldNormal, PxReal inflation = 0.0f) { PX_UNUSED(toiEstimate); //KS - TODO - can we use this again? using namespace aos; const QuatV q0 = QuatVLoadA(&transform0.q.x); const Vec3V p0 = V3LoadA(&lastTm0.p.x); const QuatV q1 = QuatVLoadA(&transform1.q.x); const Vec3V p1 = V3LoadA(&lastTm1.p.x); const PxTransformV tr0(p0, q0); const PxTransformV tr1(p1, q1); const PxMatTransformV aToB(tr1.transformInv(tr0)); const Vec3V trans0p = V3LoadA(transform0.p); const Vec3V trans1p = V3LoadA(transform1.p); const Vec3V trA = V3Sub(trans0p, p0); const Vec3V trB = V3Sub(trans1p, p1); const Vec3V relTr = tr1.rotateInv(V3Sub(trB, trA)); FloatV lambda; Vec3V closestA, normal; const FloatV initialLambda = FZero(); const RelativeConvex<ConvexA> convexA(a, aToB); const LocalConvex<ConvexB> convexB(b); #ifdef USE_VIRTUAL_GJK if(virtualGjkRaycastPenetration(convexA, convexB, aToB.p, initialLambda, V3Zero(), relTr, lambda, normal, closestA, inflation, true)) #else if(gjkRaycastPenetration<RelativeConvex<ConvexA>, LocalConvex<ConvexB> >(convexA, convexB, aToB.p, initialLambda, V3Zero(), relTr, lambda, normal, closestA, inflation, true)) #endif { //Adjust closestA because it will be on the surface of convex a in its initial position (s). If the TOI > 0, we need to move //the point along the sweep direction to get the world-space hit position. PxF32 res; FStore(lambda, &res); closestA = V3ScaleAdd(trA, FMax(lambda, FZero()), tr1.transform(closestA)); normal = tr1.rotate(normal); V3StoreU(normal, worldNormal); V3StoreU(closestA, worldPoint); return res; } return PX_MAX_REAL; } // // lookup table for geometry-vs-geometry sweeps // PxReal UnimplementedSweep (GU_SWEEP_METHOD_ARGS_UNUSED) { return PX_MAX_REAL; //no impact } template<typename Geom0, typename Geom1> static PxReal SweepGeomGeom(GU_SWEEP_METHOD_ARGS) { PX_UNUSED(outCCDFaceIndex); PX_UNUSED(fastMovingThreshold); const PxGeometry& g0 = *shape0.mGeometry; const PxGeometry& g1 = *shape1.mGeometry; typename ConvexGeom<Geom0>::Type geom0(g0); typename ConvexGeom<Geom1>::Type geom1(g1); return CCDSweep(geom0, geom1, transform0, transform1, lastTm0, lastTm1, FLoad(toiEstimate), worldPoint, worldNormal, restDistance+getRadius<Geom0>(g0)+getRadius<Geom1>(g1) ); } static PxReal SweepAnyShapeCustom(GU_SWEEP_METHOD_ARGS) { PX_UNUSED(fastMovingThreshold); PX_UNUSED(toiEstimate); PX_UNUSED(restDistance); const PxGeometry& g0 = *shape0.mGeometry; const PxGeometry& g1 = *shape1.mGeometry; PX_ASSERT(g1.getType() == PxGeometryType::eCUSTOM); const PxVec3 trA = transform0.p - lastTm0.p; const PxVec3 trB = transform1.p - lastTm1.p; const PxVec3 relTr = trA - trB; PxVec3 unitDir = relTr; const PxReal length = unitDir.normalize(); PxGeomSweepHit sweepHit; if (!static_cast<const PxCustomGeometry&>(g1).callbacks->sweep(unitDir, length, g1, lastTm1, g0, lastTm0, sweepHit, PxHitFlag::eDEFAULT, 0.0f, NULL)) return PX_MAX_REAL; worldNormal = sweepHit.normal; worldPoint = sweepHit.position; outCCDFaceIndex = sweepHit.faceIndex; return sweepHit.distance / length; } typedef PxReal (*SweepMethod) (GU_SWEEP_METHOD_ARGS); PxReal SweepAnyShapeHeightfield(GU_SWEEP_METHOD_ARGS); PxReal SweepAnyShapeMesh(GU_SWEEP_METHOD_ARGS); SweepMethod g_SweepMethodTable[][PxGeometryType::eGEOMETRY_COUNT] = { //PxGeometryType::eSPHERE { SweepGeomGeom<CapsuleV, CapsuleV>, //PxGeometryType::eSPHERE UnimplementedSweep, //PxGeometryType::ePLANE SweepGeomGeom<CapsuleV, CapsuleV>, //PxGeometryType::eCAPSULE SweepGeomGeom<CapsuleV, BoxV>, //PxGeometryType::eBOX SweepGeomGeom<CapsuleV, ConvexHullV>, //PxGeometryType::eCONVEXMESH UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, //PxGeometryType::ePLANE { 0, //PxGeometryType::eSPHERE UnimplementedSweep, //PxGeometryType::ePLANE UnimplementedSweep, //PxGeometryType::eCAPSULE UnimplementedSweep, //PxGeometryType::eBOX UnimplementedSweep, //PxGeometryType::eCONVEXMESH UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM UnimplementedSweep, //PxGeometryType::eCUSTOM }, //PxGeometryType::eCAPSULE { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE SweepGeomGeom<CapsuleV, CapsuleV>, //PxGeometryType::eCAPSULE SweepGeomGeom<CapsuleV, BoxV>, //PxGeometryType::eBOX SweepGeomGeom<CapsuleV, ConvexHullV>, //PxGeometryType::eCONVEXMESH UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, //PxGeometryType::eBOX { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE SweepGeomGeom<BoxV, BoxV>, //PxGeometryType::eBOX SweepGeomGeom<BoxV, ConvexHullV>, //PxGeometryType::eCONVEXMESH UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, //PxGeometryType::eCONVEXMESH { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX SweepGeomGeom<ConvexHullV, ConvexHullV>, //PxGeometryType::eCONVEXMESH UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH SweepAnyShapeMesh, //PxGeometryType::eTRIANGLEMESH SweepAnyShapeHeightfield, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, //PxGeometryType::ePARTICLESYSTEM { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX 0, //PxGeometryType::eCONVEXMESH UnimplementedSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM UnimplementedSweep, //PxGeometryType::eCUSTOM }, //PxGeometryType::eTETRAHEDRONMESH { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX 0, //PxGeometryType::eCONVEXMESH 0, //PxGeometryType::ePARTICLESYSTEM UnimplementedSweep, //PxGeometryType::eTETRAHEDRONMESH UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM UnimplementedSweep, //PxGeometryType::eCUSTOM }, //PxGeometryType::eTRIANGLEMESH { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX 0, //PxGeometryType::eCONVEXMESH 0, //PxGeometryType::ePARTICLESYSTEM 0, //PxGeometryType::eTETRAHEDRONMESH UnimplementedSweep, //PxGeometryType::eTRIANGLEMESH UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, //PxGeometryType::eHEIGHTFIELD { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX 0, //PxGeometryType::eCONVEXMESH 0, //PxGeometryType::ePARTICLESYSTEM 0, //PxGeometryType::eTETRAHEDRONMESH 0, //PxGeometryType::eTRIANGLEMESH UnimplementedSweep, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, //PxGeometryType::eHAIRSYSTEM { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX 0, //PxGeometryType::eCONVEXMESH 0, //PxGeometryType::ePARTICLESYSTEM 0, //PxGeometryType::eTETRAHEDRONMESH 0, //PxGeometryType::eTRIANGLEMESH 0, //PxGeometryType::eHEIGHTFIELD UnimplementedSweep, //PxGeometryType::eHAIRSYSTEM UnimplementedSweep, //PxGeometryType::eCUSTOM }, //PxGeometryType::eCUSTOM { 0, //PxGeometryType::eSPHERE 0, //PxGeometryType::ePLANE 0, //PxGeometryType::eCAPSULE 0, //PxGeometryType::eBOX 0, //PxGeometryType::eCONVEXMESH 0, //PxGeometryType::ePARTICLESYSTEM 0, //PxGeometryType::eTETRAHEDRONMESH 0, //PxGeometryType::eTRIANGLEMESH 0, //PxGeometryType::eHEIGHTFIELD 0, //PxGeometryType::eHAIRSYSTEM SweepAnyShapeCustom, //PxGeometryType::eCUSTOM }, }; PX_COMPILE_TIME_ASSERT(sizeof(g_SweepMethodTable) / sizeof(g_SweepMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT); PxReal SweepShapeShape(GU_SWEEP_METHOD_ARGS) { const PxGeometryType::Enum type0 = shape0.mGeometry->getType(); const PxGeometryType::Enum type1 = shape1.mGeometry->getType(); return g_SweepMethodTable[type0][type1](shape0, shape1, transform0, transform1, lastTm0, lastTm1, restDistance, worldNormal, worldPoint, toiEstimate, outCCDFaceIndex, fastMovingThreshold); } // // lookup table for sweeps agains triangles // PxReal UnimplementedTriangleSweep(GU_TRIANGLE_SWEEP_METHOD_ARGS) { PX_UNUSED(shape0); PX_UNUSED(shape1); PX_UNUSED(transform0); PX_UNUSED(transform1); PX_UNUSED(lastTm0); PX_UNUSED(lastTm1); PX_UNUSED(restDistance); PX_UNUSED(worldNormal); PX_UNUSED(worldPoint); PX_UNUSED(meshScaling); PX_UNUSED(triangle); PX_UNUSED(toiEstimate); return 1e10f; //no impact } template<typename Geom> PxReal SweepGeomTriangles(GU_TRIANGLE_SWEEP_METHOD_ARGS) { PX_UNUSED(meshScaling); PX_UNUSED(shape1); const PxGeometry& g = shape0; //Geom geom(g); typename ConvexGeom<Geom>::Type geom(g); return CCDSweep<TriangleV, Geom>(triangle, geom, transform1, transform0, lastTm1, lastTm0, FLoad(toiEstimate), worldPoint, worldNormal, restDistance+getRadius<Geom>(g) ); } typedef PxReal (*TriangleSweepMethod) (GU_TRIANGLE_SWEEP_METHOD_ARGS); TriangleSweepMethod g_TriangleSweepMethodTable[] = { SweepGeomTriangles<CapsuleV>, //PxGeometryType::eSPHERE UnimplementedTriangleSweep, //PxGeometryType::ePLANE SweepGeomTriangles<CapsuleV>, //PxGeometryType::eCAPSULE SweepGeomTriangles<BoxV>, //PxGeometryType::eBOX SweepGeomTriangles<ConvexHullV>, //PxGeometryType::eCONVEXMESH UnimplementedTriangleSweep, //PxGeometryType::ePARTICLESYSTEM UnimplementedTriangleSweep, //PxGeometryType::eTETRAHEDRONMESH UnimplementedTriangleSweep, //PxGeometryType::eTRIANGLEMESH UnimplementedTriangleSweep, //PxGeometryType::eHEIGHTFIELD UnimplementedTriangleSweep, //PxGeometryType::eHAIRSYSTEM UnimplementedTriangleSweep, //PxGeometryType::eCUSTOM }; PX_COMPILE_TIME_ASSERT(sizeof(g_TriangleSweepMethodTable) / sizeof(g_TriangleSweepMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT); PxReal SweepShapeTriangle(GU_TRIANGLE_SWEEP_METHOD_ARGS) { const PxGeometryType::Enum type0 = shape0.getType(); const TriangleSweepMethod method = g_TriangleSweepMethodTable[type0]; return method(shape0, shape1, transform0, transform1, lastTm0, lastTm1, restDistance, worldNormal, worldPoint, meshScaling, triangle, toiEstimate); } } }
15,925
C++
37.283654
216
0.727598
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/ccd/GuCCDSweepConvexMesh.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 "GuVecCapsule.h" #include "GuVecBox.h" #include "GuVecConvexHull.h" #include "GuVecTriangle.h" #include "GuGJKRaycast.h" #include "GuCCDSweepConvexMesh.h" #include "GuHeightFieldUtil.h" #include "foundation/PxInlineArray.h" #include "GuEntityReport.h" #include "PxContact.h" #include "GuDistancePointTriangle.h" #include "GuBox.h" #include "GuInternal.h" #include "GuBoxConversion.h" #include "GuConvexUtilsInternal.h" #include "GuMidphaseInterface.h" #include "geometry/PxGeometryQuery.h" // PT: this one makes the "behavior after impact" PEEL test "fail" (rocks stop after impact) // It also makes these UTs fail: // [ FAILED ] CCDReportTest.CCD_soakTest_mesh // [ FAILED ] CCDNegativeScalingTest.SLOW_ccdNegScaledMesh static const bool gUseGeometryQuery = false; // PT: this one seems to work. // Timings for PEEL's "limits of speculative contacts test2", for 3 runs: // false: true: // Time: 504 220 // Time: 89 7 // Time: 5 84 // Time: 8 11 // Time: 423 56 // Time: 103 14 // Time: 10 11 // Time: 10 9 // Time: 418 60 // Time: 139 17 // Time: 9 9 // Time: 9 10 static const bool gUseGeometryQueryEst = false; //#define CCD_BASIC_PROFILING #ifdef CCD_BASIC_PROFILING #include <stdio.h> #endif namespace physx { namespace Gu { PxReal SweepShapeTriangle(GU_TRIANGLE_SWEEP_METHOD_ARGS); using namespace aos; namespace { struct AccumCallback: public MeshHitCallback<PxGeomRaycastHit> { PX_NOCOPY(AccumCallback) public: PxInlineArray<PxU32, 64>& mResult; AccumCallback(PxInlineArray<PxU32, 64>& result) : MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE), mResult(result) { } virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& hit, const PxVec3&, const PxVec3&, const PxVec3&, PxReal&, const PxU32*) { mResult.pushBack(hit.faceIndex); return true; } }; // PT: TODO: refactor with MidPhaseQueryLocalReport struct EntityReportContainerCallback : public OverlapReport { PxInlineArray<PxU32, 64>& container; EntityReportContainerCallback(PxInlineArray<PxU32,64>& container_) : container(container_) { container.forceSize_Unsafe(0); } virtual ~EntityReportContainerCallback() {} virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { for(PxU32 i=0; i<nb; i++) container.pushBack(indices[i]); return true; } private: EntityReportContainerCallback& operator=(const EntityReportContainerCallback&); }; class TriangleHelper { public: TriangleHelper(const PxTriangleMeshGeometry& shapeMesh, const Cm::FastVertex2ShapeScaling& skew, // object is not copied, beware! const PxU32 triangleIndex); void getBounds(PxBounds3& bounds, const physx::PxTransform& transform) const; //non-virtuals: PX_FORCE_INLINE const TriangleMesh* getMeshData() const { return _getMeshData(mShapeMesh); } PxVec3 getPolygonNormal() const; private: TriangleHelper& operator=(const TriangleHelper&); const PxTriangleMeshGeometry& mShapeMesh; const Cm::FastVertex2ShapeScaling& mVertex2ShapeSkew; const PxU32 mTriangleIndex; }; TriangleHelper::TriangleHelper(const PxTriangleMeshGeometry& md, const Cm::FastVertex2ShapeScaling& skew, const PxU32 tg) : mShapeMesh(md), mVertex2ShapeSkew(skew), mTriangleIndex(tg) { } void TriangleHelper::getBounds(PxBounds3& bounds, const physx::PxTransform& transform) const { PxTriangle localTri; getMeshData()->getLocalTriangle(localTri, mTriangleIndex, false); // PT: 'false': no need to flip winding to compute bounds //gotta take bounds in shape space because building it in vertex space and transforming it out would skew it. bounds = PxBounds3::empty(); bounds.include(transform.transform(mVertex2ShapeSkew * localTri.verts[0])); bounds.include(transform.transform(mVertex2ShapeSkew * localTri.verts[1])); bounds.include(transform.transform(mVertex2ShapeSkew * localTri.verts[2])); } PxVec3 TriangleHelper::getPolygonNormal() const { PxTriangle localTri; getMeshData()->getLocalTriangle(localTri, mTriangleIndex, mVertex2ShapeSkew.flipsNormal()); const PxVec3 t0 = mVertex2ShapeSkew * localTri.verts[0]; const PxVec3 t1 = mVertex2ShapeSkew * localTri.verts[1]; const PxVec3 t2 = mVertex2ShapeSkew * localTri.verts[2]; const PxVec3 v0 = t0 - t1; const PxVec3 v1 = t0 - t2; const PxVec3 nor = v0.cross(v1); return nor.getNormalized(); } } PxReal SweepAnyShapeHeightfield(GU_SWEEP_METHOD_ARGS) { PX_UNUSED(toiEstimate); PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eHEIGHTFIELD); const HeightFieldUtil hfUtil(static_cast<const PxHeightFieldGeometry&>(*shape1.mGeometry)); PxInlineArray<PxU32,64> tempContainer; EntityReportContainerCallback callback(tempContainer); const PxVec3 trA = transform0.p - lastTm0.p; const PxVec3 trB = transform1.p - lastTm1.p; const PxVec3 relTr = trA - trB; const PxVec3 halfRelTr = relTr * 0.5f; const PxVec3 ext = shape0.mExtents + halfRelTr.abs() + PxVec3(restDistance); const PxVec3 cent = shape0.mCenter + halfRelTr; const PxBounds3 bounds0(cent - ext, cent + ext); hfUtil.overlapAABBTriangles(transform1, bounds0, callback); PxArray<PxU32> orderedContainer(tempContainer.size()); PxArray<PxU32> distanceEntries(tempContainer.size()); PxU32* orderedList = orderedContainer.begin(); PxF32* distances = reinterpret_cast<PxF32*>(distanceEntries.begin()); const PxVec3 origin = shape0.mCenter; const PxVec3 extent = shape0.mExtents + PxVec3(restDistance); PxReal minTOI = PX_MAX_REAL; PxU32 numTrigs = tempContainer.size(); PxU32* trianglesIndices = tempContainer.begin(); PxU32 count = 0; for(PxU32 a = 0; a < numTrigs; ++a) { PxTriangle tri; hfUtil.getTriangle(shape1.mPrevTransform, tri, 0, 0, trianglesIndices[a], true, true); PxVec3 resultNormal = -(tri.verts[1]-tri.verts[0]).cross(tri.verts[2]-tri.verts[0]); resultNormal.normalize(); if(relTr.dot(resultNormal) >= fastMovingThreshold) { PxBounds3 bounds; bounds.setEmpty(); bounds.include(tri.verts[0]); bounds.include(tri.verts[1]); bounds.include(tri.verts[2]); PxF32 toi = sweepAABBAABB(origin, extent * 1.1f, bounds.getCenter(), (bounds.getExtents() + PxVec3(0.01f, 0.01f, 0.01f)) * 1.1f, trA, trB); PxU32 index = 0; if(toi <= 1.f) { for(PxU32 b = count; b > 0; --b) { if(distances[b-1] <= toi) { //shuffle down and swap index = b; break; } PX_ASSERT(b > 0); PX_ASSERT(b < numTrigs); distances[b] = distances[b-1]; orderedList[b] = orderedList[b-1]; } PX_ASSERT(index < numTrigs); orderedList[index] = trianglesIndices[a]; distances[index] = toi; count++; } } } worldNormal = PxVec3(PxReal(0)); worldPoint = PxVec3(PxReal(0)); Cm::FastVertex2ShapeScaling idScale; PxU32 ccdFaceIndex = PXC_CONTACT_NO_FACE_INDEX; const PxVec3 sphereCenter(shape0.mPrevTransform.p); const PxF32 inSphereRadius = shape0.mFastMovingThreshold; const PxF32 inRadSq = inSphereRadius * inSphereRadius; const PxVec3 sphereCenterInTr1 = transform1.transformInv(sphereCenter); const PxVec3 sphereCenterInTr1T0 = transform1.transformInv(lastTm0.p); PxVec3 tempWorldNormal(0.f), tempWorldPoint(0.f); for (PxU32 ti = 0; ti < count; ti++) { PxTriangle tri; hfUtil.getTriangle(lastTm1, tri, 0, 0, orderedList[ti], false, false); PxVec3 resultNormal, resultPoint; TriangleV triangle(V3LoadU(tri.verts[0]), V3LoadU(tri.verts[1]), V3LoadU(tri.verts[2])); //do sweep PxReal res = SweepShapeTriangle( *shape0.mGeometry, *shape1.mGeometry, transform0, transform1, lastTm0, lastTm1, restDistance, resultNormal, resultPoint, Cm::FastVertex2ShapeScaling(), triangle, 0.f); if(res <= 0.f) { res = 0.f; const PxVec3 v0 = tri.verts[1] - tri.verts[0]; const PxVec3 v1 = tri.verts[2] - tri.verts[0]; //Now we have a 0 TOI, lets see if the in-sphere hit it! PxF32 distanceSq = distancePointTriangleSquared( sphereCenterInTr1, tri.verts[0], v0, v1); if(distanceSq < inRadSq) { const PxVec3 nor = v0.cross(v1); const PxF32 distance = PxSqrt(distanceSq); res = distance - inSphereRadius; const PxF32 d = nor.dot(tri.verts[0]); const PxF32 dd = nor.dot(sphereCenterInTr1T0); if((dd - d) > 0.f) { //back side, penetration res = -(2.f * inSphereRadius - distance); } } } if (res < minTOI) { const PxVec3 v0 = tri.verts[1] - tri.verts[0]; const PxVec3 v1 = tri.verts[2] - tri.verts[0]; PxVec3 resultNormal1 = v0.cross(v1); resultNormal1.normalize(); //if(norDotRel > 1e-6f) { tempWorldNormal = resultNormal1; tempWorldPoint = resultPoint; minTOI = res; ccdFaceIndex = orderedList[ti]; } } } worldNormal = transform1.rotate(tempWorldNormal); worldPoint = tempWorldPoint; outCCDFaceIndex = ccdFaceIndex; return minTOI; } PxReal SweepEstimateAnyShapeHeightfield(GU_SWEEP_ESTIMATE_ARGS) { PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eHEIGHTFIELD); const HeightFieldUtil hfUtil(static_cast<const PxHeightFieldGeometry&>(*shape1.mGeometry)); PxInlineArray<PxU32,64> tempContainer; EntityReportContainerCallback callback(tempContainer); const PxTransform& transform0 = shape0.mCurrentTransform; const PxTransform& lastTr0 = shape0.mPrevTransform; const PxTransform& transform1 = shape1.mCurrentTransform; const PxTransform& lastTr1 = shape1.mPrevTransform; const PxVec3 trA = transform0.p - lastTr0.p; const PxVec3 trB = transform1.p - lastTr1.p; const PxVec3 relTr = trA - trB; const PxVec3 halfRelTr = relTr * 0.5f; const PxVec3 extents = shape0.mExtents + halfRelTr.abs() + PxVec3(restDistance); const PxVec3 center = shape0.mCenter + halfRelTr; const PxBounds3 bounds0(center - extents, center + extents); hfUtil.overlapAABBTriangles(transform1, bounds0, callback); PxVec3 origin = shape0.mCenter; PxVec3 extent = shape0.mExtents; PxReal minTOI = PX_MAX_REAL; PxU32 numTrigs = tempContainer.size(); PxU32* trianglesIndices = tempContainer.begin(); for(PxU32 a = 0; a < numTrigs; ++a) { PxTriangle tri; hfUtil.getTriangle(shape1.mPrevTransform, tri, 0, 0, trianglesIndices[a], true, true); PxVec3 resultNormal = -(tri.verts[1]-tri.verts[0]).cross(tri.verts[2]-tri.verts[0]); resultNormal.normalize(); if(relTr.dot(resultNormal) >= fastMovingThreshold) { PxBounds3 bounds; bounds.setEmpty(); bounds.include(tri.verts[0]); bounds.include(tri.verts[1]); bounds.include(tri.verts[2]); PxF32 toi = sweepAABBAABB(origin, extent * 1.1f, bounds.getCenter(), (bounds.getExtents() + PxVec3(0.01f, 0.01f, 0.01f)) * 1.1f, trA, trB); minTOI = PxMin(minTOI, toi); } } return minTOI; } PxReal SweepAnyShapeMesh(GU_SWEEP_METHOD_ARGS) { PX_UNUSED(toiEstimate); // this is the trimesh midphase for convex vs mesh sweep. shape0 is the convex shape. const PxVec3 trA = transform0.p - lastTm0.p; const PxVec3 trB = transform1.p - lastTm1.p; const PxVec3 relTr = trA - trB; PxVec3 unitDir = relTr; const PxReal length = unitDir.normalize(); PX_UNUSED(restDistance); PX_UNUSED(fastMovingThreshold); if(gUseGeometryQuery) { PxGeomSweepHit sweepHit; if(!PxGeometryQuery::sweep(unitDir, length, *shape0.mGeometry, lastTm0, *shape1.mGeometry, lastTm1, sweepHit, PxHitFlag::eDEFAULT, 0.0f, PxGeometryQueryFlag::Enum(0), NULL)) //if(!PxGeometryQuery::sweep(unitDir, length, *shape0.mGeometry, transform0, *shape1.mGeometry, transform1, sweepHit, PxHitFlag::eDEFAULT, 0.0f, PxGeometryQueryFlag::Enum(0), NULL)) return PX_MAX_REAL; worldNormal = sweepHit.normal; worldPoint = sweepHit.position; outCCDFaceIndex = sweepHit.faceIndex; return sweepHit.distance/length; } else { // Get actual shape data PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eTRIANGLEMESH); const PxTriangleMeshGeometry& shapeMesh = static_cast<const PxTriangleMeshGeometry&>(*shape1.mGeometry); const Cm::FastVertex2ShapeScaling meshScaling(shapeMesh.scale); const PxMat33 matRot(PxIdentity); //1) Compute the swept bounds Box sweptBox; computeSweptBox(sweptBox, shape0.mExtents, shape0.mCenter, matRot, unitDir, length); Box vertexSpaceBox; if (shapeMesh.scale.isIdentity()) vertexSpaceBox = transformBoxOrthonormal(sweptBox, transform1.getInverse()); else computeVertexSpaceOBB(vertexSpaceBox, sweptBox, transform1, shapeMesh.scale); vertexSpaceBox.extents += PxVec3(restDistance); PxInlineArray<PxU32, 64> tempContainer; AccumCallback callback(tempContainer); // AP scaffold: early out opportunities, should probably use fat raycast Midphase::intersectOBB(_getMeshData(shapeMesh), vertexSpaceBox, callback, true); if (tempContainer.size() == 0) return PX_MAX_REAL; // Intersection found, fetch triangles PxU32 numTrigs = tempContainer.size(); const PxU32* triangleIndices = tempContainer.begin(); PxVec3 origin = shape0.mCenter; PxVec3 extent = shape0.mExtents + PxVec3(restDistance); PxInlineArray<PxU32, 64> orderedContainer; orderedContainer.resize(tempContainer.size()); PxInlineArray<PxU32, 64> distanceEntries; distanceEntries.resize(tempContainer.size()); PxU32* orderedList = orderedContainer.begin(); PxF32* distances = reinterpret_cast<PxF32*>(distanceEntries.begin()); PxReal minTOI = PX_MAX_REAL; PxU32 count = 0; for(PxU32 a = 0; a < numTrigs; ++a) { const TriangleHelper convexPartOfMesh1(shapeMesh, meshScaling, triangleIndices[a]); const PxVec3 resultNormal = -transform1.rotate(convexPartOfMesh1.getPolygonNormal()); if(relTr.dot(resultNormal) >= fastMovingThreshold) { PxBounds3 bounds; convexPartOfMesh1.getBounds(bounds, lastTm1); //OK, we have all 3 vertices, now calculate bounds... PxF32 toi = sweepAABBAABB(origin, extent, bounds.getCenter(), bounds.getExtents() + PxVec3(0.02f, 0.02f, 0.02f), trA, trB); PxU32 index = 0; if(toi <= 1.f) { for(PxU32 b = count; b > 0; --b) { if(distances[b-1] <= toi) { //shuffle down and swap index = b; break; } PX_ASSERT(b > 0); PX_ASSERT(b < numTrigs); distances[b] = distances[b-1]; orderedList[b] = orderedList[b-1]; } PX_ASSERT(index < numTrigs); orderedList[index] = triangleIndices[a]; distances[index] = toi; count++; } } } PxVec3 tempWorldNormal(0.f), tempWorldPoint(0.f); Cm::FastVertex2ShapeScaling idScale; PxU32 ccdFaceIndex = PXC_CONTACT_NO_FACE_INDEX; const PxVec3 sphereCenter(lastTm1.p); const PxF32 inSphereRadius = shape0.mFastMovingThreshold; //PxF32 inRadSq = inSphereRadius * inSphereRadius; const PxVec3 sphereCenterInTransform1 = transform1.transformInv(sphereCenter); const PxVec3 sphereCenterInTransform0p = transform1.transformInv(lastTm0.p); for (PxU32 ti = 0; ti < count /*&& PxMax(minTOI, 0.f) >= distances[ti]*/; ti++) { const TriangleHelper convexPartOfMesh1(shapeMesh, meshScaling, orderedList[ti]); PxVec3 resultNormal, resultPoint; PxTriangle localTri; _getMeshData(shapeMesh)->getLocalTriangle(localTri, orderedList[ti], meshScaling.flipsNormal()); const PxVec3 v0 = meshScaling * localTri.verts[0]; const PxVec3 v1 = meshScaling * localTri.verts[1]; const PxVec3 v2 = meshScaling * localTri.verts[2]; TriangleV triangle(V3LoadU(v0), V3LoadU(v1), V3LoadU(v2)); //do sweep PxReal res = SweepShapeTriangle( *shape0.mGeometry, *shape1.mGeometry, transform0, transform1, lastTm0, lastTm1, restDistance, resultNormal, resultPoint, Cm::FastVertex2ShapeScaling(), triangle, 0.f); resultNormal = -resultNormal; if(res <= 0.f) { res = 0.f; const PxF32 inRad = inSphereRadius + restDistance; const PxF32 inRadSq = inRad*inRad; const PxVec3 vv0 = v1 - v0; const PxVec3 vv1 = v2 - v0; const PxVec3 nor = vv0.cross(vv1); //Now we have a 0 TOI, lets see if the in-sphere hit it! const PxF32 distanceSq = distancePointTriangleSquared( sphereCenterInTransform1, v0, vv0, vv1); if(distanceSq < inRadSq) { const PxF32 distance = PxSqrt(distanceSq); res = distance - inRad; const PxF32 d = nor.dot(v0); const PxF32 dd = nor.dot(sphereCenterInTransform0p); if((dd - d) < 0.f) { //back side, penetration res = -(2.f * inRad - distance); } } PX_ASSERT(PxIsFinite(res)); resultNormal = transform1.rotate(convexPartOfMesh1.getPolygonNormal()); } if (res < minTOI) { tempWorldNormal = resultNormal;//convexPartOfMesh1.getPolygonNormal(0);//transform1.rotate(convexPartOfMesh1.getPolygonNormal(0)); tempWorldPoint = resultPoint; minTOI = res; ccdFaceIndex = orderedList[ti]; } } worldNormal = tempWorldNormal;//transform1.rotate(tempWorldNormal); worldPoint = tempWorldPoint; outCCDFaceIndex = ccdFaceIndex; return minTOI; } } /** \brief This code performs a conservative estimate of the TOI of a shape v mesh. */ PxReal SweepEstimateAnyShapeMesh(GU_SWEEP_ESTIMATE_ARGS) { // this is the trimesh midphase for convex vs mesh sweep. shape0 is the convex shape. // Get actual shape data PX_ASSERT(shape1.mGeometry->getType()==PxGeometryType::eTRIANGLEMESH); const PxTriangleMeshGeometry& shapeMesh = static_cast<const PxTriangleMeshGeometry&>(*shape1.mGeometry); const PxTransform& transform0 = shape0.mCurrentTransform; const PxTransform& lastTr0 = shape0.mPrevTransform; const PxTransform& transform1 = shape1.mCurrentTransform; const PxTransform& lastTr1 = shape1.mPrevTransform; const PxVec3 trA = transform0.p - lastTr0.p; const PxVec3 trB = transform1.p - lastTr1.p; const PxVec3 relTr = trA - trB; PxVec3 unitDir = relTr; const PxReal length = unitDir.normalize(); #ifdef CCD_BASIC_PROFILING unsigned long long time = __rdtsc(); #endif if(gUseGeometryQueryEst) { PX_UNUSED(restDistance); PX_UNUSED(fastMovingThreshold); PX_UNUSED(shapeMesh); { PxGeomSweepHit sweepHit; bool status = PxGeometryQuery::sweep(unitDir, length, *shape0.mGeometry, lastTr0, *shape1.mGeometry, lastTr1, sweepHit, PxHitFlag::eDEFAULT, 0.0f, PxGeometryQueryFlag::Enum(0), NULL); #ifdef CCD_BASIC_PROFILING unsigned long long time2 = __rdtsc(); printf("Time: %d\n", PxU32(time2 - time)/1024); #endif return status ? sweepHit.distance/length : PX_MAX_REAL; } } else { const Cm::FastVertex2ShapeScaling meshScaling(shapeMesh.scale); const PxMat33 matRot(PxIdentity); //1) Compute the swept bounds Box sweptBox; computeSweptBox(sweptBox, shape0.mExtents, shape0.mCenter, matRot, unitDir, length); Box vertexSpaceBox; computeVertexSpaceOBB(vertexSpaceBox, sweptBox, transform1, shapeMesh.scale); vertexSpaceBox.extents += PxVec3(restDistance); // TODO: implement a cached mode that fetches the trigs from a cache rather than per opcode if there is little motion. struct CB : MeshHitCallback<PxGeomRaycastHit> { PxReal minTOI; PxReal sumFastMovingThresh; const PxTriangleMeshGeometry& shapeMesh; const Cm::FastVertex2ShapeScaling& meshScaling; const PxVec3& relTr; const PxVec3& trA; const PxVec3& trB; const PxTransform& transform1; const PxVec3& origin; const PxVec3& extent; CB(PxReal aSumFast, const PxTriangleMeshGeometry& aShapeMesh, const Cm::FastVertex2ShapeScaling& aMeshScaling, const PxVec3& aRelTr, const PxVec3& atrA, const PxVec3& atrB, const PxTransform& aTransform1, const PxVec3& aOrigin, const PxVec3& aExtent) : MeshHitCallback<PxGeomRaycastHit>(CallbackMode::eMULTIPLE), sumFastMovingThresh(aSumFast), shapeMesh(aShapeMesh), meshScaling(aMeshScaling), relTr(aRelTr), trA(atrA), trB(atrB), transform1(aTransform1), origin(aOrigin), extent(aExtent) { minTOI = PX_MAX_REAL; } virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& hit, const PxVec3&, const PxVec3&, const PxVec3&, PxReal& shrunkMaxT, const PxU32*) { const TriangleHelper convexPartOfMesh1(shapeMesh, meshScaling, hit.faceIndex); const PxVec3 resultNormal = -transform1.rotate(convexPartOfMesh1.getPolygonNormal()); if(relTr.dot(resultNormal) >= sumFastMovingThresh) { PxBounds3 bounds; convexPartOfMesh1.getBounds(bounds, transform1); //OK, we have all 3 vertices, now calculate bounds... PxF32 toi = sweepAABBAABB( origin, extent * 1.1f, bounds.getCenter(), (bounds.getExtents() + PxVec3(0.01f, 0.01f, 0.01f)) * 1.1f, trA, trB); minTOI = PxMin(minTOI, toi); shrunkMaxT = minTOI; } return (minTOI > 0.0f); // stop traversal if minTOI == 0.0f } void operator=(const CB&) {} }; const PxVec3& origin = shape0.mCenter; const PxVec3 extent = shape0.mExtents + PxVec3(restDistance); CB callback(fastMovingThreshold, shapeMesh, meshScaling, relTr, trA, trB, transform1, origin, extent); Midphase::intersectOBB(_getMeshData(shapeMesh), vertexSpaceBox, callback, true); #ifdef CCD_BASIC_PROFILING unsigned long long time2 = __rdtsc(); printf("Time: %d\n", PxU32(time2 - time)/1024); #endif return callback.minTOI; } } } }
22,864
C++
30.537931
186
0.723233
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/ccd/GuCCDSweepConvexMesh.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CCD_SWEEP_CONVEX_MESH_H #define GU_CCD_SWEEP_CONVEX_MESH_H #include "common/PxPhysXCommonConfig.h" #include "foundation/PxVecTransform.h" #include "CmScaling.h" #define GU_TRIANGLE_SWEEP_METHOD_ARGS \ const PxGeometry& shape0, \ const PxGeometry& shape1, \ const PxTransform32& transform0, \ const PxTransform32& transform1, \ const PxTransform32& lastTm0, \ const PxTransform32& lastTm1, \ PxReal restDistance, \ PxVec3& worldNormal, \ PxVec3& worldPoint, \ const Cm::FastVertex2ShapeScaling& meshScaling, \ Gu::TriangleV& triangle, \ const PxF32 toiEstimate #define GU_SWEEP_METHOD_ARGS \ const Gu::CCDShape& shape0, \ const Gu::CCDShape& shape1, \ const PxTransform32& transform0, \ const PxTransform32& transform1, \ const PxTransform32& lastTm0, \ const PxTransform32& lastTm1, \ PxReal restDistance, \ PxVec3& worldNormal, \ PxVec3& worldPoint, \ const PxF32 toiEstimate, \ PxU32& outCCDFaceIndex, \ const PxReal fastMovingThreshold #define GU_SWEEP_ESTIMATE_ARGS \ const CCDShape& shape0, \ const CCDShape& shape1, \ const PxReal restDistance, \ const PxReal fastMovingThreshold #define GU_SWEEP_METHOD_ARGS_UNUSED \ const Gu::CCDShape& /*shape0*/, \ const Gu::CCDShape& /*shape1*/, \ const PxTransform32& /*transform0*/,\ const PxTransform32& /*transform1*/,\ const PxTransform32& /*lastTm0*/, \ const PxTransform32& /*lastTm1*/, \ PxReal /*restDistance*/, \ PxVec3& /*worldNormal*/, \ PxVec3& /*worldPoint*/, \ const PxF32 /*toiEstimate*/, \ PxU32& /*outCCDFaceIndex*/, \ const PxReal /*fastMovingThreshold*/ namespace physx { namespace Gu { struct CCDShape { const PxGeometry* mGeometry; PxReal mFastMovingThreshold; //The CCD threshold for this shape PxTransform mPrevTransform; //This shape's previous transform PxTransform mCurrentTransform; //This shape's current transform PxVec3 mExtents; //The extents of this shape's AABB PxVec3 mCenter; //The center of this shape's AABB PxU32 mUpdateCount; //How many times this shape has been updated in the CCD. This is correlated with the CCD body's update count. }; PX_FORCE_INLINE PxF32 sweepAABBAABB(const PxVec3& centerA, const PxVec3& extentsA, const PxVec3& centerB, const PxVec3& extentsB, const PxVec3& trA, const PxVec3& trB) { //Sweep 2 AABBs against each other, return the TOI when they hit else PX_MAX_REAL if they don't hit const PxVec3 cAcB = centerA - centerB; const PxVec3 sumExtents = extentsA + extentsB; //Initial hit if(PxAbs(cAcB.x) <= sumExtents.x && PxAbs(cAcB.y) <= sumExtents.y && PxAbs(cAcB.z) <= sumExtents.z) return 0.f; //No initial hit - perform the sweep const PxVec3 relTr = trB - trA; PxF32 tfirst = 0.f; PxF32 tlast = 1.f; const PxVec3 aMax = centerA + extentsA; const PxVec3 aMin = centerA - extentsA; const PxVec3 bMax = centerB + extentsB; const PxVec3 bMin = centerB - extentsB; const PxF32 eps = 1e-6f; for(PxU32 a = 0; a < 3; ++a) { if(relTr[a] < -eps) { if(bMax[a] < aMin[a]) return PX_MAX_REAL; if(aMax[a] < bMin[a]) tfirst = PxMax((aMax[a] - bMin[a])/relTr[a], tfirst); if(bMax[a] > aMin[a]) tlast = PxMin((aMin[a] - bMax[a])/relTr[a], tlast); } else if(relTr[a] > eps) { if(bMin[a] > aMax[a]) return PX_MAX_REAL; if(bMax[a] < aMin[a]) tfirst = PxMax((aMin[a] - bMax[a])/relTr[a], tfirst); if(aMax[a] > bMin[a]) tlast = PxMin((aMax[a] - bMin[a])/relTr[a], tlast); } else { if(bMax[a] < aMin[a] || bMin[a] > aMax[a]) return PX_MAX_REAL; } //No hit if(tfirst > tlast) return PX_MAX_REAL; } //There was a hit so return the TOI return tfirst; } PX_PHYSX_COMMON_API PxReal SweepShapeShape(GU_SWEEP_METHOD_ARGS); PX_PHYSX_COMMON_API PxReal SweepEstimateAnyShapeHeightfield(GU_SWEEP_ESTIMATE_ARGS); PX_PHYSX_COMMON_API PxReal SweepEstimateAnyShapeMesh(GU_SWEEP_ESTIMATE_ARGS); } } #endif
5,755
C
33.674699
168
0.69609
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKPenetration.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJK_PENETRATION_H #define GU_GJK_PENETRATION_H #include "GuConvexSupportTable.h" #include "GuGJKSimplex.h" #include "GuVecConvexHullNoScale.h" #include "GuGJKUtil.h" #include "foundation/PxUtilities.h" #include "GuGJKType.h" #define GJK_VALIDATE 0 namespace physx { namespace Gu { class ConvexV; PX_FORCE_INLINE void assignWarmStartValue(PxU8* PX_RESTRICT aIndices, PxU8* PX_RESTRICT bIndices, PxU8& size_, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, PxU32 size ) { if(aIndices) { PX_ASSERT(bIndices); size_ = PxTo8(size); for(PxU32 i=0; i<size; ++i) { aIndices[i] = PxTo8(aInd[i]); bIndices[i] = PxTo8(bInd[i]); } } } PX_FORCE_INLINE void validateDuplicateVertex(const aos::Vec3V* Q, const aos::Vec3VArg support, const PxU32 size) { using namespace aos; const FloatV eps = FEps(); //Get rid of the duplicate point BoolV match = BFFFF(); for(PxU32 na = 0; na < size; ++na) { Vec3V dif = V3Sub(Q[na], support); match = BOr(match, FIsGrtr(eps, V3Dot(dif, dif))); } //we have duplicate code if(BAllEqTTTT(match)) { PX_ASSERT(0); } } //*Each convex has //* a support function //* a margin - if the shape is sphere/capsule, margin is the radius //* a minMargin - some percentage of margin, which is used to determine the termination condition for gjk //*We'll report: //* GJK_NON_INTERSECT if the minimum distance between the shapes is greater than the sum of the margins and the the contactDistance //* EPA_CONTACT if shapes overlap. We treat sphere/capsule as a point/a segment and we shrunk other shapes by 10% of margin //* GJK_CONTACT if the algorithm converges, and the distance between the shapes is less than the sum of the margins plus the contactDistance. In this case we return the closest points found //* GJK_DEGENERATE if the algorithm doesn't converge, we return this flag to indicate the normal and closest point we return might not be accurated template<typename ConvexA, typename ConvexB > PX_NOINLINE GjkStatus gjkPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, const bool takeCoreShape, PxU8* PX_RESTRICT aIndices, PxU8* PX_RESTRICT bIndices, aos::Vec3V* PX_RESTRICT aPoints, aos::Vec3V* PX_RESTRICT bPoints, PxU8& warmStartSize, GjkOutput& output) { using namespace aos; //ML: eps is the threshold that uses to determine whether two (shrunk) shapes overlap. We calculate eps2 based on 10% of the minimum margin of two shapes const FloatV minMargin = FMin(a.ConvexA::getMinMargin(), b.ConvexB::getMinMargin()); const FloatV eps = FMul(minMargin, FLoad(0.1f)); //const FloatV eps2 = FMul(_eps2, _eps2); //ML: epsRel2 is the square of 0.01. This is used to scale the square distance of a closest point to origin to determine whether two shrunk shapes overlap in the margin, but //they don't overlap. //const FloatV epsRel2 = FMax(FLoad(0.0001), eps2); // ML:epsRel is square value of 1.5% which applied to the distance of a closest point(v) to the origin. // If |v|- v/|v|.dot(w) < epsRel*|v|=>(|v|*(1-epsRel) < v/|v|.dot(w)), // two shapes are clearly separated, GJK terminate and return non intersect. // This adjusts the termination condition based on the length of v // which avoids ill-conditioned terminations. const FloatV epsRel = FLoad(0.000225f);//1.5%. const FloatV relDif = FSub(FOne(), epsRel); const FloatV zero = FZero(); //capsule/sphere will have margin which is its radius const FloatV marginA = a.getMargin(); const FloatV marginB = b.getMargin(); const BoolV aQuadratic = a.isMarginEqRadius(); const BoolV bQuadratic = b.isMarginEqRadius(); const FloatV tMarginA = FSel(aQuadratic, marginA, zero); const FloatV tMarginB = FSel(bQuadratic, marginB, zero); const FloatV sumMargin = FAdd(tMarginA, tMarginB); const FloatV sumExpandedMargin = FAdd(sumMargin, contactDist); FloatV dist = FMax(); FloatV prevDist = dist; const Vec3V zeroV = V3Zero(); Vec3V prevClos = zeroV; const BoolV bTrue = BTTTT(); BoolV bNotTerminated = bTrue; BoolV bNotDegenerated = bTrue; Vec3V closest; Vec3V Q[4]; Vec3V* A = aPoints; Vec3V* B = bPoints; PxI32 aInd[4]; PxI32 bInd[4]; Vec3V supportA = zeroV, supportB = zeroV, support=zeroV; Vec3V v; PxU32 size = 0;//_size; //ML: if _size!=0, which means we pass in the previous frame simplex so that we can warm-start the simplex. //In this case, GJK will normally terminate in one iteration if(warmStartSize != 0) { for(PxU32 i=0; i<warmStartSize; ++i) { aInd[i] = aIndices[i]; bInd[i] = bIndices[i]; //de-virtualize supportA = a.ConvexA::supportPoint(aIndices[i]); supportB = b.ConvexB::supportPoint(bIndices[i]); support = V3Sub(supportA, supportB); #if GJK_VALIDATE //ML: this is used to varify whether we will have duplicate vertices in the warm-start value. If this function get triggered, //this means something isn't right and we need to investigate validateDuplicateVertex(Q, support, size); #endif A[size] = supportA; B[size] = supportB; Q[size++] = support; } //run simplex solver to determine whether the point is closest enough so that gjk can terminate closest = GJKCPairDoSimplex(Q, A, B, aInd, bInd, support, size); dist = V3Length(closest); //sDist = V3Dot(closest, closest); v = V3ScaleInv(closest, dist); prevDist = dist; prevClos = closest; bNotTerminated = FIsGrtr(dist, eps); } else { //const Vec3V _initialSearchDir = V3Sub(a.getCenter(), b.getCenter()); closest = V3Sel(FIsGrtr(V3Dot(initialSearchDir, initialSearchDir), zero), initialSearchDir, V3UnitX()); v = V3Normalize(closest); } // ML : termination condition //(1)two shapes overlap. GJK will terminate based on sq(v) < eps2 and indicate that two shapes are overlapping. //(2)two shapes are separated. If sq(vw) > sqMargin * sq(v), which means the original objects do not intesect, GJK terminate with GJK_NON_INTERSECT. //(3)two shapes don't overlap. However, they interect within margin distance. if sq(v)- vw < epsRel2*sq(v), this means the shrunk shapes interect in the margin, // GJK terminate with GJK_CONTACT. while(BAllEqTTTT(bNotTerminated)) { //prevDist, prevClos are used to store the previous iteration's closest point and the square distance from the closest point //to origin in Mincowski space prevDist = dist; prevClos = closest; //de-virtualize supportA = a.ConvexA::support(V3Neg(closest), aInd[size]); supportB = b.ConvexB::support(closest, bInd[size]); //calculate the support point support = V3Sub(supportA, supportB); const FloatV vw = V3Dot(v, support); if(FAllGrtr(vw, sumExpandedMargin)) { assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size); return GJK_NON_INTERSECT; } //if(FAllGrtr(FMul(epsRel, dist), FSub(dist, vw))) if(FAllGrtr(vw, FMul(dist, relDif))) { assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size); PX_ASSERT(FAllGrtr(dist, FEps())); //const Vec3V n = V3ScaleInv(closest, dist);//normalise output.normal = v; Vec3V closA, closB; getClosestPoint(Q, A, B, closest, closA, closB, size); //ML: if one of the shape is sphere/capsule and the takeCoreShape flag is true, the contact point for sphere/capsule will be the sphere center or a point in the //capsule segment. This will increase the stability for the manifold recycling code. Otherwise, we will return a contact point on the surface for sphere/capsule //while the takeCoreShape flag is set to be false if(takeCoreShape) { output.closestA= closA; output.closestB = closB; output.penDep = dist; } else { //This is for capsule/sphere want to take the surface point. For box/convex, //we need to get rid of margin output.closestA = V3NegScaleSub(v, tMarginA, closA); output.closestB = V3ScaleAdd(v, tMarginB, closB); output.penDep = FSub(dist, sumMargin); } return GJK_CONTACT; } A[size] = supportA; B[size] = supportB; Q[size++]=support; PX_ASSERT(size <= 4); //calculate the closest point between two convex hull closest = GJKCPairDoSimplex(Q, A, B, aInd, bInd, support, size); dist = V3Length(closest); v = V3ScaleInv(closest, dist); bNotDegenerated = FIsGrtr(prevDist, dist); bNotTerminated = BAnd(FIsGrtr(dist, eps), bNotDegenerated); } if(BAllEqFFFF(bNotDegenerated)) { assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size-1); //Reset back to older closest point dist = prevDist; closest = prevClos;//V3Sub(closA, closB); Vec3V closA, closB; getClosestPoint(Q, A, B, closest, closA, closB, size); //PX_ASSERT(FAllGrtr(dist, FEps())); const Vec3V n = V3ScaleInv(prevClos, prevDist);//normalise output.normal = n; output.searchDir = v; if(takeCoreShape) { output.closestA = closA; output.closestB = closB; output.penDep = dist; } else { //This is for capsule/sphere want to take the surface point. For box/convex, //we need to get rid of margin output.closestA = V3NegScaleSub(n, tMarginA, closA); output.closestB = V3ScaleAdd(n, tMarginB, closB); output.penDep = FSub(dist, sumMargin); if (FAllGrtrOrEq(sumMargin, dist)) return GJK_CONTACT; } return GJK_DEGENERATE; } else { //this two shapes are deeply intersected with each other, we need to use EPA algorithm to calculate MTD assignWarmStartValue(aIndices, bIndices, warmStartSize, aInd, bInd, size); return EPA_CONTACT; } } template<typename ConvexA, typename ConvexB > PX_NOINLINE GjkStatus gjkPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, const bool takeCoreShape, PxU8* PX_RESTRICT aIndices, PxU8* PX_RESTRICT bIndices, PxU8& warmStartSize, GjkOutput& output) { aos::Vec3V aPoints[4], bPoints[4]; return gjkPenetration(a, b, initialSearchDir, contactDist, takeCoreShape, aIndices, bIndices, aPoints, bPoints, warmStartSize, output); } template<typename ConvexA, typename ConvexB > PX_NOINLINE GjkStatus gjkPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, const bool takeCoreShape, aos::Vec3V* PX_RESTRICT aPoints, aos::Vec3V* PX_RESTRICT bPoints, PxU8& warmStartSize, GjkOutput& output) { PxU8 aIndices[4], bIndices[4]; return gjkPenetration(a, b, initialSearchDir, contactDist, takeCoreShape, aIndices, bIndices, aPoints, bPoints, warmStartSize, output); } }//Gu }//physx #endif
12,540
C
36.435821
198
0.708373
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecBox.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_BOX_H #define GU_VEC_BOX_H /** \addtogroup geomutils @{ */ #include "foundation/PxTransform.h" #include "common/PxPhysXCommonConfig.h" #include "geometry/PxBoxGeometry.h" #include "foundation/PxVecTransform.h" #include "GuVecConvex.h" #include "GuConvexSupportTable.h" namespace physx { PX_PHYSX_COMMON_API extern const aos::BoolV boxVertexTable[8]; namespace Gu { #define BOX_MARGIN_RATIO 0.15f #define BOX_MIN_MARGIN_RATIO 0.05f #define BOX_SWEEP_MARGIN_RATIO 0.05f #define BOX_MARGIN_CCD_RATIO 0.01f #define BOX_MIN_MARGIN_CCD_RATIO 0.005f class CapsuleV; PX_FORCE_INLINE void CalculateBoxMargin(const aos::Vec3VArg extent, PxReal& margin, PxReal& minMargin, PxReal& sweepMargin, const PxReal marginR = BOX_MARGIN_RATIO, const PxReal minMarginR = BOX_MIN_MARGIN_RATIO) { using namespace aos; PxReal minExtent; const FloatV min = V3ExtractMin(extent); FStore(min, &minExtent); margin = minExtent * marginR; minMargin = minExtent * minMarginR; sweepMargin = minExtent * BOX_SWEEP_MARGIN_RATIO; } PX_FORCE_INLINE aos::FloatV CalculateBoxTolerance(const aos::Vec3VArg extent) { using namespace aos; const FloatV r0 = FLoad(0.01f); const FloatV min = V3ExtractMin(extent);//FMin(V3GetX(extent), FMin(V3GetY(extent), V3GetZ(extent))); return FMul(min, r0); } //This method is called in the PCM contact gen for the refreshing contacts PX_FORCE_INLINE aos::FloatV CalculatePCMBoxMargin(const aos::Vec3VArg extent, const PxReal toleranceLength, const PxReal toleranceMarginRatio = BOX_MARGIN_RATIO) { using namespace aos; const FloatV min = V3ExtractMin(extent);//FMin(V3GetX(extent), FMin(V3GetY(extent), V3GetZ(extent))); const FloatV toleranceMargin = FLoad(toleranceLength * toleranceMarginRatio); return FMin(FMul(min, FLoad(BOX_MARGIN_RATIO)), toleranceMargin); } PX_FORCE_INLINE aos::FloatV CalculateMTDBoxMargin(const aos::Vec3VArg extent) { using namespace aos; const FloatV min = V3ExtractMin(extent);//FMin(V3GetX(extent), FMin(V3GetY(extent), V3GetZ(extent))); return FMul(min, FLoad(BOX_MARGIN_RATIO)); } class BoxV : public ConvexV { public: /** \brief Constructor */ PX_INLINE BoxV() : ConvexV(ConvexType::eBOX) { } PX_FORCE_INLINE BoxV(const aos::Vec3VArg origin, const aos::Vec3VArg extent) : ConvexV(ConvexType::eBOX, origin), extents(extent) { CalculateBoxMargin(extent, margin, minMargin, sweepMargin); } //this constructor is used by the CCD system PX_FORCE_INLINE BoxV(const PxGeometry& geom) : ConvexV(ConvexType::eBOX, aos::V3Zero()) { using namespace aos; const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(geom); const Vec3V extent = aos::V3LoadU(boxGeom.halfExtents); extents = extent; CalculateBoxMargin(extent, margin, minMargin, sweepMargin, BOX_MARGIN_CCD_RATIO, BOX_MIN_MARGIN_CCD_RATIO); } /** \brief Destructor */ PX_INLINE ~BoxV() { } PX_FORCE_INLINE void resetMargin(const PxReal toleranceLength) { minMargin = PxMin(toleranceLength * BOX_MIN_MARGIN_RATIO, minMargin); } //! Assignment operator PX_FORCE_INLINE const BoxV& operator=(const BoxV& other) { center = other.center; extents = other.extents; margin = other.margin; minMargin = other.minMargin; sweepMargin = other.sweepMargin; return *this; } PX_FORCE_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) verts[i] = V3LoadU_SafeReadW(originalVerts[inds[i]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'populateVerts' is always called with polyData.mVerts) } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { using namespace aos; const BoolV con = boxVertexTable[index]; return V3Sel(con, extents, V3Neg(extents)); } PX_FORCE_INLINE void getIndex(const aos::BoolV con, PxI32& index)const { using namespace aos; index = PxI32(BGetBitMask(con) & 0x7); } PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; return V3Sel(V3IsGrtr(dir, V3Zero()), extents, V3Neg(extents)); } //this is used in the sat test for the full contact gen PX_SUPPORT_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; const Vec3V point = V3Sel(V3IsGrtr(dir, V3Zero()), extents, V3Neg(extents)); max = V3Dot(dir, point); min = FNeg(max); } PX_SUPPORT_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT) const { //a is the current object, b is the other object, dir is in the local space of b using namespace aos; // const Vec3V _dir = aTob.rotateInv(dir);//relTra.rotateInv(dir);//from b to a const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir);//from b to a const Vec3V p = supportLocal(_dir); //transfer p into the b space return aTob.transform(p);//relTra.transform(p); } PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; const BoolV comp = V3IsGrtr(dir, V3Zero()); getIndex(comp, index); return V3Sel(comp, extents, V3Neg(extents)); } PX_SUPPORT_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT, PxI32& index)const { //a is the current object, b is the other object, dir is in the local space of b using namespace aos; // const Vec3V _dir = aTob.rotateInv(dir);//relTra.rotateInv(dir);//from b to a const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir);//from b to a const Vec3V p = supportLocal(_dir, index); //transfer p into the b space return aTob.transform(p);//relTra.transform(p); } aos::Vec3V extents; }; } //PX_COMPILE_TIME_ASSERT(sizeof(Gu::BoxV) == 96); } /** @} */ #endif
7,751
C
33.300885
193
0.722487
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKTest.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJK_TEST_H #define GU_GJK_TEST_H #include "common/PxPhysXCommonConfig.h" #include "GuGJKUtil.h" namespace physx { namespace Gu { struct GjkConvex; PX_PHYSX_COMMON_API GjkStatus testGjk(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, aos::Vec3V& closestA, aos::Vec3V& closestB, aos::Vec3V& normal, aos::FloatV& dist); PX_PHYSX_COMMON_API bool testGjkRaycast(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal _inflation, const bool initialOverlap); PX_PHYSX_COMMON_API GjkStatus testGjkPenetration(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg initialSearchDir, const aos::FloatVArg contactDist, PxU8* aIndices, PxU8* bIndices, PxU8& size, GjkOutput& output); PX_PHYSX_COMMON_API GjkStatus testEpaPenetration(const GjkConvex& a, const GjkConvex& b, const PxU8* aIndices, const PxU8* bIndices, const PxU8 size, GjkOutput& output); } } #endif
2,836
C
49.660713
202
0.765867
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuEPAFacet.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_EPA_FACET_H #define GU_EPA_FACET_H #include "foundation/PxVecMath.h" #include "foundation/PxFPU.h" #include "foundation/PxUtilities.h" #include "CmIDPool.h" #if (defined __GNUC__ && defined _DEBUG) #define PX_EPA_FORCE_INLINE #else #define PX_EPA_FORCE_INLINE PX_FORCE_INLINE #endif #define EPA_DEBUG 0 namespace physx { #define MaxEdges 32 #define MaxFacets 64 #define MaxSupportPoints 64 namespace Gu { const PxU32 lookUp[3] = {1, 2, 0}; PX_FORCE_INLINE PxU32 incMod3(PxU32 i) { return lookUp[i]; } class EdgeBuffer; class Edge; typedef Cm::InlineDeferredIDPool<MaxFacets> EPAFacetManager; class Facet { public: Facet() { } PX_FORCE_INLINE Facet(const PxU32 _i0, const PxU32 _i1, const PxU32 _i2) : m_obsolete(false), m_inHeap(false) { m_indices[0]= PxToI8(_i0); m_indices[1]= PxToI8(_i1); m_indices[2]= PxToI8(_i2); m_adjFacets[0] = m_adjFacets[1] = m_adjFacets[2] = NULL; m_adjEdges[0] = m_adjEdges[1] = m_adjEdges[2] = -1; } PX_FORCE_INLINE void invalidate() { m_adjFacets[0] = m_adjFacets[1] = m_adjFacets[2] = NULL; m_adjEdges[0] = m_adjEdges[1] = m_adjEdges[2] = -1; } PX_FORCE_INLINE bool Valid() { return (m_adjFacets[0] != NULL) & (m_adjFacets[1] != NULL) & (m_adjFacets[2] != NULL); } PX_FORCE_INLINE PxU32 operator[](const PxU32 i) const { return PxU32(m_indices[i]); } //create ajacency information bool link(const PxU32 edge0, Facet* PX_RESTRICT facet, const PxU32 edge1); PX_FORCE_INLINE bool isObsolete() const { return m_obsolete; } //calculate the signed distance from a point to a plane PX_FORCE_INLINE aos::FloatV getPlaneDist(const aos::Vec3VArg p, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf) const; //check to see whether the triangle is a valid triangle, calculate plane normal and plane distance at the same time aos::BoolV isValid2(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, const aos::FloatVArg upper); //return the absolute value for the plane distance from origin PX_FORCE_INLINE aos::FloatV getPlaneDist() const { return aos::FLoad(m_planeDist); } //return the plane normal PX_FORCE_INLINE aos::Vec3V getPlaneNormal()const { return m_planeNormal; } //calculate the closest points for a shape pair void getClosestPoint(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, aos::Vec3V& closestA, aos::Vec3V& closestB); //calculate the closest points for a shape pair //void getClosestPoint(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, aos::FloatV& v, aos::FloatV& w); //performs a flood fill over the boundary of the current polytope. void silhouette(const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager); //m_planeDist is positive bool operator <(const Facet& b) const { return m_planeDist < b.m_planeDist; } //store all the boundary facets for the new polytope in the edgeBuffer and free indices when an old facet isn't part of the boundary anymore PX_FORCE_INLINE void silhouette(const PxU32 index, const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager); aos::Vec3V m_planeNormal; //16 PxF32 m_planeDist; #if EPA_DEBUG PxF32 m_lambda1; PxF32 m_lambda2; #endif Facet* PX_RESTRICT m_adjFacets[3]; //the triangle adjacent to edge i in this triangle //32 PxI8 m_adjEdges[3]; //the edge connected with the corresponding triangle //35 PxI8 m_indices[3]; //the index of vertices of the triangle //38 bool m_obsolete; //a flag to denote whether the triangle are still part of the bundeary of the new polytope //39 bool m_inHeap; //a flag to indicate whether the triangle is in the heap //40 PxU8 m_FacetId; //41 //73 }; class Edge { public: PX_FORCE_INLINE Edge() {} PX_FORCE_INLINE Edge(Facet * PX_RESTRICT facet, const PxU32 index) : m_facet(facet), m_index(index) {} PX_FORCE_INLINE Edge(const Edge& other) : m_facet(other.m_facet), m_index(other.m_index){} PX_FORCE_INLINE Edge& operator = (const Edge& other) { m_facet = other.m_facet; m_index = other.m_index; return *this; } PX_FORCE_INLINE Facet *getFacet() const { return m_facet; } PX_FORCE_INLINE PxU32 getIndex() const { return m_index; } //get out the associated start vertex index in this edge from the facet PX_FORCE_INLINE PxU32 getSource() const { PX_ASSERT(m_index < 3); return (*m_facet)[m_index]; } //get out the associated end vertex index in this edge from the facet PX_FORCE_INLINE PxU32 getTarget() const { PX_ASSERT(m_index < 3); return (*m_facet)[incMod3(m_index)]; } Facet* PX_RESTRICT m_facet; PxU32 m_index; }; class EdgeBuffer { public: EdgeBuffer() : m_Size(0), m_OverFlow(false) { } Edge* Insert(Facet* PX_RESTRICT facet, const PxU32 index) { if (m_Size < MaxEdges) { Edge* pEdge = &m_pEdges[m_Size++]; pEdge->m_facet = facet; pEdge->m_index = index; return pEdge; } m_OverFlow = true; return NULL; } Edge* Get(const PxU32 index) { PX_ASSERT(index < m_Size); return &m_pEdges[index]; } PxU32 Size() { return m_Size; } bool IsValid() { return m_Size > 0 && !m_OverFlow; } void MakeEmpty() { m_Size = 0; m_OverFlow = false; } Edge m_pEdges[MaxEdges]; PxU32 m_Size; bool m_OverFlow; }; //ML: calculate MTD points for a shape pair PX_FORCE_INLINE void Facet::getClosestPoint(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, aos::Vec3V& closestA, aos::Vec3V& closestB) { using namespace aos; const Vec3V pa0(aBuf[m_indices[0]]); const Vec3V pa1(aBuf[m_indices[1]]); const Vec3V pa2(aBuf[m_indices[2]]); const Vec3V pb0(bBuf[m_indices[0]]); const Vec3V pb1(bBuf[m_indices[1]]); const Vec3V pb2(bBuf[m_indices[2]]); const Vec3V p0 = V3Sub(pa0, pb0); const Vec3V p1 = V3Sub(pa1, pb1); const Vec3V p2 = V3Sub(pa2, pb2); const Vec3V v0 = V3Sub(p1, p0); const Vec3V v1 = V3Sub(p2, p0); const Vec3V closestP = V3Scale(m_planeNormal, FLoad(m_planeDist)); const Vec3V v2 = V3Sub(closestP, p0); //calculate barycentric coordinates const FloatV d00 = V3Dot(v0, v0); const FloatV d01 = V3Dot(v0, v1); const FloatV d11 = V3Dot(v1, v1); const FloatV d20 = V3Dot(v2, v0); const FloatV d21 = V3Dot(v2, v1); const FloatV det = FNegScaleSub(d01, d01, FMul(d00, d11));//FSub( FMul(v1dv1, v2dv2), FMul(v1dv2, v1dv2) ); // non-negative const FloatV recip = FSel(FIsGrtr(det, FEps()), FRecip(det), FZero()); const FloatV lambda1 = FMul(FNegScaleSub(d01, d21, FMul(d11, d20)), recip); const FloatV lambda2 = FMul(FNegScaleSub(d01, d20, FMul(d00, d21)), recip); #if EPA_DEBUG FStore(lambda1, &m_lambda1); FStore(lambda2, &m_lambda2); #endif const FloatV u = FSub(FOne(), FAdd(lambda1, lambda2)); closestA = V3ScaleAdd(pa0, u, V3ScaleAdd(pa1, lambda1, V3Scale(pa2, lambda2))); closestB = V3ScaleAdd(pb0, u, V3ScaleAdd(pb1, lambda1, V3Scale(pb2, lambda2))); } //ML: create adjacency informations for both facets PX_FORCE_INLINE bool Facet::link(const PxU32 edge0, Facet * PX_RESTRICT facet, const PxU32 edge1) { m_adjFacets[edge0] = facet; m_adjEdges[edge0] = PxToI8(edge1); facet->m_adjFacets[edge1] = this; facet->m_adjEdges[edge1] = PxToI8(edge0); return (m_indices[edge0] == facet->m_indices[incMod3(edge1)]) && (m_indices[incMod3(edge0)] == facet->m_indices[edge1]); } } } #endif
9,554
C
30.327869
172
0.684949
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKSimplex.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 "GuGJKSimplex.h" namespace physx { namespace Gu { using namespace aos; static Vec3V getClosestPtPointTriangle(Vec3V* PX_RESTRICT Q, const BoolVArg bIsOutside4, PxU32* indices, PxU32& size) { FloatV bestSqDist = FMax(); PxU32 _indices[3] = {0, 1, 2}; Vec3V closestPt = V3Zero(); if(BAllEqTTTT(BGetX(bIsOutside4))) { //use the original indices, size, v and w bestSqDist = closestPtPointTriangleBaryCentric(Q[0], Q[1], Q[2], indices, size, closestPt); } if(BAllEqTTTT(BGetY(bIsOutside4))) { PxU32 _size = 3; _indices[0] = 0; _indices[1] = 2; _indices[2] = 3; Vec3V tClosestPt; const FloatV sqDist = closestPtPointTriangleBaryCentric(Q[0], Q[2], Q[3], _indices, _size, tClosestPt); const BoolV con = FIsGrtr(bestSqDist, sqDist); if(BAllEqTTTT(con)) { closestPt = tClosestPt; bestSqDist = sqDist; indices[0] = _indices[0]; indices[1] = _indices[1]; indices[2] = _indices[2]; size = _size; } } if(BAllEqTTTT(BGetZ(bIsOutside4))) { PxU32 _size = 3; _indices[0] = 0; _indices[1] = 3; _indices[2] = 1; Vec3V tClosestPt; const FloatV sqDist = closestPtPointTriangleBaryCentric(Q[0], Q[3], Q[1], _indices, _size, tClosestPt); const BoolV con = FIsGrtr(bestSqDist, sqDist); if(BAllEqTTTT(con)) { closestPt = tClosestPt; bestSqDist = sqDist; indices[0] = _indices[0]; indices[1] = _indices[1]; indices[2] = _indices[2]; size = _size; } } if(BAllEqTTTT(BGetW(bIsOutside4))) { PxU32 _size = 3; _indices[0] = 1; _indices[1] = 3; _indices[2] = 2; Vec3V tClosestPt; const FloatV sqDist = closestPtPointTriangleBaryCentric(Q[1], Q[3], Q[2], _indices, _size, tClosestPt); const BoolV con = FIsGrtr(bestSqDist, sqDist); if(BAllEqTTTT(con)) { closestPt = tClosestPt; bestSqDist = sqDist; indices[0] = _indices[0]; indices[1] = _indices[1]; indices[2] = _indices[2]; size = _size; } } return closestPt; } PX_NOALIAS Vec3V closestPtPointTetrahedron(Vec3V* PX_RESTRICT Q, Vec3V* PX_RESTRICT A, Vec3V* PX_RESTRICT B, PxU32& size) { const FloatV eps = FLoad(1e-4f); const Vec3V a = Q[0]; const Vec3V b = Q[1]; const Vec3V c = Q[2]; const Vec3V d = Q[3]; //degenerated const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V n = V3Normalize(V3Cross(ab, ac)); const FloatV signDist = V3Dot(n, V3Sub(d, a)); if(FAllGrtr(eps, FAbs(signDist))) { size = 3; return closestPtPointTriangle(Q, A, B, size); } const BoolV bIsOutside4 = PointOutsideOfPlane4(a, b, c, d); if(BAllEqFFFF(bIsOutside4)) { //All inside return V3Zero(); } PxU32 indices[3] = {0, 1, 2}; const Vec3V closest = getClosestPtPointTriangle(Q, bIsOutside4, indices, size); const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]]; const Vec3V q2 = Q[indices[2]]; const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]]; const Vec3V a2 = A[indices[2]]; const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]]; const Vec3V b2 = B[indices[2]]; Q[0] = q0; Q[1] = q1; Q[2] = q2; A[0] = a0; A[1] = a1; A[2] = a2; B[0] = b0; B[1] = b1; B[2] = b2; return closest; } PX_NOALIAS Vec3V closestPtPointTetrahedron(Vec3V* PX_RESTRICT Q, Vec3V* PX_RESTRICT A, Vec3V* PX_RESTRICT B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, PxU32& size) { const FloatV eps = FLoad(1e-4f); const Vec3V zeroV = V3Zero(); const Vec3V a = Q[0]; const Vec3V b = Q[1]; const Vec3V c = Q[2]; const Vec3V d = Q[3]; //degenerated const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V n = V3Normalize(V3Cross(ab, ac)); const FloatV signDist = V3Dot(n, V3Sub(d, a)); if(FAllGrtr(eps, FAbs(signDist))) { size = 3; return closestPtPointTriangle(Q, A, B, aInd, bInd, size); } const BoolV bIsOutside4 = PointOutsideOfPlane4(a, b, c, d); if(BAllEqFFFF(bIsOutside4)) { //All inside return zeroV; } PxU32 indices[3] = {0, 1, 2}; const Vec3V closest = getClosestPtPointTriangle(Q, bIsOutside4, indices, size); const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]]; const Vec3V q2 = Q[indices[2]]; const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]]; const Vec3V a2 = A[indices[2]]; const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]]; const Vec3V b2 = B[indices[2]]; const PxI32 _aInd0 = aInd[indices[0]]; const PxI32 _aInd1 = aInd[indices[1]]; const PxI32 _aInd2 = aInd[indices[2]]; const PxI32 _bInd0 = bInd[indices[0]]; const PxI32 _bInd1 = bInd[indices[1]]; const PxI32 _bInd2 = bInd[indices[2]]; Q[0] = q0; Q[1] = q1; Q[2] = q2; A[0] = a0; A[1] = a1; A[2] = a2; B[0] = b0; B[1] = b1; B[2] = b2; aInd[0] = _aInd0; aInd[1] = _aInd1; aInd[2] = _aInd2; bInd[0] = _bInd0; bInd[1] = _bInd1; bInd[2] = _bInd2; return closest; } } }
6,611
C++
29.611111
173
0.659356
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKSimplex.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKSIMPLEX_H #define GU_GJKSIMPLEX_H #include "foundation/PxVecMath.h" #include "GuBarycentricCoordinates.h" #if (defined __GNUC__ && defined _DEBUG) #define PX_GJK_INLINE PX_INLINE #define PX_GJK_FORCE_INLINE PX_INLINE #else #define PX_GJK_INLINE PX_INLINE #define PX_GJK_FORCE_INLINE PX_FORCE_INLINE #endif namespace physx { namespace Gu { PX_NOALIAS aos::Vec3V closestPtPointTetrahedron(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, PxU32& size); PX_NOALIAS aos::Vec3V closestPtPointTetrahedron(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, PxU32& size); PX_NOALIAS PX_FORCE_INLINE aos::BoolV PointOutsideOfPlane4(const aos::Vec3VArg _a, const aos::Vec3VArg _b, const aos::Vec3VArg _c, const aos::Vec3VArg _d) { using namespace aos; const Vec4V zero = V4Load(0.f); const Vec3V ab = V3Sub(_b, _a); const Vec3V ac = V3Sub(_c, _a); const Vec3V ad = V3Sub(_d, _a); const Vec3V bd = V3Sub(_d, _b); const Vec3V bc = V3Sub(_c, _b); const Vec3V v0 = V3Cross(ab, ac); const Vec3V v1 = V3Cross(ac, ad); const Vec3V v2 = V3Cross(ad, ab); const Vec3V v3 = V3Cross(bd, bc); const FloatV signa0 = V3Dot(v0, _a); const FloatV signa1 = V3Dot(v1, _a); const FloatV signa2 = V3Dot(v2, _a); const FloatV signd3 = V3Dot(v3, _a); const FloatV signd0 = V3Dot(v0, _d); const FloatV signd1 = V3Dot(v1, _b); const FloatV signd2 = V3Dot(v2, _c); const FloatV signa3 = V3Dot(v3, _b); const Vec4V signa = V4Merge(signa0, signa1, signa2, signa3); const Vec4V signd = V4Merge(signd0, signd1, signd2, signd3); return V4IsGrtrOrEq(V4Mul(signa, signd), zero);//same side, outside of the plane } PX_NOALIAS PX_FORCE_INLINE aos::Vec3V closestPtPointSegment(aos::Vec3V* PX_RESTRICT Q, PxU32& size) { using namespace aos; const Vec3V a = Q[0]; const Vec3V b = Q[1]; //const Vec3V origin = V3Zero(); const FloatV zero = FZero(); const FloatV one = FOne(); //Test degenerated case const Vec3V ab = V3Sub(b, a); const FloatV denom = V3Dot(ab, ab); const Vec3V ap = V3Neg(a);//V3Sub(origin, a); const FloatV nom = V3Dot(ap, ab); const BoolV con = FIsGrtrOrEq(FEps(), denom);//FIsEq(denom, zero); //TODO - can we get rid of this branch? The problem is size, which isn't a vector! if(BAllEqTTTT(con)) { size = 1; return Q[0]; } /* const PxU32 count = BAllEq(con, bTrue); size = 2 - count;*/ const FloatV tValue = FClamp(FDiv(nom, denom), zero, one); return V3ScaleAdd(ab, tValue, a); } PX_FORCE_INLINE void getClosestPoint(const aos::Vec3V* PX_RESTRICT Q, const aos::Vec3V* PX_RESTRICT A, const aos::Vec3V* PX_RESTRICT B, const aos::Vec3VArg closest, aos::Vec3V& closestA, aos::Vec3V& closestB, const PxU32 size) { using namespace aos; switch(size) { case 1: { closestA = A[0]; closestB = B[0]; break; } case 2: { FloatV v; barycentricCoordinates(closest, Q[0], Q[1], v); const Vec3V av = V3Sub(A[1], A[0]); const Vec3V bv = V3Sub(B[1], B[0]); closestA = V3ScaleAdd(av, v, A[0]); closestB = V3ScaleAdd(bv, v, B[0]); break; } case 3: { //calculate the Barycentric of closest point p in the mincowsky sum FloatV v, w; barycentricCoordinates(closest, Q[0], Q[1], Q[2], v, w); const Vec3V av0 = V3Sub(A[1], A[0]); const Vec3V av1 = V3Sub(A[2], A[0]); const Vec3V bv0 = V3Sub(B[1], B[0]); const Vec3V bv1 = V3Sub(B[2], B[0]); closestA = V3Add(A[0], V3Add(V3Scale(av0, v), V3Scale(av1, w))); closestB = V3Add(B[0], V3Add(V3Scale(bv0, v), V3Scale(bv1, w))); } }; } PX_NOALIAS PX_GJK_FORCE_INLINE aos::FloatV closestPtPointTriangleBaryCentric(const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c, PxU32* PX_RESTRICT indices, PxU32& size, aos::Vec3V& closestPt) { using namespace aos; size = 3; const FloatV zero = FZero(); const FloatV eps = FEps(); const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V n = V3Cross(ab, ac); //ML: if the shape is oblong, the degeneracy test sometime can't catch the degeneracy in the tetraheron. Therefore, we need to make sure we still can ternimate with the previous //triangle by returning the maxinum distance. const FloatV nn = V3Dot(n, n); if (FAllEq(nn, zero)) return FMax(); //const FloatV va = FNegScaleSub(d5, d4, FMul(d3, d6));//edge region of BC //const FloatV vb = FNegScaleSub(d1, d6, FMul(d5, d2));//edge region of AC //const FloatV vc = FNegScaleSub(d3, d2, FMul(d1, d4));//edge region of AB //const FloatV va = V3Dot(n, V3Cross(b, c));//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a //const FloatV vb = V3Dot(n, V3Cross(c, a));//edge region of AC, signed area rac, v = S(rca)/S(abc) for b //const FloatV vc = V3Dot(n, V3Cross(a, b));//edge region of AB, signed area rab, w = S(rab)/S(abc) for c const VecCrossV crossA = V3PrepareCross(a); const VecCrossV crossB = V3PrepareCross(b); const VecCrossV crossC = V3PrepareCross(c); const Vec3V bCrossC = V3Cross(crossB, crossC); const Vec3V cCrossA = V3Cross(crossC, crossA); const Vec3V aCrossB = V3Cross(crossA, crossB); const FloatV va = V3Dot(n, bCrossC);//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a const FloatV vb = V3Dot(n, cCrossA);//edge region of AC, signed area rac, v = S(rca)/S(abc) for b const FloatV vc = V3Dot(n, aCrossB);//edge region of AB, signed area rab, w = S(rab)/S(abc) for c const BoolV isFacePoints = BAnd(FIsGrtrOrEq(va, zero), BAnd(FIsGrtrOrEq(vb, zero), FIsGrtrOrEq(vc, zero))); //face region if(BAllEqTTTT(isFacePoints)) { const FloatV t = FDiv(V3Dot(n, a), nn); const Vec3V q = V3Scale(n, t); closestPt = q; return V3Dot(q, q); } const Vec3V ap = V3Neg(a); const Vec3V bp = V3Neg(b); const Vec3V cp = V3Neg(c); const FloatV d1 = V3Dot(ab, ap); // snom const FloatV d2 = V3Dot(ac, ap); // tnom const FloatV d3 = V3Dot(ab, bp); // -sdenom const FloatV d4 = V3Dot(ac, bp); // unom = d4 - d3 const FloatV d5 = V3Dot(ab, cp); // udenom = d5 - d6 const FloatV d6 = V3Dot(ac, cp); // -tdenom const FloatV unom = FSub(d4, d3); const FloatV udenom = FSub(d5, d6); size = 2; //check if p in edge region of AB const BoolV con30 = FIsGrtrOrEq(zero, vc); const BoolV con31 = FIsGrtrOrEq(d1, zero); const BoolV con32 = FIsGrtrOrEq(zero, d3); const BoolV con3 = BAnd(con30, BAnd(con31, con32));//edge AB region if(BAllEqTTTT(con3)) { const FloatV toRecipAB = FSub(d1, d3); const FloatV recipAB = FSel(FIsGrtr(FAbs(toRecipAB), eps), FRecip(toRecipAB), zero); const FloatV t = FMul(d1, recipAB); const Vec3V q = V3ScaleAdd(ab, t, a); closestPt = q; return V3Dot(q, q); } //check if p in edge region of BC const BoolV con40 = FIsGrtrOrEq(zero, va); const BoolV con41 = FIsGrtrOrEq(d4, d3); const BoolV con42 = FIsGrtrOrEq(d5, d6); const BoolV con4 = BAnd(con40, BAnd(con41, con42)); //edge BC region if(BAllEqTTTT(con4)) { const Vec3V bc = V3Sub(c, b); const FloatV toRecipBC = FAdd(unom, udenom); const FloatV recipBC = FSel(FIsGrtr(FAbs(toRecipBC), eps), FRecip(toRecipBC), zero); const FloatV t = FMul(unom, recipBC); indices[0] = indices[1]; indices[1] = indices[2]; const Vec3V q = V3ScaleAdd(bc, t, b); closestPt = q; return V3Dot(q, q); } //check if p in edge region of AC const BoolV con50 = FIsGrtrOrEq(zero, vb); const BoolV con51 = FIsGrtrOrEq(d2, zero); const BoolV con52 = FIsGrtrOrEq(zero, d6); const BoolV con5 = BAnd(con50, BAnd(con51, con52));//edge AC region if(BAllEqTTTT(con5)) { const FloatV toRecipAC = FSub(d2, d6); const FloatV recipAC = FSel(FIsGrtr(FAbs(toRecipAC), eps), FRecip(toRecipAC), zero); const FloatV t = FMul(d2, recipAC); indices[1]=indices[2]; const Vec3V q = V3ScaleAdd(ac, t, a); closestPt = q; return V3Dot(q, q); } size = 1; //check if p in vertex region outside a const BoolV con00 = FIsGrtrOrEq(zero, d1); // snom <= 0 const BoolV con01 = FIsGrtrOrEq(zero, d2); // tnom <= 0 const BoolV con0 = BAnd(con00, con01); // vertex region a if(BAllEqTTTT(con0)) { closestPt = a; return V3Dot(a, a); } //check if p in vertex region outside b const BoolV con10 = FIsGrtrOrEq(d3, zero); const BoolV con11 = FIsGrtrOrEq(d3, d4); const BoolV con1 = BAnd(con10, con11); // vertex region b if(BAllEqTTTT(con1)) { indices[0] = indices[1]; closestPt = b; return V3Dot(b, b); } //p is in vertex region outside c indices[0] = indices[2]; closestPt = c; return V3Dot(c, c); } PX_NOALIAS PX_GJK_FORCE_INLINE aos::Vec3V closestPtPointTriangle(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* A, aos::Vec3V* B, PxU32& size) { using namespace aos; size = 3; const FloatV eps = FEps(); const Vec3V a = Q[0]; const Vec3V b = Q[1]; const Vec3V c = Q[2]; const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V signArea = V3Cross(ab, ac);//0.5*(abXac) const FloatV area = V3Dot(signArea, signArea); if(FAllGrtrOrEq(eps, area)) { //degenerate size = 2; return closestPtPointSegment(Q, size); } PxU32 _size; PxU32 indices[3]={0, 1, 2}; Vec3V closestPt; closestPtPointTriangleBaryCentric(a, b, c, indices, _size, closestPt); if(_size != 3) { const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]]; const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]]; const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]]; Q[0] = q0; Q[1] = q1; A[0] = a0; A[1] = a1; B[0] = b0; B[1] = b1; size = _size; } return closestPt; } PX_NOALIAS PX_GJK_FORCE_INLINE aos::Vec3V closestPtPointTriangle(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* A, aos::Vec3V* B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, PxU32& size) { using namespace aos; size = 3; const FloatV eps = FEps(); const Vec3V a = Q[0]; const Vec3V b = Q[1]; const Vec3V c = Q[2]; const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V signArea = V3Cross(ab, ac);//0.5*(abXac) const FloatV area = V3Dot(signArea, signArea); if(FAllGrtrOrEq(eps, area)) { //degenerate size = 2; return closestPtPointSegment(Q, size); } PxU32 _size; PxU32 indices[3]={0, 1, 2}; Vec3V closestPt; closestPtPointTriangleBaryCentric(a, b, c, indices, _size, closestPt); if(_size != 3) { const Vec3V q0 = Q[indices[0]]; const Vec3V q1 = Q[indices[1]]; const Vec3V a0 = A[indices[0]]; const Vec3V a1 = A[indices[1]]; const Vec3V b0 = B[indices[0]]; const Vec3V b1 = B[indices[1]]; const PxI32 aInd0 = aInd[indices[0]]; const PxI32 aInd1 = aInd[indices[1]]; const PxI32 bInd0 = bInd[indices[0]]; const PxI32 bInd1 = bInd[indices[1]]; Q[0] = q0; Q[1] = q1; A[0] = a0; A[1] = a1; B[0] = b0; B[1] = b1; aInd[0] = aInd0; aInd[1] = aInd1; bInd[0] = bInd0; bInd[1] = bInd1; size = _size; } return closestPt; } PX_NOALIAS PX_FORCE_INLINE aos::Vec3V GJKCPairDoSimplex(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, const aos::Vec3VArg support, PxU32& size) { using namespace aos; //const PxU32 tempSize = size; //calculate a closest from origin to the simplex switch(size) { case 1: { return support; } case 2: { return closestPtPointSegment(Q, size); } case 3: { return closestPtPointTriangle(Q, A, B, size); } case 4: return closestPtPointTetrahedron(Q, A, B, size); default: PX_ASSERT(0); } return support; } PX_NOALIAS PX_FORCE_INLINE aos::Vec3V GJKCPairDoSimplex(aos::Vec3V* PX_RESTRICT Q, aos::Vec3V* PX_RESTRICT A, aos::Vec3V* PX_RESTRICT B, PxI32* PX_RESTRICT aInd, PxI32* PX_RESTRICT bInd, const aos::Vec3VArg support, PxU32& size) { using namespace aos; //const PxU32 tempSize = size; //calculate a closest from origin to the simplex switch(size) { case 1: { return support; } case 2: { return closestPtPointSegment(Q, size); } case 3: { return closestPtPointTriangle(Q, A, B, aInd, bInd, size); } case 4: return closestPtPointTetrahedron(Q, A, B, aInd, bInd, size); default: PX_ASSERT(0); } return support; } } } #endif
14,055
C
30.305122
227
0.661615
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecPlane.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_PLANE_H #define GU_VEC_PLANE_H /** \addtogroup geomutils @{ */ #include "foundation/PxVec3.h" #include "foundation/PxPlane.h" #include "foundation/PxVecMath.h" /** \brief Representation of a plane. Plane equation used: a*x + b*y + c*z + d = 0 */ namespace physx { namespace Gu { class PlaneV { public: /** \brief Constructor */ PX_FORCE_INLINE PlaneV() { } /** \brief Constructor from a normal and a distance */ PX_FORCE_INLINE PlaneV(const aos::FloatVArg nx, const aos::FloatVArg ny, const aos::FloatVArg nz, const aos::FloatVArg _d) { set(nx, ny, nz, _d); } PX_FORCE_INLINE PlaneV(const PxPlane& plane) { using namespace aos; const Vec3V _n = V3LoadU(plane.n); const FloatV _d = FLoad(plane.d); nd = V4SetW(Vec4V_From_Vec3V(_n), _d); } /** \brief Constructor from three points */ PX_FORCE_INLINE PlaneV(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2) { set(p0, p1, p2); } /** \brief Constructor from a normal and a distance */ PX_FORCE_INLINE PlaneV(const aos::Vec3VArg _n, const aos::FloatVArg _d) { nd = aos::V4SetW(aos::Vec4V_From_Vec3V(_n), _d); } /** \brief Copy constructor */ PX_FORCE_INLINE PlaneV(const PlaneV& plane) : nd(plane.nd) { } /** \brief Destructor */ PX_FORCE_INLINE ~PlaneV() { } /** \brief Sets plane to zero. */ PX_FORCE_INLINE PlaneV& setZero() { nd = aos::V4Zero(); return *this; } PX_FORCE_INLINE PlaneV& set(const aos::FloatVArg nx, const aos::FloatVArg ny, const aos::FloatVArg nz, const aos::FloatVArg _d) { using namespace aos; const Vec3V n= V3Merge(nx, ny, nz); nd = V4SetW(Vec4V_From_Vec3V(n), _d); return *this; } PX_FORCE_INLINE PlaneV& set(const aos::Vec3VArg _normal, aos::FloatVArg _d) { nd = aos::V4SetW(aos::Vec4V_From_Vec3V(_normal), _d); return *this; } /** \brief Computes the plane equation from 3 points. */ PlaneV& set(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2) { using namespace aos; const Vec3V edge0 = V3Sub(p1, p0); const Vec3V edge1 = V3Sub(p2, p0); const Vec3V n = V3Normalize(V3Cross(edge0, edge1)); // See comments in set() for computation of d const FloatV d = FNeg(V3Dot(p0, n)); nd = V4SetW(Vec4V_From_Vec3V(n), d); return *this; } /*** \brief Computes distance, assuming plane is normalized \sa normalize */ PX_FORCE_INLINE aos::FloatV distance(const aos::Vec3VArg p) const { // Valid for plane equation a*x + b*y + c*z + d = 0 using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return FAdd(V3Dot(p, n), V4GetW(nd)); } PX_FORCE_INLINE aos::BoolV belongs(const aos::Vec3VArg p) const { using namespace aos; const FloatV eps = FLoad(1.0e-7f); return FIsGrtr(eps, FAbs(distance(p))); } /** \brief projects p into the plane */ PX_FORCE_INLINE aos::Vec3V project(const aos::Vec3VArg p) const { // Pretend p is on positive side of plane, i.e. plane.distance(p)>0. // To project the point we have to go in a direction opposed to plane's normal, i.e.: using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return V3Sub(p, V3Scale(n, V4GetW(nd))); } PX_FORCE_INLINE aos::FloatV signedDistanceHessianNormalForm(const aos::Vec3VArg point) const { using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return FAdd(V3Dot(n, point), V4GetW(nd)); } PX_FORCE_INLINE aos::Vec3V getNormal() const { return aos::Vec3V_From_Vec4V(nd); } PX_FORCE_INLINE aos::FloatV getSignDist() const { return aos::V4GetW(nd); } /** \brief find an arbitrary point in the plane */ PX_FORCE_INLINE aos::Vec3V pointInPlane() const { // Project origin (0,0,0) to plane: // (0) - normal * distance(0) = - normal * ((p|(0)) + d) = -normal*d using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); return V3Neg(V3Scale(n, V4GetW(nd))); } PX_FORCE_INLINE void normalize() { using namespace aos; const Vec3V n = Vec3V_From_Vec4V(nd); const FloatV denom = FRecip(V3Length(n)); V4Scale(nd, denom); } aos::Vec4V nd; //!< The normal to the plan , w store the distance from the origin }; } } /** @} */ #endif
5,975
C
25.798206
129
0.674142
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuEPA.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 "GuEPA.h" #include "GuEPAFacet.h" #include "GuGJKSimplex.h" #include "CmPriorityQueue.h" #include "foundation/PxAllocator.h" namespace physx { namespace Gu { using namespace aos; class ConvexV; struct FacetDistanceComparator { bool operator()(const Facet* left, const Facet* right) const { return *left < *right; } }; #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class EPA { public: EPA(){} GjkStatus PenetrationDepth(const GjkConvex& a, const GjkConvex& b, const aos::Vec3V* PX_RESTRICT A, const aos::Vec3V* PX_RESTRICT B, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output); bool expandPoint(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound); bool expandSegment(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound); bool expandTriangle(PxI32& numVerts, const FloatVArg upperBound); Facet* addFacet(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::FloatVArg upper); bool originInTetrahedron(const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3, const aos::Vec3VArg p4); Cm::InlinePriorityQueue<Facet*, MaxFacets, FacetDistanceComparator> heap; aos::Vec3V aBuf[MaxSupportPoints]; aos::Vec3V bBuf[MaxSupportPoints]; Facet facetBuf[MaxFacets]; EdgeBuffer edgeBuffer; EPAFacetManager facetManager; private: PX_NOCOPY(EPA) }; #if PX_VC #pragma warning(pop) #endif PX_FORCE_INLINE bool EPA::originInTetrahedron(const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3, const aos::Vec3VArg p4) { using namespace aos; return BAllEqFFFF(PointOutsideOfPlane4(p1, p2, p3, p4)) == 1; } static PX_FORCE_INLINE void doSupport(const GjkConvex& a, const GjkConvex& b, const aos::Vec3VArg dir, aos::Vec3V& supportA, aos::Vec3V& supportB, aos::Vec3V& support) { const Vec3V tSupportA = a.support(V3Neg(dir)); const Vec3V tSupportB = b.support(dir); //avoid LHS supportA = tSupportA; supportB = tSupportB; support = V3Sub(tSupportA, tSupportB); } GjkStatus epaPenetration(const GjkConvex& a, const GjkConvex& b, const PxU8* PX_RESTRICT aInd, const PxU8* PX_RESTRICT bInd, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output) { PX_ASSERT(size > 0 && size <=4); Vec3V A[4]; Vec3V B[4]; //ML: we construct a simplex based on the gjk simplex indices for(PxU32 i=0; i<size; ++i) { A[i] = a.supportPoint(aInd[i]); B[i] = b.supportPoint(bInd[i]); } EPA epa; return epa.PenetrationDepth(a, b, A, B, size, takeCoreShape, tolerenceLength, output); } GjkStatus epaPenetration(const GjkConvex& a, const GjkConvex& b, const aos::Vec3V* PX_RESTRICT aPnt, const aos::Vec3V* PX_RESTRICT bPnt, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output) { PX_ASSERT(size > 0 && size <=4); const Vec3V* A = aPnt; const Vec3V* B = bPnt; EPA epa; return epa.PenetrationDepth(a, b, A, B, size, takeCoreShape, tolerenceLength, output); } //ML: this function returns the signed distance of a point to a plane PX_FORCE_INLINE aos::FloatV Facet::getPlaneDist(const aos::Vec3VArg p, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf) const { const Vec3V pa0(aBuf[m_indices[0]]); const Vec3V pb0(bBuf[m_indices[0]]); const Vec3V p0 = V3Sub(pa0, pb0); return V3Dot(m_planeNormal, V3Sub(p, p0)); } //ML: This function: // (1)calculates the distance from orign((0, 0, 0)) to a triangle plane // (2) rejects triangle if the triangle is degenerate (two points are identical) // (3) rejects triangle to be added into the heap if the plane distance is large than upper aos::BoolV Facet::isValid2(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, const aos::FloatVArg upper) { using namespace aos; const FloatV eps = FEps(); const Vec3V pa0(aBuf[i0]); const Vec3V pa1(aBuf[i1]); const Vec3V pa2(aBuf[i2]); const Vec3V pb0(bBuf[i0]); const Vec3V pb1(bBuf[i1]); const Vec3V pb2(bBuf[i2]); const Vec3V p0 = V3Sub(pa0, pb0); const Vec3V p1 = V3Sub(pa1, pb1); const Vec3V p2 = V3Sub(pa2, pb2); const Vec3V v0 = V3Sub(p1, p0); const Vec3V v1 = V3Sub(p2, p0); const Vec3V denormalizedNormal = V3Cross(v0, v1); FloatV norValue = V3Dot(denormalizedNormal, denormalizedNormal); //if norValue < eps, this triangle is degenerate const BoolV con = FIsGrtr(norValue, eps); norValue = FSel(con, norValue, FOne()); const Vec3V planeNormal = V3Scale(denormalizedNormal, FRsqrt(norValue)); const FloatV planeDist = V3Dot(planeNormal, p0); m_planeNormal = planeNormal; FStore(planeDist, &m_planeDist); return BAnd(con, FIsGrtrOrEq(upper, planeDist)); } //ML: if the triangle is valid(not degenerate and within lower and upper bound), we need to add it into the heap. Otherwise, we just return //the triangle so that the facet can be linked to other facets in the expanded polytope. Facet* EPA::addFacet(const PxU32 i0, const PxU32 i1, const PxU32 i2, const aos::FloatVArg upper) { using namespace aos; PX_ASSERT(i0 != i1 && i0 != i2 && i1 != i2); //ML: we move the control in the calling code so we don't need to check weather we will run out of facets or not PX_ASSERT(facetManager.getNumUsedID() < MaxFacets); const PxU32 facetId = facetManager.getNewID(); PxPrefetchLine(&facetBuf[facetId], 128); Facet * facet = PX_PLACEMENT_NEW(&facetBuf[facetId],Facet(i0, i1, i2)); facet->m_FacetId = PxU8(facetId); const BoolV validTriangle = facet->isValid2(i0, i1, i2, aBuf, bBuf, upper); if(BAllEqTTTT(validTriangle)) { heap.push(facet); facet->m_inHeap = true; } else { facet->m_inHeap = false; } return facet; } //ML: this function performs a flood fill over the boundary of the current polytope. void Facet::silhouette(const PxU32 _index, const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager) { using namespace aos; const FloatV zero = FZero(); Edge stack[MaxFacets]; stack[0] = Edge(this, _index); PxI32 size = 1; while(size--) { Facet* const PX_RESTRICT f = stack[size].m_facet; const PxU32 index = stack[size].m_index; PX_ASSERT(f->Valid()); if(!f->m_obsolete) { //ML: if the point is above the facet, the facet has an reflex edge, which will make the polytope concave. Therefore, we need to //remove this facet and make sure the expanded polytope is convex. const FloatV pointPlaneDist = f->getPlaneDist(w, aBuf, bBuf); if(FAllGrtr(zero, pointPlaneDist)) { //ML: facet isn't visible from w (we don't have a reflex edge), this facet will be on the boundary and part of the new polytope so that //we will push it into our edgeBuffer if(!edgeBuffer.Insert(f, index)) return; } else { //ML:facet is visible from w, therefore, we need to remove this facet from the heap and push its adjacent facets onto the stack f->m_obsolete = true; // Facet is visible from w const PxU32 next(incMod3(index)); const PxU32 next2(incMod3(next)); stack[size++] = Edge(f->m_adjFacets[next2],PxU32(f->m_adjEdges[next2])); stack[size++] = Edge(f->m_adjFacets[next], PxU32(f->m_adjEdges[next])); PX_ASSERT(size <= MaxFacets); if(!f->m_inHeap) { //if the facet isn't in the heap, we can release that memory manager.deferredFreeID(f->m_FacetId); } } } } } //ML: this function perform flood fill for the adjancent facet and store the boundary facet into the edgeBuffer void Facet::silhouette(const aos::Vec3VArg w, const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, EdgeBuffer& edgeBuffer, EPAFacetManager& manager) { m_obsolete = true; for(PxU32 a = 0; a < 3; ++a) { m_adjFacets[a]->silhouette(PxU32(m_adjEdges[a]), w, aBuf, bBuf, edgeBuffer, manager); } } bool EPA::expandPoint(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound) { const Vec3V x = V3UnitX(); Vec3V q0 = V3Sub(aBuf[0], bBuf[0]); Vec3V q1; doSupport(a, b, x, aBuf[1], bBuf[1], q1); if (V3AllEq(q0, q1)) return false; return expandSegment(a, b, numVerts, upperBound); } //ML: this function use the segement to create a triangle bool EPA::expandSegment(const GjkConvex& a, const GjkConvex& b, PxI32& numVerts, const FloatVArg upperBound) { const Vec3V q0 = V3Sub(aBuf[0], bBuf[0]); const Vec3V q1 = V3Sub(aBuf[1], bBuf[1]); const Vec3V v = V3Sub(q1, q0); const Vec3V absV = V3Abs(v); const FloatV x = V3GetX(absV); const FloatV y = V3GetY(absV); const FloatV z = V3GetZ(absV); Vec3V axis = V3UnitX(); const BoolV con0 = BAnd(FIsGrtr(x, y), FIsGrtr(z, y)); if (BAllEqTTTT(con0)) { axis = V3UnitY(); } else if(FAllGrtr(x, z)) { axis = V3UnitZ(); } const Vec3V n = V3Normalize(V3Cross(axis, v)); Vec3V q2; doSupport(a, b, n, aBuf[2], bBuf[2], q2); return expandTriangle(numVerts, upperBound); } bool EPA::expandTriangle(PxI32& numVerts, const FloatVArg upperBound) { numVerts = 3; Facet * PX_RESTRICT f0 = addFacet(0, 1, 2, upperBound); Facet * PX_RESTRICT f1 = addFacet(1, 0, 2, upperBound); if(heap.empty()) return false; f0->link(0, f1, 0); f0->link(1, f1, 2); f0->link(2, f1, 1); return true; } //ML: this function calculates contact information. If takeCoreShape flag is true, this means the two closest points will be on the core shape used in the support functions. //For example, we treat sphere/capsule as a point/segment in the support function for GJK/EPA, so that the core shape for sphere/capsule is a point/segment. For PCM, we need //to take the point from the core shape because this will allows us recycle the contacts more stably. For SQ sweeps, we need to take the point on the surface of the sphere/capsule //when we calculate MTD because this is what will be reported to the user. Therefore, the takeCoreShape flag will be set to be false in SQ. static void calculateContactInformation(const aos::Vec3V* PX_RESTRICT aBuf, const aos::Vec3V* PX_RESTRICT bBuf, Facet* facet, const GjkConvex& a, const GjkConvex& b, const bool takeCoreShape, GjkOutput& output) { const FloatV zero = FZero(); Vec3V _pa, _pb; facet->getClosestPoint(aBuf, bBuf, _pa, _pb); //dist > 0 means two shapes are penetrated. If dist < 0(when origin isn't inside the polytope), two shapes status are unknown const FloatV dist = FAbs(facet->getPlaneDist()); const Vec3V planeNormal = V3Neg(facet->getPlaneNormal()); if(takeCoreShape) { output.closestA = _pa; output.closestB = _pb; output.normal = planeNormal; output.penDep = FNeg(dist); } else { //for sphere/capusule to take the surface point const BoolV aQuadratic = a.isMarginEqRadius(); const BoolV bQuadratic = b.isMarginEqRadius(); const FloatV marginA = FSel(aQuadratic, a.getMargin(), zero); const FloatV marginB = FSel(bQuadratic, b.getMargin(), zero); const FloatV sumMargin = FAdd(marginA, marginB); output.closestA = V3NegScaleSub(planeNormal, marginA, _pa); output.closestB = V3ScaleAdd(planeNormal, marginB, _pb); output.normal = planeNormal; output.penDep = FNeg(FAdd(dist, sumMargin)); } } //ML: This function returns one of three status codes: //(1)EPA_FAIL: the algorithm failed to create a valid polytope(the origin wasn't inside the polytope) from the input simplex //(2)EPA_CONTACT : the algorithm found the MTD and converged successfully. //(3)EPA_DEGENERATE: the algorithm cannot make further progress and the result is unknown. GjkStatus EPA::PenetrationDepth(const GjkConvex& a, const GjkConvex& b, const aos::Vec3V* PX_RESTRICT A, const aos::Vec3V* PX_RESTRICT B, const PxU8 size, const bool takeCoreShape, const FloatV tolerenceLength, GjkOutput& output) { using namespace aos; PX_UNUSED(tolerenceLength); PxPrefetchLine(&facetBuf[0]); PxPrefetchLine(&facetBuf[0], 128); const FloatV zero = FZero(); const FloatV _max = FMax(); FloatV upper_bound(_max); aBuf[0]=A[0]; aBuf[1]=A[1]; aBuf[2]=A[2]; aBuf[3]=A[3]; bBuf[0]=B[0]; bBuf[1]=B[1]; bBuf[2]=B[2]; bBuf[3]=B[3]; PxI32 numVertsLocal = 0; heap.clear(); //if the simplex isn't a tetrahedron, we need to construct one before we can expand it switch (size) { case 1: { // Touching contact. Yes, we have a collision and the penetration will be zero if(!expandPoint(a, b, numVertsLocal, upper_bound)) return EPA_FAIL; break; } case 2: { // We have a line segment inside the Minkowski sum containing the // origin. we need to construct two back to back triangles which link to each other if(!expandSegment(a, b, numVertsLocal, upper_bound)) return EPA_FAIL; break; } case 3: { // We have a triangle inside the Minkowski sum containing // the origin. We need to construct two back to back triangles which link to each other if(!expandTriangle(numVertsLocal, upper_bound)) return EPA_FAIL; break; } case 4: { //check for input face normal. All face normals in this tetrahedron should be all pointing either inwards or outwards. If all face normals are pointing outward, we are good to go. Otherwise, we need to //shuffle the input vertexes and make sure all face normals are pointing outward const Vec3V pa0(aBuf[0]); const Vec3V pa1(aBuf[1]); const Vec3V pa2(aBuf[2]); const Vec3V pa3(aBuf[3]); const Vec3V pb0(bBuf[0]); const Vec3V pb1(bBuf[1]); const Vec3V pb2(bBuf[2]); const Vec3V pb3(bBuf[3]); const Vec3V p0 = V3Sub(pa0, pb0); const Vec3V p1 = V3Sub(pa1, pb1); const Vec3V p2 = V3Sub(pa2, pb2); const Vec3V p3 = V3Sub(pa3, pb3); const Vec3V v1 = V3Sub(p1, p0); const Vec3V v2 = V3Sub(p2, p0); const Vec3V planeNormal = V3Normalize(V3Cross(v1, v2)); const FloatV signDist = V3Dot(planeNormal, V3Sub(p3, p0)); if (FAllGrtr(signDist, zero)) { //shuffle the input vertexes const Vec3V tempA0 = aBuf[2]; const Vec3V tempB0 = bBuf[2]; aBuf[2] = aBuf[1]; bBuf[2] = bBuf[1]; aBuf[1] = tempA0; bBuf[1] = tempB0; } Facet * PX_RESTRICT f0 = addFacet(0, 1, 2, upper_bound); Facet * PX_RESTRICT f1 = addFacet(0, 3, 1, upper_bound); Facet * PX_RESTRICT f2 = addFacet(0, 2, 3, upper_bound); Facet * PX_RESTRICT f3 = addFacet(1, 3, 2, upper_bound); if (heap.empty()) return EPA_FAIL; #if EPA_DEBUG PX_ASSERT(f0->m_planeDist >= -1e-2f); PX_ASSERT(f1->m_planeDist >= -1e-2f); PX_ASSERT(f2->m_planeDist >= -1e-2f); PX_ASSERT(f3->m_planeDist >= -1e-2f); #endif f0->link(0, f1, 2); f0->link(1, f3, 2); f0->link(2, f2, 0); f1->link(0, f2, 2); f1->link(1, f3, 0); f2->link(1, f3, 1); numVertsLocal = 4; break; } } const FloatV minMargin = FMin(a.getMinMargin(), b.getMinMargin()); const FloatV eps = FMul(minMargin, FLoad(0.1f)); Facet* PX_RESTRICT facet = NULL; Vec3V tempa, tempb, q; do { facetManager.processDeferredIds(); facet = heap.pop(); //get the shortest distance triangle of origin from the list facet->m_inHeap = false; if (!facet->isObsolete()) { PxPrefetchLine(edgeBuffer.m_pEdges); PxPrefetchLine(edgeBuffer.m_pEdges,128); PxPrefetchLine(edgeBuffer.m_pEdges,256); const Vec3V planeNormal = facet->getPlaneNormal(); const FloatV planeDist = facet->getPlaneDist(); tempa = a.support(planeNormal); tempb = b.support(V3Neg(planeNormal)); q = V3Sub(tempa, tempb); PxPrefetchLine(&aBuf[numVertsLocal],128); PxPrefetchLine(&bBuf[numVertsLocal],128); //calculate the distance from support point to the origin along the plane normal. Because the support point is search along //the plane normal, which means the distance should be positive. However, if the origin isn't contained in the polytope, dist //might be negative const FloatV dist = V3Dot(q, planeNormal); const BoolV con0 = FIsGrtrOrEq(eps, FAbs(FSub(dist, planeDist))); if (BAllEqTTTT(con0)) { calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); if (takeCoreShape) { const FloatV toleranceEps = FMul(FLoad(1e-3f), tolerenceLength); const Vec3V dif = V3Sub(output.closestA, output.closestB); const FloatV pen = FAdd(FAbs(output.penDep), toleranceEps); const FloatV sqDif = V3Dot(dif, dif); const FloatV length = FSel(FIsGrtr(sqDif, zero), FSqrt(sqDif), zero); if (FAllGrtr(length, pen)) return EPA_DEGENERATE; } return EPA_CONTACT; } //update the upper bound to the minimum between existing upper bound and the distance upper_bound = FMin(upper_bound, dist); aBuf[numVertsLocal]=tempa; bBuf[numVertsLocal]=tempb; const PxU32 index =PxU32(numVertsLocal++); // Compute the silhouette cast by the new vertex // Note that the new vertex is on the positive side // of the current facet, so the current facet will // not be in the polytope. Start local search // from this facet. edgeBuffer.MakeEmpty(); facet->silhouette(q, aBuf, bBuf, edgeBuffer, facetManager); if (!edgeBuffer.IsValid()) { calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); return EPA_DEGENERATE; } Edge* PX_RESTRICT edge=edgeBuffer.Get(0); PxU32 bufferSize=edgeBuffer.Size(); //check to see whether we have enough space in the facet manager to create new facets if(bufferSize > facetManager.getNumRemainingIDs()) { calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); return EPA_DEGENERATE; } Facet *firstFacet = addFacet(edge->getTarget(), edge->getSource(),index, upper_bound); PX_ASSERT(firstFacet); firstFacet->link(0, edge->getFacet(), edge->getIndex()); Facet * PX_RESTRICT lastFacet = firstFacet; #if EPA_DEBUG bool degenerate = false; for(PxU32 i=1; (i<bufferSize) && (!degenerate); ++i) { edge=edgeBuffer.Get(i); Facet* PX_RESTRICT newFacet = addFacet(edge->getTarget(), edge->getSource(),index, upper_bound); PX_ASSERT(newFacet); const bool b0 = newFacet->link(0, edge->getFacet(), edge->getIndex()); const bool b1 = newFacet->link(2, lastFacet, 1); degenerate = degenerate || !b0 || !b1; lastFacet = newFacet; } if (degenerate) PxDebugBreak(); #else for (PxU32 i = 1; i<bufferSize; ++i) { edge = edgeBuffer.Get(i); Facet* PX_RESTRICT newFacet = addFacet(edge->getTarget(), edge->getSource(), index, upper_bound); newFacet->link(0, edge->getFacet(), edge->getIndex()); newFacet->link(2, lastFacet, 1); lastFacet = newFacet; } #endif firstFacet->link(2, lastFacet, 1); } facetManager.freeID(facet->m_FacetId); } while((heap.size() > 0) && FAllGrtr(upper_bound, heap.top()->getPlaneDist()) && numVertsLocal != MaxSupportPoints); calculateContactInformation(aBuf, bBuf, facet, a, b, takeCoreShape, output); return EPA_DEGENERATE; } } }
21,172
C++
32.93109
211
0.687512
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecTetrahedron.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_TETRAHEDRON_H #define GU_VEC_TETRAHEDRON_H /** \addtogroup geomutils @{ */ #include "GuVecConvex.h" #include "GuConvexSupportTable.h" #include "GuDistancePointTriangle.h" namespace physx { namespace Gu { class TetrahedronV : public ConvexV { public: /** \brief Constructor */ PX_FORCE_INLINE TetrahedronV() : ConvexV(ConvexType::eTETRAHEDRON) { margin = 0.02f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Constructor \param[in] p0 Point 0 \param[in] p1 Point 1 \param[in] p2 Point 2 \param[in] p3 Point 3 */ PX_FORCE_INLINE TetrahedronV(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2, const aos::Vec3VArg p3) : ConvexV(ConvexType::eTETRAHEDRON) { using namespace aos; //const FloatV zero = FZero(); const FloatV num = FLoad(0.25f); center = V3Scale(V3Add(V3Add(p0, p1), V3Add(p2, p3)), num); //vertsX store all the x elements form those four point vertsX = V4SetW(V4SetZ(V4SetY(Vec4V_From_Vec3V(p0), V3GetX(p1)), V3GetX(p2)), V3GetX(p3)); //vertsY store all the y elements from those four point vertsY = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetY(p0)), V3GetY(p1)), V3GetY(p2)), V3GetY(p3)); //vertsZ store all the z elements from those four point vertsZ = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetZ(p0)), V3GetZ(p1)), V3GetZ(p2)), V3GetZ(p3)); verts[0] = p0; verts[1] = p1; verts[2] = p2; verts[3] = p3; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } PX_FORCE_INLINE TetrahedronV(const PxVec3* pts) : ConvexV(ConvexType::eTETRAHEDRON) { using namespace aos; const Vec3V p0 = V3LoadU(pts[0]); const Vec3V p1 = V3LoadU(pts[1]); const Vec3V p2 = V3LoadU(pts[2]); const Vec3V p3 = V3LoadU(pts[3]); const FloatV num = FLoad(0.25f); center = V3Scale(V3Add(V3Add(p0, p1), V3Add(p2, p3)), num); vertsX = V4SetW(V4SetZ(V4SetY(Vec4V_From_Vec3V(p0), V3GetX(p1)), V3GetX(p2)), V3GetX(p3)); vertsY = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetY(p0)), V3GetY(p1)), V3GetY(p2)), V3GetY(p3)); vertsZ = V4SetW(V4SetZ(V4SetY(V4Splat(V3GetZ(p0)), V3GetZ(p1)), V3GetZ(p2)), V3GetZ(p3)); verts[0] = p0; verts[1] = p1; verts[2] = p2; verts[3] = p3; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Copy constructor \param[in] tetrahedron Tetrahedron to copy */ PX_FORCE_INLINE TetrahedronV(const Gu::TetrahedronV& tetrahedron) : ConvexV(ConvexType::eTETRAHEDRON) { using namespace aos; vertsX = tetrahedron.vertsX; vertsY = tetrahedron.vertsY; vertsZ = tetrahedron.vertsZ; verts[0] = tetrahedron.verts[0]; verts[1] = tetrahedron.verts[1]; verts[2] = tetrahedron.verts[2]; verts[3] = tetrahedron.verts[3]; center = tetrahedron.center; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Destructor */ PX_FORCE_INLINE ~TetrahedronV() { } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FMax(); } PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { using namespace aos; Vec3V offset = V3Sub(_center, center); center = _center; vertsX = V4Add(vertsX, V4Splat(V3GetX(offset))); vertsY = V4Add(vertsY, V4Splat(V3GetY(offset))); vertsZ = V4Add(vertsZ, V4Splat(V3GetZ(offset))); verts[0] = V3Add(verts[0], offset); verts[1] = V3Add(verts[1], offset); verts[2] = V3Add(verts[2], offset); verts[3] = V3Add(verts[3], offset); } PX_FORCE_INLINE aos::Vec4V getProjection(const aos::Vec3VArg dir) const { using namespace aos; const Vec4V dx = V4Scale(vertsX, V3GetX(dir)); const Vec4V dy = V4Scale(vertsY, V3GetY(dir)); const Vec4V dz = V4Scale(vertsZ, V3GetZ(dir)); return V4Add(dx, V4Add(dy, dz)); } //dir is in local space, verts in the local space PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir) const { using namespace aos; const Vec4V d = getProjection(dir); const FloatV d0 = V4GetX(d); const FloatV d1 = V4GetY(d); const FloatV d2 = V4GetZ(d); const FloatV d3 = V4GetW(d); const BoolV con0 = BAnd(BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)), FIsGrtr(d0, d3)); const BoolV con1 = BAnd(FIsGrtr(d1, d2), FIsGrtr(d1, d3)); const BoolV con2 = FIsGrtr(d2, d3); return V3Sel(con0, verts[0], V3Sel(con1, verts[1], V3Sel(con2, verts[2], verts[3]))); } //dir is in b space PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT) const { using namespace aos; //verts are in local space // const Vec3V _dir = aToB.rotateInv(dir); //transform dir back to a space const Vec3V _dir = aTobT.rotate(dir); //transform dir back to a space const Vec3V maxPoint = supportLocal(_dir); return aToB.transform(maxPoint);//transform maxPoint to the b space } PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index) const { using namespace aos; const Vec4V d = getProjection(dir); const FloatV d0 = V4GetX(d); const FloatV d1 = V4GetY(d); const FloatV d2 = V4GetZ(d); const FloatV d3 = V4GetW(d); const BoolV con0 = BAnd(BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)), FIsGrtr(d0, d3)); const BoolV con1 = BAnd(FIsGrtr(d1, d2), FIsGrtr(d1, d3)); const BoolV con2 = FIsGrtr(d2, d3); const VecI32V vIndex = VecI32V_Sel(con0, I4Load(0), VecI32V_Sel(con1, I4Load(1), VecI32V_Sel(con2, I4Load(2), I4Load(3)))); PxI32_From_VecI32V(vIndex, &index); //return V3Sel(con0, v0, V3Sel(con1, v1, v2)); return verts[index]; } PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT, PxI32& index)const { //don't put margin in the triangle using namespace aos; //transfer dir into the local space of triangle // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); return aToB.transform(supportLocal(_dir, index));//transform the support poin to b space } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { return verts[index]; } /** \brief Array of Vertices. */ aos::Vec3V verts[4]; aos::Vec4V vertsX; aos::Vec4V vertsY; aos::Vec4V vertsZ; }; } } #endif
8,210
C
31.975903
145
0.672473
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecConvexHull.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CONVEXHULL_H #define GU_VEC_CONVEXHULL_H #include "common/PxPhysXCommonConfig.h" #include "geometry/PxMeshScale.h" #include "GuConvexMesh.h" #include "GuVecConvex.h" #include "GuConvexMeshData.h" #include "GuBigConvexData.h" #include "GuConvexSupportTable.h" #include "GuCubeIndex.h" #include "foundation/PxFPU.h" #include "foundation/PxVecQuat.h" #include "GuShapeConvex.h" namespace physx { namespace Gu { #define CONVEX_MARGIN_RATIO 0.1f #define CONVEX_MIN_MARGIN_RATIO 0.05f #define CONVEX_SWEEP_MARGIN_RATIO 0.025f #define TOLERANCE_MARGIN_RATIO 0.08f #define TOLERANCE_MIN_MARGIN_RATIO 0.05f //This margin is used in Persistent contact manifold PX_SUPPORT_FORCE_INLINE aos::FloatV CalculatePCMConvexMargin(const Gu::ConvexHullData* hullData, const aos::Vec3VArg scale, const PxReal toleranceLength, const PxReal toleranceRatio = TOLERANCE_MIN_MARGIN_RATIO) { using namespace aos; const Vec3V extents= V3Mul(V3LoadU(hullData->mInternal.mExtents), scale); const FloatV min = V3ExtractMin(extents); const FloatV toleranceMargin = FLoad(toleranceLength * toleranceRatio); //ML: 25% of the minimum extents of the internal AABB as this convex hull's margin return FMin(FMul(min, FLoad(0.25f)), toleranceMargin); } PX_SUPPORT_FORCE_INLINE aos::FloatV CalculateMTDConvexMargin(const Gu::ConvexHullData* hullData, const aos::Vec3VArg scale) { using namespace aos; const Vec3V extents = V3Mul(V3LoadU(hullData->mInternal.mExtents), scale); const FloatV min = V3ExtractMin(extents); //ML: 25% of the minimum extents of the internal AABB as this convex hull's margin return FMul(min, FLoad(0.25f)); } //This minMargin is used in PCM contact gen PX_SUPPORT_FORCE_INLINE void CalculateConvexMargin(const InternalObjectsData& internalObject, PxReal& margin, PxReal& minMargin, PxReal& sweepMargin, const aos::Vec3VArg scale) { using namespace aos; const Vec3V extents = V3Mul(V3LoadU(internalObject.mExtents), scale); const FloatV min_ = V3ExtractMin(extents); PxReal minExtent; FStore(min_, &minExtent); //margin is used as acceptanceTolerance for overlap. margin = minExtent * CONVEX_MARGIN_RATIO; //minMargin is used in the GJK termination condition minMargin = minExtent * CONVEX_MIN_MARGIN_RATIO; //this is used for sweep(gjkRaycast) sweepMargin = minExtent * CONVEX_SWEEP_MARGIN_RATIO; } PX_SUPPORT_FORCE_INLINE aos::Mat33V ConstructSkewMatrix(const aos::Vec3VArg scale, const aos::QuatVArg rotation) { using namespace aos; Mat33V rot; QuatGetMat33V(rotation, rot.col0, rot.col1, rot.col2); Mat33V trans = M33Trnsps(rot); trans.col0 = V3Scale(trans.col0, V3GetX(scale)); trans.col1 = V3Scale(trans.col1, V3GetY(scale)); trans.col2 = V3Scale(trans.col2, V3GetZ(scale)); return M33MulM33(trans, rot); } PX_SUPPORT_FORCE_INLINE void ConstructSkewMatrix(const aos::Vec3VArg scale, const aos::QuatVArg rotation, aos::Mat33V& vertex2Shape, aos::Mat33V& shape2Vertex, aos::Vec3V& center, const bool idtScale) { using namespace aos; PX_ASSERT(!V3AllEq(scale, V3Zero())); if(idtScale) { //create identity buffer const Mat33V identity = M33Identity(); vertex2Shape = identity; shape2Vertex = identity; } else { const FloatV scaleX = V3GetX(scale); const Vec3V invScale = V3Recip(scale); //this is uniform scale if(V3AllEq(V3Splat(scaleX), scale)) { vertex2Shape = M33Diagonal(scale); shape2Vertex = M33Diagonal(invScale); } else { Mat33V rot; QuatGetMat33V(rotation, rot.col0, rot.col1, rot.col2); const Mat33V trans = M33Trnsps(rot); /* vertex2shape skewMat = Inv(R)*Diagonal(scale)*R; */ const Mat33V temp(V3Scale(trans.col0, scaleX), V3Scale(trans.col1, V3GetY(scale)), V3Scale(trans.col2, V3GetZ(scale))); vertex2Shape = M33MulM33(temp, rot); //don't need it in the support function /* shape2Vertex invSkewMat =(invSkewMat)= Inv(R)*Diagonal(1/scale)*R; */ shape2Vertex.col0 = V3Scale(trans.col0, V3GetX(invScale)); shape2Vertex.col1 = V3Scale(trans.col1, V3GetY(invScale)); shape2Vertex.col2 = V3Scale(trans.col2, V3GetZ(invScale)); shape2Vertex = M33MulM33(shape2Vertex, rot); //shape2Vertex = M33Inverse(vertex2Shape); } //transform center to shape space center = M33MulV3(vertex2Shape, center); } } PX_SUPPORT_FORCE_INLINE aos::Mat33V ConstructVertex2ShapeMatrix(const aos::Vec3VArg scale, const aos::QuatVArg rotation) { using namespace aos; Mat33V rot; QuatGetMat33V(rotation, rot.col0, rot.col1, rot.col2); const Mat33V trans = M33Trnsps(rot); /* vertex2shape skewMat = Inv(R)*Diagonal(scale)*R; */ const Mat33V temp(V3Scale(trans.col0, V3GetX(scale)), V3Scale(trans.col1, V3GetY(scale)), V3Scale(trans.col2, V3GetZ(scale))); return M33MulM33(temp, rot); } class ConvexHullV : public ConvexV { class TinyBitMap { public: PxU32 m[8]; PX_FORCE_INLINE TinyBitMap() { m[0] = m[1] = m[2] = m[3] = m[4] = m[5] = m[6] = m[7] = 0; } PX_FORCE_INLINE void set(PxU8 v) { m[v >> 5] |= 1 << (v & 31); } PX_FORCE_INLINE bool get(PxU8 v) const { return (m[v >> 5] & 1 << (v & 31)) != 0; } }; public: /** \brief Constructor */ PX_SUPPORT_INLINE ConvexHullV() : ConvexV(ConvexType::eCONVEXHULL) { } PX_SUPPORT_INLINE ConvexHullV(const Gu::ConvexHullData* _hullData, const aos::Vec3VArg _center, const aos::Vec3VArg scale, const aos::QuatVArg scaleRot, const bool idtScale) : ConvexV(ConvexType::eCONVEXHULL, _center) { using namespace aos; hullData = _hullData; const PxVec3* PX_RESTRICT tempVerts = _hullData->getHullVertices(); verts = tempVerts; numVerts = _hullData->mNbHullVertices; CalculateConvexMargin(_hullData->mInternal, margin, minMargin, sweepMargin, scale); ConstructSkewMatrix(scale, scaleRot, vertex2Shape, shape2Vertex, center, idtScale); data = _hullData->mBigConvexRawData; } PX_SUPPORT_INLINE ConvexHullV(const Gu::ConvexHullData* _hullData, const aos::Vec3VArg _center) : ConvexV(ConvexType::eCONVEXHULL, _center) { using namespace aos; hullData = _hullData; verts = _hullData->getHullVertices(); numVerts = _hullData->mNbHullVertices; data = _hullData->mBigConvexRawData; } //this is used by CCD system PX_SUPPORT_INLINE ConvexHullV(const PxGeometry& geom) : ConvexV(ConvexType::eCONVEXHULL, aos::V3Zero()) { using namespace aos; const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom); const Gu::ConvexHullData* hData = _getHullData(convexGeom); const Vec3V vScale = V3LoadU_SafeReadW(convexGeom.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vRot = QuatVLoadU(&convexGeom.scale.rotation.x); const bool idtScale = convexGeom.scale.isIdentity(); hullData = hData; const PxVec3* PX_RESTRICT tempVerts = hData->getHullVertices(); verts = tempVerts; numVerts = hData->mNbHullVertices; CalculateConvexMargin(hData->mInternal, margin, minMargin, sweepMargin, vScale); ConstructSkewMatrix(vScale, vRot, vertex2Shape, shape2Vertex, center, idtScale); data = hData->mBigConvexRawData; } //this is used by convex vs tetrahedron collision PX_SUPPORT_INLINE ConvexHullV(const Gu::PolygonalData& polyData, const Cm::FastVertex2ShapeScaling& convexScale) : ConvexV(ConvexType::eCONVEXHULL, aos::V3LoadU(polyData.mCenter)) { using namespace aos; const Vec3V vScale = V3LoadU(polyData.mScale.scale); verts = polyData.mVerts; numVerts = PxU8(polyData.mNbVerts); CalculateConvexMargin(polyData.mInternal, margin, minMargin, sweepMargin, vScale); const PxMat33& v2s = convexScale.getVertex2ShapeSkew(); const PxMat33& s2v = convexScale.getShape2VertexSkew(); vertex2Shape.col0 = V3LoadU(v2s.column0); vertex2Shape.col1 = V3LoadU(v2s.column1); vertex2Shape.col2 = V3LoadU(v2s.column2); shape2Vertex.col0 = V3LoadU(s2v.column0); shape2Vertex.col1 = V3LoadU(s2v.column1); shape2Vertex.col2 = V3LoadU(s2v.column2); data = polyData.mBigData; } PX_SUPPORT_INLINE void initialize(const Gu::ConvexHullData* _hullData, const aos::Vec3VArg _center, const aos::Vec3VArg scale, const aos::QuatVArg scaleRot, const bool idtScale) { using namespace aos; const PxVec3* tempVerts = _hullData->getHullVertices(); CalculateConvexMargin(_hullData->mInternal, margin, minMargin, sweepMargin, scale); ConstructSkewMatrix(scale, scaleRot, vertex2Shape, shape2Vertex, center, idtScale); verts = tempVerts; numVerts = _hullData->mNbHullVertices; //rot = _rot; center = _center; // searchIndex = 0; data = _hullData->mBigConvexRawData; hullData = _hullData; if (_hullData->mBigConvexRawData) { PxPrefetchLine(hullData->mBigConvexRawData->mValencies); PxPrefetchLine(hullData->mBigConvexRawData->mValencies, 128); PxPrefetchLine(hullData->mBigConvexRawData->mAdjacentVerts); } } PX_FORCE_INLINE void resetMargin(const PxReal toleranceLength) { const PxReal toleranceMinMargin = toleranceLength * TOLERANCE_MIN_MARGIN_RATIO; const PxReal toleranceMargin = toleranceLength * TOLERANCE_MARGIN_RATIO; margin = PxMin(margin, toleranceMargin); minMargin = PxMin(minMargin, toleranceMinMargin); } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { using namespace aos; return M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[index])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } PX_NOINLINE PxU32 hillClimbing(const aos::Vec3VArg _dir)const { using namespace aos; const Gu::Valency* valency = data->mValencies; const PxU8* adjacentVerts = data->mAdjacentVerts; //NotSoTinyBitMap visited; PxU32 smallBitMap[8] = {0,0,0,0,0,0,0,0}; // PxU32 index = searchIndex; PxU32 index = 0; { PxVec3 vertexSpaceDirection; V3StoreU(_dir, vertexSpaceDirection); const PxU32 offset = ComputeCubemapNearestOffset(vertexSpaceDirection, data->mSubdiv); //const PxU32 offset = ComputeCubemapOffset(vertexSpaceDirection, data->mSubdiv); index = data->mSamples[offset]; } Vec3V maxPoint = V3LoadU_SafeReadW(verts[index]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) FloatV max = V3Dot(maxPoint, _dir); PxU32 initialIndex = index; do { initialIndex = index; const PxU32 numNeighbours = valency[index].mCount; const PxU32 offset = valency[index].mOffset; for(PxU32 a = 0; a < numNeighbours; ++a) { const PxU32 neighbourIndex = adjacentVerts[offset + a]; const Vec3V vertex = V3LoadU_SafeReadW(verts[neighbourIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const FloatV dist = V3Dot(vertex, _dir); if(FAllGrtr(dist, max)) { const PxU32 ind = neighbourIndex>>5; const PxU32 mask = PxU32(1 << (neighbourIndex & 31)); if((smallBitMap[ind] & mask) == 0) { smallBitMap[ind] |= mask; max = dist; index = neighbourIndex; } } } }while(index != initialIndex); return index; } PX_SUPPORT_INLINE PxU32 bruteForceSearch(const aos::Vec3VArg _dir)const { using namespace aos; //brute force PxVec3 dir; V3StoreU(_dir, dir); PxReal max = verts[0].dot(dir); PxU32 maxIndex = 0; for (PxU32 i = 1; i < numVerts; ++i) { const PxReal dist = verts[i].dot(dir); if (dist > max) { max = dist; maxIndex = i; } } return maxIndex; } //points are in vertex space, _dir in vertex space PX_NOINLINE PxU32 supportVertexIndex(const aos::Vec3VArg _dir)const { using namespace aos; if(data) return hillClimbing(_dir); else return bruteForceSearch(_dir); } //dir is in the vertex space PX_SUPPORT_INLINE void bruteForceSearchMinMax(const aos::Vec3VArg _dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //brute force PxVec3 dir; V3StoreU(_dir, dir); //get the support point from the orignal margin PxReal _max = verts[0].dot(dir); PxReal _min = _max; for(PxU32 i = 1; i < numVerts; ++i) { const PxReal dist = verts[i].dot(dir); _max = PxMax(dist, _max); _min = PxMin(dist, _min); } min = FLoad(_min); max = FLoad(_max); } //This function is used in the full contact manifold generation code, points are in vertex space. //This function support scaling, _dir is in the shape space PX_SUPPORT_INLINE void supportVertexMinMax(const aos::Vec3VArg _dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //dir is in the vertex space const Vec3V dir = M33TrnspsMulV3(vertex2Shape, _dir); if(data) { const PxU32 maxIndex= hillClimbing(dir); const PxU32 minIndex= hillClimbing(V3Neg(dir)); const Vec3V maxPoint= M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[maxIndex])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const Vec3V minPoint= M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[minIndex])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) min = V3Dot(_dir, minPoint); max = V3Dot(_dir, maxPoint); } else { //dir is in the vertex space bruteForceSearchMinMax(dir, min, max); } } //This function is used in the full contact manifold generation code PX_SUPPORT_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* _verts)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) _verts[i] = M33MulV3(vertex2Shape, V3LoadU_SafeReadW(originalVerts[inds[i]])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'populateVerts' is always called with polyData.mVerts) } //This function is used in epa //dir is in the shape space PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; //scale dir and put it in the vertex space const Vec3V _dir = M33TrnspsMulV3(vertex2Shape, dir); const PxU32 maxIndex = supportVertexIndex(_dir); return M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[maxIndex])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this is used in the sat test for the full contact gen PX_SUPPORT_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //dir is in the shape space supportVertexMinMax(dir, min, max); } //This function is used in epa PX_SUPPORT_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT) const { using namespace aos; //transform dir into the shape space // const Vec3V dir_ = aTob.rotateInv(dir);//relTra.rotateInv(dir); const Vec3V dir_ = aTobT.rotate(dir);//relTra.rotateInv(dir); const Vec3V maxPoint =supportLocal(dir_); //translate maxPoint from shape space of a back to the b space return aTob.transform(maxPoint);//relTra.transform(maxPoint); } //dir in the shape space, this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; //scale dir and put it in the vertex space, for non-uniform scale, we don't want the scale in the dir, therefore, we are using //the transpose of the inverse of shape2Vertex(which is vertex2shape). This will allow us igore the scale and keep the rotation const Vec3V dir_ = M33TrnspsMulV3(vertex2Shape, dir); //get the extreme point index const PxU32 maxIndex = supportVertexIndex(dir_); index = PxI32(maxIndex); //p is in the shape space return M33MulV3(vertex2Shape, V3LoadU_SafeReadW(verts[index])); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT, PxI32& index)const { using namespace aos; //transform dir from b space to the shape space of a space // const Vec3V dir_ = aTob.rotateInv(dir);//relTra.rotateInv(dir);//M33MulV3(skewInvRot, dir); const Vec3V dir_ = aTobT.rotate(dir);//relTra.rotateInv(dir);//M33MulV3(skewInvRot, dir); const Vec3V p = supportLocal(dir_, index); //transfrom from a to b space return aTob.transform(p); } aos::Mat33V vertex2Shape;//inv(R)*S*R aos::Mat33V shape2Vertex;//inv(vertex2Shape) const Gu::ConvexHullData* hullData; const BigConvexRawData* data; const PxVec3* verts; PxU8 numVerts; }; } } #endif //
18,982
C
34.088725
229
0.715783
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecCapsule.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CAPSULE_H #define GU_VEC_CAPSULE_H /** \addtogroup geomutils @{ */ #include "geometry/PxCapsuleGeometry.h" #include "GuVecConvex.h" #include "GuConvexSupportTable.h" namespace physx { namespace Gu { PX_FORCE_INLINE aos::FloatV CalculateCapsuleMinMargin(const aos::FloatVArg radius) { using namespace aos; const FloatV ratio = aos::FLoad(0.05f); return FMul(radius, ratio); } class CapsuleV : public ConvexV { public: /** \brief Constructor */ PX_INLINE CapsuleV():ConvexV(ConvexType::eCAPSULE) { bMarginIsRadius = true; } //constructor for sphere PX_INLINE CapsuleV(const aos::Vec3VArg p, const aos::FloatVArg radius_) : ConvexV(ConvexType::eCAPSULE) { using namespace aos; center = p; radius = radius_; p0 = p; p1 = p; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } PX_INLINE CapsuleV(const aos::Vec3VArg center_, const aos::Vec3VArg v_, const aos::FloatVArg radius_) : ConvexV(ConvexType::eCAPSULE, center_) { using namespace aos; radius = radius_; p0 = V3Add(center_, v_); p1 = V3Sub(center_, v_); FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } PX_INLINE CapsuleV(const PxGeometry& geom) : ConvexV(ConvexType::eCAPSULE, aos::V3Zero()) { using namespace aos; const PxCapsuleGeometry& capsuleGeom = static_cast<const PxCapsuleGeometry&>(geom); const Vec3V axis = V3Scale(V3UnitX(), FLoad(capsuleGeom.halfHeight)); const FloatV r = FLoad(capsuleGeom.radius); p0 = axis; p1 = V3Neg(axis); radius = r; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } /** \brief Constructor \param _radius Radius of the capsule. */ /** \brief Destructor */ PX_INLINE ~CapsuleV() { } PX_FORCE_INLINE void initialize(const aos::Vec3VArg _p0, const aos::Vec3VArg _p1, const aos::FloatVArg _radius) { using namespace aos; radius = _radius; p0 = _p0; p1 = _p1; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); center = V3Scale(V3Add(_p0, _p1), FHalf()); } PX_INLINE aos::Vec3V computeDirection() const { return aos::V3Sub(p1, p0); } PX_FORCE_INLINE aos::FloatV getRadius() const { return radius; } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { return (&p0)[1-index]; } PX_FORCE_INLINE void getIndex(const aos::BoolV con, PxI32& index)const { using namespace aos; const VecI32V v = VecI32V_From_BoolV(con); const VecI32V t = VecI32V_And(v, VecI32V_One()); PxI32_From_VecI32V(t, &index); } PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { using namespace aos; Vec3V offset = V3Sub(_center, center); center = _center; p0 = V3Add(p0, offset); p1 = V3Add(p1, offset); } //dir, p0 and p1 are in the local space of dir PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; //const Vec3V _dir = V3Normalize(dir); const FloatV dist0 = V3Dot(p0, dir); const FloatV dist1 = V3Dot(p1, dir); return V3Sel(FIsGrtr(dist0, dist1), p0, p1); } PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT) const { using namespace aos; //transform dir into the local space of a // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); const Vec3V p = supportLocal(_dir); //transform p back to the local space of b return aToB.transform(p); } //dir, p0 and p1 are in the local space of dir PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; const FloatV dist0 = V3Dot(p0, dir); const FloatV dist1 = V3Dot(p1, dir); const BoolV comp = FIsGrtr(dist0, dist1); getIndex(comp, index); return V3Sel(comp, p0, p1); } PX_FORCE_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT, PxI32& index)const { using namespace aos; //transform dir into the local space of a // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); const Vec3V p = supportLocal(_dir, index); //transform p back to the local space of b return aToB.transform(p); } PX_FORCE_INLINE aos::Vec3V supportLocal(aos::Vec3V& support, const PxI32& index, const aos::BoolV comp)const { PX_UNUSED(index); using namespace aos; const Vec3V p = V3Sel(comp, p0, p1); support = p; return p; } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FZero(); } //don't change the order of p0 and p1, the getPoint function depend on the order aos::Vec3V p0; //!< Start of segment aos::Vec3V p1; //!< End of segment aos::FloatV radius; }; } } #endif
6,770
C
27.56962
144
0.691581
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKType.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKTYPE_H #define GU_GJKTYPE_H #include "GuVecConvex.h" #include "foundation/PxVecTransform.h" namespace physx { namespace Gu { class ConvexHullV; class ConvexHullNoScaleV; class BoxV; template <typename Convex> struct ConvexGeom { typedef Convex Type; }; template <> struct ConvexGeom<ConvexHullV> { typedef ConvexHullV Type; }; template <> struct ConvexGeom<ConvexHullNoScaleV> { typedef ConvexHullNoScaleV Type; }; template <> struct ConvexGeom<BoxV> { typedef BoxV Type; }; struct GjkConvex { GjkConvex(const ConvexV& convex) : mConvex(convex) {} virtual ~GjkConvex() {} PX_FORCE_INLINE aos::FloatV getMinMargin() const { return mConvex.getMinMargin(); } PX_FORCE_INLINE aos::BoolV isMarginEqRadius() const { return mConvex.isMarginEqRadius(); } PX_FORCE_INLINE bool getMarginIsRadius() const { return mConvex.getMarginIsRadius(); } PX_FORCE_INLINE aos::FloatV getMargin() const { return mConvex.getMargin(); } template <typename Convex> PX_FORCE_INLINE const Convex& getConvex() const { return static_cast<const Convex&>(mConvex); } virtual aos::Vec3V supportPoint(const PxI32 index) const { return doVirtualSupportPoint(index); } virtual aos::Vec3V support(const aos::Vec3VArg v) const { return doVirtualSupport(v); } virtual aos::Vec3V support(const aos::Vec3VArg dir, PxI32& index) const { return doVirtualSupport(dir, index); } virtual aos::FloatV getSweepMargin() const { return doVirtualGetSweepMargin(); } virtual aos::Vec3V getCenter() const = 0; protected: const ConvexV& mConvex; private: // PT: following functions call the v-table. I think this curious pattern is needed for the de-virtualization // approach used in the GJK code, combined with the GuGJKTest file that is only used externally. aos::Vec3V doVirtualSupportPoint(const PxI32 index) const { return supportPoint(index); } aos::Vec3V doVirtualSupport(const aos::Vec3VArg v) const { return support(v); } aos::Vec3V doVirtualSupport(const aos::Vec3VArg dir, PxI32& index) const { return support(dir, index); } aos::FloatV doVirtualGetSweepMargin() const { return getSweepMargin(); } //PX_NOCOPY(GjkConvex) GjkConvex& operator = (const GjkConvex&); }; template <typename Convex> struct LocalConvex : public GjkConvex { LocalConvex(const Convex& convex) : GjkConvex(convex){} // PT: I think we omit the virtual on purpose here, for the de-virtualization approach, i.e. the code calls these // functions directly (bypassing the v-table). In fact I think we don't need virtuals at all here, it's probably // only for external cases and/or cases where we want to reduce code size. // The mix of virtual/force-inline/inline below is confusing/unclear. // GjkConvex PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index) const { return getConvex<Convex>().supportPoint(index); } aos::Vec3V support(const aos::Vec3VArg v) const { return getConvex<Convex>().supportLocal(v); } aos::Vec3V support(const aos::Vec3VArg dir, PxI32& index) const { return getConvex<Convex>().supportLocal(dir, index); } PX_INLINE aos::FloatV getSweepMargin() const { return getConvex<Convex>().getSweepMargin(); } virtual aos::Vec3V getCenter() const { return getConvex<Convex>().getCenter(); } //~GjkConvex //ML: we can't force inline function, otherwise win modern will throw compiler error PX_INLINE LocalConvex<typename ConvexGeom<Convex>::Type > getGjkConvex() const { return LocalConvex<typename ConvexGeom<Convex>::Type >(static_cast<const typename ConvexGeom<Convex>::Type&>(GjkConvex::mConvex)); } typedef LocalConvex<typename ConvexGeom<Convex>::Type > ConvexGeomType; typedef Convex Type; private: //PX_NOCOPY(LocalConvex<Convex>) LocalConvex<Convex>& operator = (const LocalConvex<Convex>&); }; template <typename Convex> struct RelativeConvex : public GjkConvex { RelativeConvex(const Convex& convex, const aos::PxMatTransformV& aToB) : GjkConvex(convex), mAToB(aToB), mAToBTransposed(aToB) { aos::V3Transpose(mAToBTransposed.rot.col0, mAToBTransposed.rot.col1, mAToBTransposed.rot.col2); } // GjkConvex PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index) const { return mAToB.transform(getConvex<Convex>().supportPoint(index)); } aos::Vec3V support(const aos::Vec3VArg v) const { return getConvex<Convex>().supportRelative(v, mAToB, mAToBTransposed); } aos::Vec3V support(const aos::Vec3VArg dir, PxI32& index) const { return getConvex<Convex>().supportRelative(dir, mAToB, mAToBTransposed, index); } PX_INLINE aos::FloatV getSweepMargin() const { return getConvex<Convex>().getSweepMargin(); } virtual aos::Vec3V getCenter() const { return mAToB.transform(getConvex<Convex>().getCenter()); } //~GjkConvex PX_FORCE_INLINE const aos::PxMatTransformV& getRelativeTransform() const { return mAToB; } //ML: we can't force inline function, otherwise win modern will throw compiler error PX_INLINE RelativeConvex<typename ConvexGeom<Convex>::Type > getGjkConvex() const { return RelativeConvex<typename ConvexGeom<Convex>::Type >(static_cast<const typename ConvexGeom<Convex>::Type&>(GjkConvex::mConvex), mAToB); } typedef RelativeConvex<typename ConvexGeom<Convex>::Type > ConvexGeomType; typedef Convex Type; private: //PX_NOCOPY(RelativeConvex<Convex>) RelativeConvex<Convex>& operator = (const RelativeConvex<Convex>&); const aos::PxMatTransformV& mAToB; aos::PxMatTransformV mAToBTransposed; // PT: precomputed mAToB transpose (because 'rotate' is faster than 'rotateInv') }; } } #endif
7,447
C
47.051613
153
0.731301
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecConvexHullNoScale.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CONVEXHULL_NOSCALE_H #define GU_VEC_CONVEXHULL_NOSCALE_H #include "foundation/PxUnionCast.h" #include "common/PxPhysXCommonConfig.h" #include "GuVecConvexHull.h" namespace physx { namespace Gu { class ConvexHullNoScaleV : public ConvexHullV { public: /** \brief Constructor */ PX_SUPPORT_INLINE ConvexHullNoScaleV(): ConvexHullV() { } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { using namespace aos; return V3LoadU_SafeReadW(verts[index]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //This funcation is just to load the PxVec3 to Vec3V. However, for GuVecConvexHul.h, this is used to transform all the verts from vertex space to shape space PX_SUPPORT_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* verts_)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) verts_[i] = V3LoadU_SafeReadW(originalVerts[inds[i]]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'populateVerts' is always called with polyData.mVerts) } //This function is used in epa //dir is in the shape space PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir)const { using namespace aos; const PxU32 maxIndex = supportVertexIndex(dir); return V3LoadU_SafeReadW(verts[maxIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this is used in the sat test for the full contact gen PX_SUPPORT_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { supportVertexMinMax(dir, min, max); } //This function is used in epa PX_SUPPORT_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT) const { using namespace aos; //transform dir into the shape space const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir); const Vec3V maxPoint = supportLocal(_dir); //translate maxPoint from shape space of a back to the b space return aTob.transform(maxPoint);//relTra.transform(maxPoint); } //dir in the shape space, this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index)const { using namespace aos; //scale dir and put it in the vertex space, for non-uniform scale, we don't want the scale in the dir, therefore, we are using //the transpose of the inverse of shape2Vertex(which is vertex2shape). This will allow us igore the scale and keep the rotation //get the extreme point index const PxU32 maxIndex = supportVertexIndex(dir); index = PxI32(maxIndex); return V3LoadU_SafeReadW(verts[index]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) } //this function is used in gjk PX_SUPPORT_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aTob, const aos::PxMatTransformV& aTobT, PxI32& index)const { using namespace aos; //transform dir from b space to the shape space of a space const Vec3V _dir = aTobT.rotate(dir);//relTra.rotateInv(dir);//M33MulV3(skewInvRot, dir); const Vec3V p = supportLocal(_dir, index); //transfrom from a to b space return aTob.transform(p); } PX_SUPPORT_INLINE void bruteForceSearchMinMax(const aos::Vec3VArg _dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; //brute force //get the support point from the orignal margin FloatV _max = V3Dot(V3LoadU_SafeReadW(verts[0]), _dir); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) FloatV _min = _max; for(PxU32 i = 1; i < numVerts; ++i) { PxPrefetchLine(&verts[i], 128); const Vec3V vertex = V3LoadU_SafeReadW(verts[i]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const FloatV dist = V3Dot(vertex, _dir); _max = FMax(dist, _max); _min = FMin(dist, _min); } min = _min; max = _max; } //This function support no scaling, dir is in the shape space(the same as vertex space) PX_SUPPORT_INLINE void supportVertexMinMax(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max)const { using namespace aos; if(data) { const PxU32 maxIndex= hillClimbing(dir); const PxU32 minIndex= hillClimbing(V3Neg(dir)); const Vec3V maxPoint= V3LoadU_SafeReadW(verts[maxIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) const Vec3V minPoint= V3LoadU_SafeReadW(verts[minIndex]); // PT: safe because of the way vertex memory is allocated in ConvexHullData (and 'verts' is initialized with ConvexHullData::getHullVertices()) min = V3Dot(dir, minPoint); max = V3Dot(dir, maxPoint); } else { bruteForceSearchMinMax(dir, min, max); } } }; #define PX_CONVEX_TO_NOSCALECONVEX(x) (static_cast<const ConvexHullNoScaleV*>(x)) } } #endif //
7,126
C
41.933735
205
0.731827
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecConvex.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_CONVEX_H #define GU_VEC_CONVEX_H #include "foundation/PxVecMath.h" #define PX_SUPPORT_INLINE PX_FORCE_INLINE #define PX_SUPPORT_FORCE_INLINE PX_FORCE_INLINE namespace physx { namespace Gu { struct ConvexType { enum Type { eCONVEXHULL, eCONVEXHULLNOSCALE, eSPHERE, eBOX, eCAPSULE, eTRIANGLE, eTETRAHEDRON, eCUSTOM }; }; class ConvexV { public: PX_FORCE_INLINE ConvexV(const ConvexType::Type type_) : type(type_), bMarginIsRadius(false) { margin = 0.f; minMargin = 0.f; sweepMargin = 0.f; center = aos::V3Zero(); } PX_FORCE_INLINE ConvexV(const ConvexType::Type type_, const aos::Vec3VArg center_) : type(type_), bMarginIsRadius(false) { using namespace aos; center = center_; margin = 0.f; minMargin = 0.f; sweepMargin = 0.f; } //everytime when someone transform the object, they need to up PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { center = _center; } PX_FORCE_INLINE void setMargin(const aos::FloatVArg margin_) { aos::FStore(margin_, &margin); } PX_FORCE_INLINE void setMargin(const PxReal margin_) { margin = margin_; } PX_FORCE_INLINE void setMinMargin(const aos::FloatVArg minMargin_) { aos::FStore(minMargin_, & minMargin); } PX_FORCE_INLINE void setSweepMargin(const aos::FloatVArg sweepMargin_) { aos::FStore(sweepMargin_, &sweepMargin); } PX_FORCE_INLINE aos::Vec3V getCenter()const { return center; } PX_FORCE_INLINE aos::FloatV getMargin() const { return aos::FLoad(margin); } PX_FORCE_INLINE aos::FloatV getMinMargin() const { return aos::FLoad(minMargin); } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FLoad(sweepMargin); } PX_FORCE_INLINE ConvexType::Type getType() const { return type; } PX_FORCE_INLINE aos::BoolV isMarginEqRadius()const { return aos::BLoad(bMarginIsRadius); } PX_FORCE_INLINE bool getMarginIsRadius() const { return bMarginIsRadius; } PX_FORCE_INLINE PxReal getMarginF() const { return margin; } protected: ~ConvexV(){} aos::Vec3V center; PxReal margin; //margin is the amount by which we shrunk the shape for a convex or box. If the shape are sphere/capsule, margin is the radius PxReal minMargin; //minMargin is some percentage of marginBase, which is used to determine the termination condition for gjk PxReal sweepMargin; //sweepMargin minMargin is some percentage of marginBase, which is used to determine the termination condition for gjkRaycast ConvexType::Type type; bool bMarginIsRadius; }; PX_FORCE_INLINE aos::FloatV getContactEps(const aos::FloatV& _marginA, const aos::FloatV& _marginB) { using namespace aos; const FloatV ratio = FLoad(0.25f); const FloatV minMargin = FMin(_marginA, _marginB); return FMul(minMargin, ratio); } PX_FORCE_INLINE aos::FloatV getSweepContactEps(const aos::FloatV& _marginA, const aos::FloatV& _marginB) { using namespace aos; const FloatV ratio = FLoad(100.f); const FloatV minMargin = FAdd(_marginA, _marginB); return FMul(minMargin, ratio); } } } #endif
4,864
C
26.027778
149
0.717722
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuEPA.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_EPA_H #define GU_EPA_H #include "GuGJKUtil.h" #include "GuGJKType.h" namespace physx { namespace Gu { //ML: The main entry point for EPA. // //This function returns one of three status codes: //(1)EPA_FAIL: the algorithm failed to create a valid polytope(the origin wasn't inside the polytope) from the input simplex. //(2)EPA_CONTACT : the algorithm found the MTD and converged successfully. //(3)EPA_DEGENERATE: the algorithm cannot make further progress and the result is unknown. GjkStatus epaPenetration( const GjkConvex& a, //convex a in the space of convex b const GjkConvex& b, //convex b const PxU8* PX_RESTRICT aInd, //warm start index for convex a to create an initial simplex const PxU8* PX_RESTRICT bInd, //warm start index for convex b to create an initial simplex const PxU8 size, //number of warm-start indices const bool takeCoreShape, //indicates whether we take support point from the core shape or surface of capsule/sphere const aos::FloatV tolerenceLength, //the length of meter GjkOutput& output); //result GjkStatus epaPenetration( const GjkConvex& a, //convex a in the space of convex b const GjkConvex& b, //convex b const aos::Vec3V* PX_RESTRICT aPnt, //warm start point for convex a to create an initial simplex const aos::Vec3V* PX_RESTRICT bPnt, //warm start point for convex b to create an initial simplex const PxU8 size, //number of warm-start indices const bool takeCoreShape, //indicates whether we take support point from the core shape or surface of capsule/sphere const aos::FloatV tolerenceLength, //the length of meter GjkOutput& output); //result } } #endif
3,542
C
50.347825
127
0.718238
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecSphere.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_SPHERE_H #define GU_VEC_SPHERE_H /** \addtogroup geomutils @{ */ #include "geometry/PxSphereGeometry.h" #include "GuVecConvex.h" #include "GuConvexSupportTable.h" /** \brief Represents a sphere defined by its center point and radius. */ namespace physx { namespace Gu { class SphereV : public ConvexV { public: /** \brief Constructor */ PX_INLINE SphereV(): ConvexV(ConvexType::eSPHERE) { radius = aos::FZero(); bMarginIsRadius = true; } PX_INLINE SphereV(const aos::Vec3VArg _center, const aos::FloatV _radius) : ConvexV(ConvexType::eSPHERE, _center) { using namespace aos; radius = _radius; FStore(radius, &margin); FStore(radius, &minMargin); FStore(radius, &sweepMargin); bMarginIsRadius = true; } /** \brief Copy constructor */ PX_INLINE SphereV(const SphereV& sphere) : ConvexV(ConvexType::eSPHERE), radius(sphere.radius) { margin = sphere.margin; minMargin = sphere.minMargin; sweepMargin = sphere.sweepMargin; bMarginIsRadius = true; } PX_INLINE SphereV(const PxGeometry& geom) : ConvexV(ConvexType::eSPHERE, aos::V3Zero()) { using namespace aos; const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom); const FloatV r = FLoad(sphereGeom.radius); radius = r; margin = sphereGeom.radius; minMargin = sphereGeom.radius; sweepMargin = sphereGeom.radius; bMarginIsRadius = true; } /** \brief Destructor */ PX_INLINE ~SphereV() { } PX_INLINE void setV(const aos::Vec3VArg _center, const aos::FloatVArg _radius) { center = _center; radius = _radius; } /** \brief Checks the sphere is valid. \return true if the sphere is valid */ PX_INLINE bool isValid() const { // Consistency condition for spheres: Radius >= 0.0f using namespace aos; return BAllEqTTTT(FIsGrtrOrEq(radius, FZero())) != 0; } /** \brief Tests if a point is contained within the sphere. \param[in] p the point to test \return true if inside the sphere */ PX_INLINE bool contains(const aos::Vec3VArg p) const { using namespace aos; const FloatV rr = FMul(radius, radius); const FloatV cc = V3LengthSq(V3Sub(center, p)); return FAllGrtrOrEq(rr, cc) != 0; } /** \brief Tests if a sphere is contained within the sphere. \param sphere [in] the sphere to test \return true if inside the sphere */ PX_INLINE bool contains(const SphereV& sphere) const { using namespace aos; const Vec3V centerDif= V3Sub(center, sphere.center); const FloatV radiusDif = FSub(radius, sphere.radius); const FloatV cc = V3Dot(centerDif, centerDif); const FloatV rr = FMul(radiusDif, radiusDif); const BoolV con0 = FIsGrtrOrEq(radiusDif, FZero());//might contain const BoolV con1 = FIsGrtr(rr, cc);//return true return BAllEqTTTT(BAnd(con0, con1))==1; } /** \brief Tests if a box is contained within the sphere. \param minimum [in] minimum value of the box \param maximum [in] maximum value of the box \return true if inside the sphere */ PX_INLINE bool contains(const aos::Vec3VArg minimum, const aos::Vec3VArg maximum) const { //compute the sphere which wrap around the box using namespace aos; const FloatV zero = FZero(); const FloatV half = FHalf(); const Vec3V boxSphereCenter = V3Scale(V3Add(maximum, minimum), half); const Vec3V v = V3Scale(V3Sub(maximum, minimum), half); const FloatV boxSphereR = V3Length(v); const Vec3V w = V3Sub(center, boxSphereCenter); const FloatV wLength = V3Length(w); const FloatV dif = FSub(FSub(radius, wLength), boxSphereR); return FAllGrtrOrEq(dif, zero) != 0; } /** \brief Tests if the sphere intersects another sphere \param sphere [in] the other sphere \return true if spheres overlap */ PX_INLINE bool intersect(const SphereV& sphere) const { using namespace aos; const Vec3V centerDif = V3Sub(center, sphere.center); const FloatV cc = V3Dot(centerDif, centerDif); const FloatV r = FAdd(radius, sphere.radius); const FloatV rr = FMul(r, r); return FAllGrtrOrEq(rr, cc) != 0; } //return point in local space PX_FORCE_INLINE aos::Vec3V getPoint(const PxU8) { return aos::V3Zero(); } // //sweep code need to have full version PX_FORCE_INLINE aos::Vec3V supportSweep(const aos::Vec3VArg dir)const { using namespace aos; const Vec3V _dir = V3Normalize(dir); return V3ScaleAdd(_dir, radius, center); } //make the support function the same as support margin PX_FORCE_INLINE aos::Vec3V support(const aos::Vec3VArg)const { return center;//_margin is the same as radius } PX_FORCE_INLINE aos::Vec3V supportMargin(const aos::Vec3VArg dir, const aos::FloatVArg _margin, aos::Vec3V& support)const { PX_UNUSED(_margin); PX_UNUSED(dir); support = center; return center;//_margin is the same as radius } PX_FORCE_INLINE aos::BoolV isMarginEqRadius()const { return aos::BTTTT(); } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FZero(); } aos::FloatV radius; //!< Sphere's center, w component is radius }; } } #endif
6,911
C
27.444444
123
0.698452
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuVecTriangle.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_VEC_TRIANGLE_H #define GU_VEC_TRIANGLE_H /** \addtogroup geomutils @{ */ #include "GuVecConvex.h" #include "GuConvexSupportTable.h" #include "GuDistancePointTriangle.h" namespace physx { namespace Gu { class TriangleV : public ConvexV { public: /** \brief Constructor */ PX_FORCE_INLINE TriangleV() : ConvexV(ConvexType::eTRIANGLE) { margin = 0.02f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Constructor \param[in] p0 Point 0 \param[in] p1 Point 1 \param[in] p2 Point 2 */ PX_FORCE_INLINE TriangleV(const aos::Vec3VArg p0, const aos::Vec3VArg p1, const aos::Vec3VArg p2): ConvexV(ConvexType::eTRIANGLE) { using namespace aos; //const FloatV zero = FZero(); const FloatV num = FLoad(0.333333f); center = V3Scale(V3Add(V3Add(p0, p1), p2), num); verts[0] = p0; verts[1] = p1; verts[2] = p2; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } PX_FORCE_INLINE TriangleV(const PxVec3* pts) : ConvexV(ConvexType::eTRIANGLE) { using namespace aos; const Vec3V p0 = V3LoadU(pts[0]); const Vec3V p1 = V3LoadU(pts[1]); const Vec3V p2 = V3LoadU(pts[2]); const FloatV num = FLoad(0.333333f); center = V3Scale(V3Add(V3Add(p0, p1), p2), num); verts[0] = p0; verts[1] = p1; verts[2] = p2; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Copy constructor \param[in] triangle Tri to copy */ PX_FORCE_INLINE TriangleV(const Gu::TriangleV& triangle) : ConvexV(ConvexType::eTRIANGLE) { using namespace aos; verts[0] = triangle.verts[0]; verts[1] = triangle.verts[1]; verts[2] = triangle.verts[2]; center = triangle.center; margin = 0.f; minMargin = PX_MAX_REAL; sweepMargin = PX_MAX_REAL; } /** \brief Destructor */ PX_FORCE_INLINE ~TriangleV() { } PX_FORCE_INLINE void populateVerts(const PxU8* inds, PxU32 numInds, const PxVec3* originalVerts, aos::Vec3V* vertexs)const { using namespace aos; for(PxU32 i=0; i<numInds; ++i) { vertexs[i] = V3LoadU(originalVerts[inds[i]]); } } PX_FORCE_INLINE aos::FloatV getSweepMargin() const { return aos::FMax(); } PX_FORCE_INLINE void setCenter(const aos::Vec3VArg _center) { using namespace aos; Vec3V offset = V3Sub(_center, center); center = _center; verts[0] = V3Add(verts[0], offset); verts[1] = V3Add(verts[1], offset); verts[2] = V3Add(verts[2], offset); } /** \brief Compute the normal of the Triangle. \return Triangle normal. */ PX_FORCE_INLINE aos::Vec3V normal() const { using namespace aos; const Vec3V ab = V3Sub(verts[1], verts[0]); const Vec3V ac = V3Sub(verts[2], verts[0]); const Vec3V n = V3Cross(ab, ac); return V3Normalize(n); } /** \brief Compute the unnormalized normal of the Triangle. \param[out] _normal Triangle normal (not normalized). */ PX_FORCE_INLINE void denormalizedNormal(aos::Vec3V& _normal) const { using namespace aos; const Vec3V ab = V3Sub(verts[1], verts[0]); const Vec3V ac = V3Sub(verts[2], verts[0]); _normal = V3Cross(ab, ac); } PX_FORCE_INLINE aos::FloatV area() const { using namespace aos; const FloatV half = FLoad(0.5f); const Vec3V ba = V3Sub(verts[0], verts[1]); const Vec3V ca = V3Sub(verts[0], verts[2]); const Vec3V v = V3Cross(ba, ca); return FMul(V3Length(v), half); } //dir is in local space, verts in the local space PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir) const { using namespace aos; const Vec3V v0 = verts[0]; const Vec3V v1 = verts[1]; const Vec3V v2 = verts[2]; const FloatV d0 = V3Dot(v0, dir); const FloatV d1 = V3Dot(v1, dir); const FloatV d2 = V3Dot(v2, dir); const BoolV con0 = BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)); const BoolV con1 = FIsGrtr(d1, d2); return V3Sel(con0, v0, V3Sel(con1, v1, v2)); } PX_FORCE_INLINE void supportLocal(const aos::Vec3VArg dir, aos::FloatV& min, aos::FloatV& max) const { using namespace aos; const Vec3V v0 = verts[0]; const Vec3V v1 = verts[1]; const Vec3V v2 = verts[2]; FloatV d0 = V3Dot(v0, dir); FloatV d1 = V3Dot(v1, dir); FloatV d2 = V3Dot(v2, dir); max = FMax(d0, FMax(d1, d2)); min = FMin(d0, FMin(d1, d2)); } //dir is in b space PX_FORCE_INLINE aos::Vec3V supportRelative(const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT) const { using namespace aos; //verts are in local space // const Vec3V _dir = aToB.rotateInv(dir); //transform dir back to a space const Vec3V _dir = aTobT.rotate(dir); //transform dir back to a space const Vec3V maxPoint = supportLocal(_dir); return aToB.transform(maxPoint);//transform maxPoint to the b space } PX_FORCE_INLINE aos::Vec3V supportLocal(const aos::Vec3VArg dir, PxI32& index) const { using namespace aos; const VecI32V vZero = VecI32V_Zero(); const VecI32V vOne = VecI32V_One(); const VecI32V vTwo = VecI32V_Two(); const Vec3V v0 = verts[0]; const Vec3V v1 = verts[1]; const Vec3V v2 = verts[2]; const FloatV d0 = V3Dot(v0, dir); const FloatV d1 = V3Dot(v1, dir); const FloatV d2 = V3Dot(v2, dir); const BoolV con0 = BAnd(FIsGrtr(d0, d1), FIsGrtr(d0, d2)); const BoolV con1 = FIsGrtr(d1, d2); const VecI32V vIndex = VecI32V_Sel(con0, vZero, VecI32V_Sel(con1, vOne, vTwo)); PxI32_From_VecI32V(vIndex, &index); return V3Sel(con0, v0, V3Sel(con1, v1, v2)); } PX_FORCE_INLINE aos::Vec3V supportRelative( const aos::Vec3VArg dir, const aos::PxMatTransformV& aToB, const aos::PxMatTransformV& aTobT, PxI32& index)const { //don't put margin in the triangle using namespace aos; //transfer dir into the local space of triangle // const Vec3V _dir = aToB.rotateInv(dir); const Vec3V _dir = aTobT.rotate(dir); return aToB.transform(supportLocal(_dir, index));//transform the support poin to b space } PX_FORCE_INLINE aos::Vec3V supportPoint(const PxI32 index)const { return verts[index]; } /** \brief Array of Vertices. */ aos::Vec3V verts[3]; }; } } #endif
7,925
C
28.574627
144
0.674322
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJK.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJK_H #define GU_GJK_H #include "GuGJKType.h" #include "GuGJKUtil.h" #include "GuConvexSupportTable.h" #include "GuGJKSimplex.h" #include "foundation/PxFPU.h" #define GJK_SEPERATING_AXIS_VALIDATE 0 namespace physx { namespace Gu { class ConvexV; #if GJK_SEPERATING_AXIS_VALIDATE template<typename ConvexA, typename ConvexB> static void validateSeparatingAxis(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg separatingAxis) { using namespace aos; const Vec3V minV0 = a.ConvexA::support(V3Neg(separatingAxis)); const Vec3V maxV0 = a.ConvexA::support(separatingAxis); const Vec3V minV1 = b.ConvexB::support(V3Neg(separatingAxis)); const Vec3V maxV1 = b.ConvexB::support(separatingAxis); const FloatV min0 = V3Dot(minV0, separatingAxis); const FloatV max0 = V3Dot(maxV0, separatingAxis); const FloatV min1 = V3Dot(minV1, separatingAxis); const FloatV max1 = V3Dot(maxV1, separatingAxis); PX_ASSERT(FAllGrtr(min1, max0) || FAllGrtr(min0, max1)); } #endif /* initialSearchDir :initial search direction in the mincowsky sum, it should be in the local space of ConvexB closestA :it is the closest point in ConvexA in the local space of ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage closestB :it is the closest point in ConvexB in the local space of ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage normal :normal pointing from ConvexA to ConvexB in the local space of ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage distance :the distance of the closest points between ConvexA and ConvexB if acceptance threshold is sufficent large. Otherwise, it will be garbage contactDist :the distance which we will generate contact information if ConvexA and ConvexB are both separated within contactDist */ //*Each convex has //* a support function //* a margin - the amount by which we shrunk the shape for a convex or box. If the shape are sphere/capsule, margin is the radius //* a minMargin - some percentage of margin, which is used to determine the termination condition for gjk //*We'll report: //* GJK_NON_INTERSECT if the sign distance between the shapes is greater than the sum of the margins and the the contactDistance //* GJK_CLOSE if the minimum distance between the shapes is less than the sum of the margins and the the contactDistance //* GJK_CONTACT if the two shapes are overlapped with each other template<typename ConvexA, typename ConvexB> GjkStatus gjk(const ConvexA& a, const ConvexB& b, const aos::Vec3V& initialSearchDir, const aos::FloatV& contactDist, aos::Vec3V& closestA, aos::Vec3V& closestB, aos::Vec3V& normal, aos::FloatV& distance) { using namespace aos; Vec3V Q[4]; Vec3V A[4]; Vec3V B[4]; const FloatV zero = FZero(); PxU32 size=0; //const Vec3V _initialSearchDir = aToB.p; Vec3V closest = V3Sel(FIsGrtr(V3Dot(initialSearchDir, initialSearchDir), zero), initialSearchDir, V3UnitX()); Vec3V v = V3Normalize(closest); // ML: eps2 is the square value of an epsilon value which applied in the termination condition for two shapes overlap. // GJK will terminate based on sq(v) < eps and indicate that two shapes are overlapping. // we calculate the eps based on 10% of the minimum margin of two shapes const FloatV tenPerc = FLoad(0.1f); const FloatV minMargin = FMin(a.getMinMargin(), b.getMinMargin()); const FloatV eps = FMax(FLoad(1e-6f), FMul(minMargin, tenPerc)); // ML:epsRel is square value of 1.5% which applied to the distance of a closest point(v) to the origin. // If |v|- v/|v|.dot(w) < epsRel*|v|, // two shapes are clearly separated, GJK terminate and return non intersect. // This adjusts the termination condition based on the length of v // which avoids ill-conditioned terminations. const FloatV epsRel = FLoad(0.000225f);//1.5%. FloatV dist = FMax(); FloatV prevDist; Vec3V prevClos, prevDir; const BoolV bTrue = BTTTT(); BoolV bNotTerminated = bTrue; BoolV bNotDegenerated = bTrue; //ML: we treate sphere as a point and capsule as segment in the support function, so that we need to add on radius const BoolV aQuadratic = a.isMarginEqRadius(); const BoolV bQuadratic = b.isMarginEqRadius(); const FloatV sumMargin = FAdd(FSel(aQuadratic, a.getMargin(), zero), FSel(bQuadratic, b.getMargin(), zero)); const FloatV separatingDist = FAdd(sumMargin, contactDist); const FloatV relDif = FSub(FOne(), epsRel); do { prevDist = dist; prevClos = closest; prevDir = v; //de-virtualize, we don't need to use a normalize direction to get the support point //this will allow the cpu better pipeline the normalize calculation while it does the //support map const Vec3V supportA=a.ConvexA::support(V3Neg(closest)); const Vec3V supportB=b.ConvexB::support(closest); //calculate the support point const Vec3V support = V3Sub(supportA, supportB); const FloatV signDist = V3Dot(v, support); if(FAllGrtr(signDist, separatingDist)) { //ML:gjk found a separating axis for these two objects and the distance is large than the seperating distance, gjk might not converage so that //we won't generate contact information #if GJK_SEPERATING_AXIS_VALIDATE validateSeparatingAxis(a, b, v); #endif return GJK_NON_INTERSECT; } const BoolV con = BAnd(FIsGrtr(signDist, sumMargin), FIsGrtr(signDist, FMul(relDif, dist))); if(BAllEqTTTT(con)) { //ML:: gjk converage and we get the closest point information Vec3V closA, closB; //normal point from A to B const Vec3V n = V3Neg(v); getClosestPoint(Q, A, B, closest, closA, closB, size); closestA = V3Sel(aQuadratic, V3ScaleAdd(n, a.getMargin(), closA), closA); closestB = V3Sel(bQuadratic, V3NegScaleSub(n, b.getMargin(), closB), closB); distance = FMax(zero, FSub(dist, sumMargin)); normal = n;//V3Normalize(V3Neg(closest)); return GJK_CLOSE; } PX_ASSERT(size < 4); A[size]=supportA; B[size]=supportB; Q[size++]=support; //calculate the closest point between two convex hull closest = GJKCPairDoSimplex(Q, A, B, support, size); dist = V3Length(closest); v = V3ScaleInv(closest, dist); bNotDegenerated = FIsGrtr(prevDist, dist); bNotTerminated = BAnd(FIsGrtr(dist, eps), bNotDegenerated); }while(BAllEqTTTT(bNotTerminated)); if(BAllEqTTTT(bNotDegenerated)) { //GJK_CONTACT distance = zero; return GJK_CONTACT; } //GJK degenerated, use the previous closest point const FloatV acceptancePerc = FLoad(0.2f); const FloatV acceptanceMargin = FMul(acceptancePerc, FMin(a.getMargin(), b.getMargin())); const FloatV acceptanceDist = FSel(FIsGrtr(sumMargin, zero), sumMargin, acceptanceMargin); Vec3V closA, closB; const Vec3V n = V3Neg(prevDir);//V3Normalize(V3Neg(prevClos)); getClosestPoint(Q, A, B, prevClos, closA, closB, size); closestA = V3Sel(aQuadratic, V3ScaleAdd(n, a.getMargin(), closA), closA); closestB = V3Sel(bQuadratic, V3NegScaleSub(n, b.getMargin(), closB), closB); normal = n; dist = FMax(zero, FSub(prevDist, sumMargin)); distance = dist; return FAllGrtr(dist, acceptanceDist) ? GJK_CLOSE: GJK_CONTACT; } } } #endif
9,035
C
40.260274
183
0.728943
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKRaycast.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKRAYCAST_H #define GU_GJKRAYCAST_H #include "GuGJKType.h" #include "GuGJKSimplex.h" #include "GuConvexSupportTable.h" #include "GuGJKPenetration.h" #include "GuEPA.h" namespace physx { namespace Gu { /* ConvexA is in the local space of ConvexB lambda : the time of impact(TOI) initialLambda : the start time of impact value (disable) s : the sweep ray origin r : the normalized sweep ray direction scaled by the sweep distance. r should be in ConvexB's space normal : the contact normal inflation : the amount by which we inflate the swept shape. If the inflated shapes aren't initially-touching, the TOI will return the time at which both shapes are at a distance equal to inflation separated. If inflation is 0 the TOI will return the time at which both shapes are touching. */ template<class ConvexA, class ConvexB> bool gjkRaycast(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal _inflation) { PX_UNUSED(initialLambda); using namespace aos; const FloatV inflation = FLoad(_inflation); const Vec3V zeroV = V3Zero(); const FloatV zero = FZero(); const FloatV one = FOne(); const BoolV bTrue = BTTTT(); const FloatV maxDist = FLoad(PX_MAX_REAL); FloatV _lambda = zero;//initialLambda; Vec3V x = V3ScaleAdd(r, _lambda, s); PxU32 size=1; //const Vec3V dir = V3Sub(a.getCenter(), b.getCenter()); const Vec3V _initialSearchDir = V3Sel(FIsGrtr(V3Dot(initialDir, initialDir), FEps()), initialDir, V3UnitX()); const Vec3V initialSearchDir = V3Normalize(_initialSearchDir); const Vec3V initialSupportA(a.ConvexA::support(V3Neg(initialSearchDir))); const Vec3V initialSupportB( b.ConvexB::support(initialSearchDir)); Vec3V Q[4] = {V3Sub(initialSupportA, initialSupportB), zeroV, zeroV, zeroV}; //simplex set Vec3V A[4] = {initialSupportA, zeroV, zeroV, zeroV}; //ConvexHull a simplex set Vec3V B[4] = {initialSupportB, zeroV, zeroV, zeroV}; //ConvexHull b simplex set Vec3V v = V3Neg(Q[0]); Vec3V supportA = initialSupportA; Vec3V supportB = initialSupportB; Vec3V support = Q[0]; const FloatV minMargin = FMin(a.ConvexA::getSweepMargin(), b.ConvexB::getSweepMargin()); const FloatV eps1 = FMul(minMargin, FLoad(0.1f)); const FloatV inflationPlusEps(FAdd(eps1, inflation)); const FloatV eps2 = FMul(eps1, eps1); const FloatV inflation2 = FMul(inflationPlusEps, inflationPlusEps); Vec3V clos(Q[0]); Vec3V preClos = clos; //Vec3V closA(initialSupportA); FloatV sDist = V3Dot(v, v); FloatV minDist = sDist; //Vec3V closAA = initialSupportA; //Vec3V closBB = initialSupportB; BoolV bNotTerminated = FIsGrtr(sDist, eps2); BoolV bNotDegenerated = bTrue; Vec3V nor = v; while(BAllEqTTTT(bNotTerminated)) { minDist = sDist; preClos = clos; const Vec3V vNorm = V3Normalize(v); const Vec3V nvNorm = V3Neg(vNorm); supportA=a.ConvexA::support(vNorm); supportB=V3Add(x, b.ConvexB::support(nvNorm)); //calculate the support point support = V3Sub(supportA, supportB); const Vec3V w = V3Neg(support); const FloatV vw = FSub(V3Dot(vNorm, w), inflationPlusEps); if(FAllGrtr(vw, zero)) { const FloatV vr = V3Dot(vNorm, r); if(FAllGrtrOrEq(vr, zero)) { return false; } else { const FloatV _oldLambda = _lambda; _lambda = FSub(_lambda, FDiv(vw, vr)); if(FAllGrtr(_lambda, _oldLambda)) { if(FAllGrtr(_lambda, one)) { return false; } const Vec3V bPreCenter = x; x = V3ScaleAdd(r, _lambda, s); const Vec3V offSet =V3Sub(x, bPreCenter); const Vec3V b0 = V3Add(B[0], offSet); const Vec3V b1 = V3Add(B[1], offSet); const Vec3V b2 = V3Add(B[2], offSet); B[0] = b0; B[1] = b1; B[2] = b2; Q[0]=V3Sub(A[0], b0); Q[1]=V3Sub(A[1], b1); Q[2]=V3Sub(A[2], b2); supportB = V3Add(x, b.ConvexB::support(nvNorm)); support = V3Sub(supportA, supportB); minDist = maxDist; nor = v; //size=0; } } } PX_ASSERT(size < 4); A[size]=supportA; B[size]=supportB; Q[size++]=support; //calculate the closest point between two convex hull clos = GJKCPairDoSimplex(Q, A, B, support, size); v = V3Neg(clos); sDist = V3Dot(clos, clos); bNotDegenerated = FIsGrtr(minDist, sDist); bNotTerminated = BAnd(FIsGrtr(sDist, inflation2), bNotDegenerated); } const BoolV aQuadratic = a.isMarginEqRadius(); //ML:if the Minkowski sum of two objects are too close to the original(eps2 > sDist), we can't take v because we will lose lots of precision. Therefore, we will take //previous configuration's normal which should give us a reasonable approximation. This effectively means that, when we do a sweep with inflation, we always keep v because //the shapes converge separated. If we do a sweep without inflation, we will usually use the previous configuration's normal. nor = V3Sel(BAnd(FIsGrtr(sDist, eps2), bNotDegenerated), v, nor); nor = V3Neg(V3NormalizeSafe(nor, V3Zero())); normal = nor; lambda = _lambda; const Vec3V closestP = V3Sel(bNotDegenerated, clos, preClos); Vec3V closA = zeroV, closB = zeroV; getClosestPoint(Q, A, B, closestP, closA, closB, size); closestA = V3Sel(aQuadratic, V3NegScaleSub(nor, a.getMargin(), closA), closA); return true; } /* ConvexA is in the local space of ConvexB lambda : the time of impact(TOI) initialLambda : the start time of impact value (disable) s : the sweep ray origin in ConvexB's space r : the normalized sweep ray direction scaled by the sweep distance. r should be in ConvexB's space normal : the contact normal in ConvexB's space closestA : the tounching contact in ConvexB's space inflation : the amount by which we inflate the swept shape. If the inflated shapes aren't initially-touching, the TOI will return the time at which both shapes are at a distance equal to inflation separated. If inflation is 0 the TOI will return the time at which both shapes are touching. */ template<class ConvexA, class ConvexB> bool gjkRaycastPenetration(const ConvexA& a, const ConvexB& b, const aos::Vec3VArg initialDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal _inflation, const bool initialOverlap) { using namespace aos; Vec3V closA; Vec3V norm; FloatV _lambda; if(gjkRaycast(a, b, initialDir, initialLambda, s, r, _lambda, norm, closA, _inflation)) { const FloatV zero = FZero(); lambda = _lambda; if(FAllEq(_lambda, zero) && initialOverlap) { //time of impact is zero, the sweep shape is intesect, use epa to get the normal and contact point const FloatV contactDist = getSweepContactEps(a.getMargin(), b.getMargin()); FloatV sDist(zero); PxU8 aIndices[4]; PxU8 bIndices[4]; PxU8 size=0; GjkOutput output; //PX_COMPILE_TIME_ASSERT(typename Shrink<ConvexB>::Type != Gu::BoxV); #ifdef USE_VIRTUAL_GJK GjkStatus status = gjkPenetration<ConvexA, ConvexB>(a, b, #else typename ConvexA::ConvexGeomType convexA = a.getGjkConvex(); typename ConvexB::ConvexGeomType convexB = b.getGjkConvex(); GjkStatus status = gjkPenetration<typename ConvexA::ConvexGeomType, typename ConvexB::ConvexGeomType>(convexA, convexB, #endif initialDir, contactDist, false, aIndices, bIndices, size, output); //norm = V3Neg(norm); if(status == GJK_CONTACT) { closA = output.closestA; sDist = output.penDep; norm = output.normal; } else if(status == EPA_CONTACT) { status = epaPenetration(a, b, aIndices, bIndices, size, false, FLoad(1.f), output); if (status == EPA_CONTACT || status == EPA_DEGENERATE) { closA = output.closestA; sDist = output.penDep; norm = output.normal; } else { //ML: if EPA fail, we will use the ray direction as the normal and set pentration to be zero closA = V3Zero(); sDist = zero; norm = V3Normalize(V3Neg(r)); } } else { //ML:: this will be gjk degenerate case. However, we can still //reply on the previous iteration's closest feature information closA = output.closestA; sDist = output.penDep; norm = output.normal; } lambda = FMin(zero, sDist); } closestA = closA; normal = norm; return true; } return false; } } } #endif
10,397
C
34.979239
254
0.692219
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKUtil.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_GJKUTIL_H #define GU_GJKUTIL_H #include "foundation/PxVecMath.h" /* This file is used to avoid the inner loop cross DLL calls */ namespace physx { namespace Gu { enum GjkStatus { GJK_NON_INTERSECT, // two shapes doesn't intersect GJK_CLOSE, // two shapes doesn't intersect and gjk algorithm will return closest point information GJK_CONTACT, // two shapes overlap within margin GJK_UNDEFINED, // undefined status GJK_DEGENERATE, // gjk can't converage EPA_CONTACT, // two shapes intersect EPA_DEGENERATE, // epa can't converage EPA_FAIL // epa fail to construct an initial polygon to work with }; struct GjkOutput { public: GjkOutput() { using namespace aos; closestA = closestB = normal = V3Zero(); penDep = FZero(); } aos::Vec3V closestA; aos::Vec3V closestB; aos::Vec3V normal; aos::Vec3V searchDir; aos::FloatV penDep; }; }//Gu }//physx #endif
2,598
C
33.653333
101
0.747113
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/gjk/GuGJKTest.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 "GuGJK.h" #include "GuGJKRaycast.h" #include "GuGJKPenetration.h" #include "GuGJKTest.h" namespace physx { namespace Gu { using namespace aos; GjkStatus testGjk(const GjkConvex& a, const GjkConvex& b, const Vec3VArg initialSearchDir, const FloatVArg contactDist, Vec3V& closestA, Vec3V& closestB, Vec3V& normal, FloatV& dist) { return gjk<GjkConvex, GjkConvex>(a, b, initialSearchDir, contactDist, closestA, closestB, normal, dist); } bool testGjkRaycast(const GjkConvex& a, const GjkConvex& b, const Vec3VArg initialSearchDir, const aos::FloatVArg initialLambda, const aos::Vec3VArg s, const aos::Vec3VArg r, aos::FloatV& lambda, aos::Vec3V& normal, aos::Vec3V& closestA, const PxReal inflation) { return gjkRaycast(a, b, initialSearchDir, initialLambda, s, r, lambda, normal, closestA, inflation); } GjkStatus testGjkPenetration(const GjkConvex& a, const GjkConvex& b, const Vec3VArg initialSearchDir, const FloatVArg contactDist, PxU8* aIndices, PxU8* bIndices, PxU8& size, GjkOutput& output) { return gjkPenetration<GjkConvex, GjkConvex>(a, b, initialSearchDir, contactDist, true, aIndices, bIndices, size, output); } GjkStatus testEpaPenetration(const GjkConvex& a, const GjkConvex& b, const PxU8* aIndices, const PxU8* bIndices, const PxU8 size, GjkOutput& output) { return epaPenetration(a, b, aIndices, bIndices, size, true, aos::FLoad(1.f), output); } } }
3,091
C++
45.149253
196
0.765448
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuFeatureCode.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 "GuConvexEdgeFlags.h" #include "GuFeatureCode.h" using namespace physx; using namespace Gu; static FeatureCode computeFeatureCode(PxReal u, PxReal v) { // Analysis if(u==0.0f) { if(v==0.0f) { // Vertex 0 return FC_VERTEX0; } else if(v==1.0f) { // Vertex 2 return FC_VERTEX2; } else { // Edge 0-2 return FC_EDGE20; } } else if(u==1.0f) { if(v==0.0f) { // Vertex 1 return FC_VERTEX1; } } else { if(v==0.0f) { // Edge 0-1 return FC_EDGE01; } else { if((u+v)>=0.9999f) { // Edge 1-2 return FC_EDGE12; } else { // Face return FC_FACE; } } } return FC_UNDEFINED; } bool Gu::selectNormal(PxU8 data, PxReal u, PxReal v) { bool useFaceNormal = false; const FeatureCode FC = computeFeatureCode(u, v); switch(FC) { case FC_VERTEX0: if(!(data & (Gu::ETD_CONVEX_EDGE_01|Gu::ETD_CONVEX_EDGE_20))) useFaceNormal = true; break; case FC_VERTEX1: if(!(data & (Gu::ETD_CONVEX_EDGE_01|Gu::ETD_CONVEX_EDGE_12))) useFaceNormal = true; break; case FC_VERTEX2: if(!(data & (Gu::ETD_CONVEX_EDGE_12|Gu::ETD_CONVEX_EDGE_20))) useFaceNormal = true; break; case FC_EDGE01: if(!(data & Gu::ETD_CONVEX_EDGE_01)) useFaceNormal = true; break; case FC_EDGE12: if(!(data & Gu::ETD_CONVEX_EDGE_12)) useFaceNormal = true; break; case FC_EDGE20: if(!(data & Gu::ETD_CONVEX_EDGE_20)) useFaceNormal = true; break; case FC_FACE: useFaceNormal = true; break; case FC_UNDEFINED: break; }; return useFaceNormal; }
3,284
C++
24.664062
74
0.683009
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleCapsule.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 "geomutils/PxContactBuffer.h" #include "GuDistanceSegmentSegment.h" #include "GuContactMethodImpl.h" #include "GuInternal.h" using namespace physx; bool Gu::contactCapsuleCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxCapsuleGeometry& capsuleGeom0 = checkedCast<PxCapsuleGeometry>(shape0); const PxCapsuleGeometry& capsuleGeom1 = checkedCast<PxCapsuleGeometry>(shape1); // PT: get capsules in local space PxVec3 dir[2]; Segment segment[2]; { const PxVec3 capsuleLocalSegment0 = getCapsuleHalfHeightVector(transform0, capsuleGeom0); const PxVec3 capsuleLocalSegment1 = getCapsuleHalfHeightVector(transform1, capsuleGeom1); const PxVec3 delta = transform1.p - transform0.p; segment[0].p0 = capsuleLocalSegment0; segment[0].p1 = -capsuleLocalSegment0; dir[0] = -capsuleLocalSegment0*2.0f; segment[1].p0 = capsuleLocalSegment1 + delta; segment[1].p1 = -capsuleLocalSegment1 + delta; dir[1] = -capsuleLocalSegment1*2.0f; } // PT: compute distance between capsules' segments PxReal s,t; const PxReal squareDist = distanceSegmentSegmentSquared(segment[0], segment[1], &s, &t); const PxReal radiusSum = capsuleGeom0.radius + capsuleGeom1.radius; const PxReal inflatedSum = radiusSum + params.mContactDistance; const PxReal inflatedSumSquared = inflatedSum*inflatedSum; if(squareDist >= inflatedSumSquared) return false; // PT: TODO: optimize this away PxReal segLen[2]; segLen[0] = dir[0].magnitude(); segLen[1] = dir[1].magnitude(); if (segLen[0]) dir[0] *= 1.0f / segLen[0]; if (segLen[1]) dir[1] *= 1.0f / segLen[1]; if (PxAbs(dir[0].dot(dir[1])) > 0.9998f) //almost parallel, ca. 1 degree difference --> generate two contact points at ends { PxU32 numCons = 0; PxReal segLenEps[2]; segLenEps[0] = segLen[0] * 0.001f;//0.1% error is ok. segLenEps[1] = segLen[1] * 0.001f; //project the two end points of each onto the axis of the other and take those 4 points. //we could also generate a single normal at the single closest point, but this would be 'unstable'. for (PxU32 destShapeIndex = 0; destShapeIndex < 2; destShapeIndex ++) { for (PxU32 startEnd = 0; startEnd < 2; startEnd ++) { const PxU32 srcShapeIndex = 1-destShapeIndex; //project start/end of srcShapeIndex onto destShapeIndex. PxVec3 pos[2]; pos[destShapeIndex] = startEnd ? segment[srcShapeIndex].p1 : segment[srcShapeIndex].p0; const PxReal p = dir[destShapeIndex].dot(pos[destShapeIndex] - segment[destShapeIndex].p0); if (p >= -segLenEps[destShapeIndex] && p <= (segLen[destShapeIndex] + segLenEps[destShapeIndex])) { pos[srcShapeIndex] = p * dir[destShapeIndex] + segment[destShapeIndex].p0; PxVec3 normal = pos[1] - pos[0]; const PxReal normalLenSq = normal.magnitudeSquared(); if (normalLenSq > 1e-6f && normalLenSq < inflatedSumSquared) { const PxReal distance = PxSqrt(normalLenSq); normal *= 1.0f/distance; PxVec3 point = pos[1] - normal * (srcShapeIndex ? capsuleGeom1 : capsuleGeom0).radius; point += transform0.p; contactBuffer.contact(point, normal, distance - radiusSum); numCons++; } } } } if (numCons) //if we did not have contacts, then we may have the case where they are parallel, but are stacked end to end, in which case the old code will generate good contacts. return true; } // Collision response PxVec3 pos1 = segment[0].getPointAt(s); PxVec3 pos2 = segment[1].getPointAt(t); PxVec3 normal = pos1 - pos2; const PxReal normalLenSq = normal.magnitudeSquared(); if (normalLenSq < 1e-6f) { // PT: TODO: revisit this. "FW" sounds old. // Zero normal -> pick the direction of segment 0. // Not always accurate but consistent with FW. if (segLen[0] > 1e-6f) normal = dir[0]; else normal = PxVec3(1.0f, 0.0f, 0.0f); } else { normal *= PxRecipSqrt(normalLenSq); } pos1 += transform0.p; contactBuffer.contact(pos1 - normal * capsuleGeom0.radius, normal, PxSqrt(squareDist) - radiusSum); return true; }
5,760
C++
37.664429
180
0.722743
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPlaneConvex.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 "geomutils/PxContactBuffer.h" #include "GuConvexMeshData.h" #include "GuContactMethodImpl.h" #include "GuConvexMesh.h" #include "CmScaling.h" #include "CmMatrix34.h" using namespace physx; using namespace Cm; bool Gu::contactPlaneConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_UNUSED(shape0); // Get actual shape data //const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape0); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); const ConvexHullData* hullData = _getHullData(shapeConvex); const PxVec3* PX_RESTRICT hullVertices = hullData->getHullVertices(); PxU32 numHullVertices = hullData->mNbHullVertices; // PxPrefetch128(hullVertices); // Plane is implicitly <1,0,0> 0 in localspace const Matrix34FromTransform convexToPlane0 (transform0.transformInv(transform1)); const PxMat33 convexToPlane_rot(convexToPlane0[0], convexToPlane0[1], convexToPlane0[2] ); bool idtScale = shapeConvex.scale.isIdentity(); FastVertex2ShapeScaling convexScaling; // PT: TODO: remove default ctor if(!idtScale) convexScaling.init(shapeConvex.scale); const PxMat34 convexToPlane(convexToPlane_rot * convexScaling.getVertex2ShapeSkew(), convexToPlane0[3]); //convexToPlane = context.mVertex2ShapeSkew[1].getVertex2WorldSkew(convexToPlane); const Matrix34FromTransform planeToW(transform0); // This is rather brute-force bool status = false; const PxVec3 contactNormal = -planeToW.m.column0; while(numHullVertices--) { const PxVec3& vertex = *hullVertices++; // if(numHullVertices) // PxPrefetch128(hullVertices); const PxVec3 pointInPlane = convexToPlane.transform(vertex); //TODO: this multiply could be factored out! if(pointInPlane.x <= params.mContactDistance) { // const PxVec3 pointInW = planeToW.transform(pointInPlane); // contactBuffer.contact(pointInW, -planeToW.m.column0, pointInPlane.x); status = true; PxContactPoint* PX_RESTRICT pt = contactBuffer.contact(); if(pt) { pt->normal = contactNormal; pt->point = planeToW.transform(pointInPlane); pt->separation = pointInPlane.x; pt->internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX; } } } return status; }
3,936
C++
38.767676
108
0.762195
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPlaneCapsule.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 "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "GuInternal.h" #include "GuSegment.h" using namespace physx; bool Gu::contactPlaneCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_UNUSED(shape0); // Get actual shape data //const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape0); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape1); const PxTransform capsuleToPlane = transform0.transformInv(transform1); //Capsule in plane space Segment segment; getCapsuleSegment(capsuleToPlane, shapeCapsule, segment); const PxVec3 negPlaneNormal = transform0.q.getBasisVector0(); bool contact = false; const PxReal separation0 = segment.p0.x - shapeCapsule.radius; const PxReal separation1 = segment.p1.x - shapeCapsule.radius; if(separation0 <= params.mContactDistance) { const PxVec3 temp(segment.p0.x - shapeCapsule.radius, segment.p0.y, segment.p0.z); const PxVec3 point = transform0.transform(temp); contactBuffer.contact(point, -negPlaneNormal, separation0); contact = true; } if(separation1 <= params.mContactDistance) { const PxVec3 temp(segment.p1.x - shapeCapsule.radius, segment.p1.y, segment.p1.z); const PxVec3 point = transform0.transform(temp); contactBuffer.contact(point, -negPlaneNormal, separation1); contact = true; } return contact; }
3,096
C++
40.293333
84
0.766796
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereSphere.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 "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" using namespace physx; bool Gu::contactSphereSphere(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxSphereGeometry& sphereGeom0 = checkedCast<PxSphereGeometry>(shape0); const PxSphereGeometry& sphereGeom1 = checkedCast<PxSphereGeometry>(shape1); PxVec3 delta = transform0.p - transform1.p; const PxReal distanceSq = delta.magnitudeSquared(); const PxReal radiusSum = sphereGeom0.radius + sphereGeom1.radius; const PxReal inflatedSum = radiusSum + params.mContactDistance; if(distanceSq >= inflatedSum*inflatedSum) return false; // We do a *manual* normalization to check for singularity condition const PxReal magn = PxSqrt(distanceSq); if(magn<=0.00001f) delta = PxVec3(1.0f, 0.0f, 0.0f); // PT: spheres are exactly overlapping => can't create normal => pick up random one else delta *= 1.0f/magn; // PT: TODO: why is this formula different from the original code? const PxVec3 contact = delta * ((sphereGeom0.radius + magn - sphereGeom1.radius)*-0.5f) + transform0.p; contactBuffer.contact(contact, delta, magn - radiusSum); return true; }
2,874
C++
44.63492
119
0.761308
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPlaneBox.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/PxUnionCast.h" #include "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "CmMatrix34.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Cm; bool Gu::contactPlaneBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); PX_UNUSED(shape0); // Get actual shape data //const PxPlaneGeometry& shapePlane = checkedCast<PxPlaneGeometry>(shape0); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); const PxVec3 negPlaneNormal = -transform0.q.getBasisVector0(); //Make sure we have a normalized plane //PX_ASSERT(PxAbs(shape0.mNormal.magnitudeSquared() - 1.0f) < 0.000001f); const Matrix34FromTransform boxMatrix(transform1); const Matrix34FromTransform boxToPlane(transform0.transformInv(transform1)); PxVec3 point; PX_ASSERT(contactBuffer.count==0); /* for(int vx=-1; vx<=1; vx+=2) for(int vy=-1; vy<=1; vy+=2) for(int vz=-1; vz<=1; vz+=2) { //point = boxToPlane.transform(PxVec3(shapeBox.halfExtents.x*vx, shapeBox.halfExtents.y*vy, shapeBox.halfExtents.z*vz)); //PxReal planeEq = point.x; //Optimized a bit point.set(shapeBox.halfExtents.x*vx, shapeBox.halfExtents.y*vy, shapeBox.halfExtents.z*vz); const PxReal planeEq = boxToPlane.m.column0.x*point.x + boxToPlane.m.column1.x*point.y + boxToPlane.m.column2.x*point.z + boxToPlane.p.x; if(planeEq <= contactDistance) { contactBuffer.contact(boxMatrix.transform(point), negPlaneNormal, planeEq); //no point in making more than 4 contacts. if (contactBuffer.count >= 6) //was: 4) actually, with strong interpenetration more than just the bottom surface goes through, //and we want to find the *deepest* 4 vertices, really. return true; } }*/ // PT: the above code is shock full of LHS/FCMPs. And there's no point in limiting the number of contacts to 6 when the max possible is 8. const PxReal limit = params.mContactDistance - boxToPlane.p.x; const PxReal dx = shapeBox.halfExtents.x; const PxReal dy = shapeBox.halfExtents.y; const PxReal dz = shapeBox.halfExtents.z; const PxReal bxdx = boxToPlane.m.column0.x * dx; const PxReal bxdy = boxToPlane.m.column1.x * dy; const PxReal bxdz = boxToPlane.m.column2.x * dz; PxReal depths[8]; depths[0] = bxdx + bxdy + bxdz - limit; depths[1] = bxdx + bxdy - bxdz - limit; depths[2] = bxdx - bxdy + bxdz - limit; depths[3] = bxdx - bxdy - bxdz - limit; depths[4] = - bxdx + bxdy + bxdz - limit; depths[5] = - bxdx + bxdy - bxdz - limit; depths[6] = - bxdx - bxdy + bxdz - limit; depths[7] = - bxdx - bxdy - bxdz - limit; //const PxU32* binary = reinterpret_cast<const PxU32*>(depths); const PxU32* binary = PxUnionCast<PxU32*, PxF32*>(depths); if(binary[0] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, dy, dz)), negPlaneNormal, depths[0] + params.mContactDistance); if(binary[1] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, dy, -dz)), negPlaneNormal, depths[1] + params.mContactDistance); if(binary[2] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, -dy, dz)), negPlaneNormal, depths[2] + params.mContactDistance); if(binary[3] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(dx, -dy, -dz)), negPlaneNormal, depths[3] + params.mContactDistance); if(binary[4] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, dy, dz)), negPlaneNormal, depths[4] + params.mContactDistance); if(binary[5] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, dy, -dz)), negPlaneNormal, depths[5] + params.mContactDistance); if(binary[6] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, -dy, dz)), negPlaneNormal, depths[6] + params.mContactDistance); if(binary[7] & PX_SIGN_BITMASK) contactBuffer.contact(boxMatrix.transform(PxVec3(-dx, -dy, -dz)), negPlaneNormal, depths[7] + params.mContactDistance); return contactBuffer.count > 0; }
5,739
C++
45.666666
141
0.731835
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereBox.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 "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" using namespace physx; //This version is ported 1:1 from novodex static PX_FORCE_INLINE bool ContactSphereBox(const PxVec3& sphereOrigin, PxReal sphereRadius, const PxVec3& boxExtents, // const PxcCachedTransforms& boxCacheTransform, const PxTransform32& boxTransform, PxVec3& point, PxVec3& normal, PxReal& separation, PxReal contactDistance) { // const PxTransform& boxTransform = boxCacheTransform.getShapeToWorld(); //returns true on contact const PxVec3 delta = sphereOrigin - boxTransform.p; // s1.center - s2.center; PxVec3 dRot = boxTransform.rotateInv(delta); //transform delta into OBB body coords. //check if delta is outside ABB - and clip the vector to the ABB. bool outside = false; if (dRot.x < -boxExtents.x) { outside = true; dRot.x = -boxExtents.x; } else if (dRot.x > boxExtents.x) { outside = true; dRot.x = boxExtents.x; } if (dRot.y < -boxExtents.y) { outside = true; dRot.y = -boxExtents.y; } else if (dRot.y > boxExtents.y) { outside = true; dRot.y = boxExtents.y; } if (dRot.z < -boxExtents.z) { outside = true; dRot.z =-boxExtents.z; } else if (dRot.z > boxExtents.z) { outside = true; dRot.z = boxExtents.z; } if (outside) //if clipping was done, sphere center is outside of box. { point = boxTransform.rotate(dRot); //get clipped delta back in world coords. normal = delta - point; //what we clipped away. const PxReal lenSquared = normal.magnitudeSquared(); const PxReal inflatedDist = sphereRadius + contactDistance; if (lenSquared > inflatedDist * inflatedDist) return false; //disjoint //normalize to make it into the normal: separation = PxRecipSqrt(lenSquared); normal *= separation; separation *= lenSquared; //any plane that touches the sphere is tangential, so a vector from contact point to sphere center defines normal. //we could also use point here, which has same direction. //this is either a faceFace or a vertexFace contact depending on whether the box's face or vertex collides, but we did not distinguish. //We'll just use vertex face for now, this info isn't really being used anyway. //contact point is point on surface of cube closest to sphere center. point += boxTransform.p; separation -= sphereRadius; return true; } else { //center is in box, we definitely have a contact. PxVec3 locNorm; //local coords contact normal /*const*/ PxVec3 absdRot; absdRot = PxVec3(PxAbs(dRot.x), PxAbs(dRot.y), PxAbs(dRot.z)); /*const*/ PxVec3 distToSurface = boxExtents - absdRot; //dist from embedded center to box surface along 3 dimensions. //find smallest element of distToSurface if (distToSurface.y < distToSurface.x) { if (distToSurface.y < distToSurface.z) { //y locNorm = PxVec3(0.0f, dRot.y > 0.0f ? 1.0f : -1.0f, 0.0f); separation = -distToSurface.y; } else { //z locNorm = PxVec3(0.0f,0.0f, dRot.z > 0.0f ? 1.0f : -1.0f); separation = -distToSurface.z; } } else { if (distToSurface.x < distToSurface.z) { //x locNorm = PxVec3(dRot.x > 0.0f ? 1.0f : -1.0f, 0.0f, 0.0f); separation = -distToSurface.x; } else { //z locNorm = PxVec3(0.0f,0.0f, dRot.z > 0.0f ? 1.0f : -1.0f); separation = -distToSurface.z; } } //separation so far is just the embedding of the center point; we still have to push out all of the radius. point = sphereOrigin; normal = boxTransform.rotate(locNorm); separation -= sphereRadius; return true; } } bool Gu::contactSphereBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxSphereGeometry& sphereGeom = checkedCast<PxSphereGeometry>(shape0); const PxBoxGeometry& boxGeom = checkedCast<PxBoxGeometry>(shape1); PxVec3 normal; PxVec3 point; PxReal separation; if(!ContactSphereBox(transform0.p, sphereGeom.radius, boxGeom.halfExtents, transform1, point, normal, separation, params.mContactDistance)) return false; contactBuffer.contact(point, normal, separation); return true; }
5,868
C++
32.729885
140
0.709271
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleMesh.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 "geomutils/PxContactBuffer.h" #include "GuIntersectionEdgeEdge.h" #include "GuDistanceSegmentTriangle.h" #include "GuIntersectionRayTriangle.h" #include "GuIntersectionTriangleBox.h" #include "GuInternal.h" #include "GuContactMethodImpl.h" #include "GuFeatureCode.h" #include "GuMidphaseInterface.h" #include "GuEntityReport.h" #include "GuHeightFieldUtil.h" #include "GuConvexEdgeFlags.h" #include "GuBox.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; #define DEBUG_RENDER_MESHCONTACTS 0 #if DEBUG_RENDER_MESHCONTACTS #include "PxPhysics.h" #include "PxScene.h" #endif #define USE_AABB_TRI_CULLING //#define USE_CAPSULE_TRI_PROJ_CULLING //#define USE_CAPSULE_TRI_SAT_CULLING #define VISUALIZE_TOUCHED_TRIS 0 #define VISUALIZE_CULLING_BOX 0 #if VISUALIZE_TOUCHED_TRIS #include "PxRenderOutput.h" #include "PxsContactManager.h" #include "PxsContext.h" static void gVisualizeLine(const PxVec3& a, const PxVec3& b, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat44 m = PxMat44::identity(); PxRenderOutput& out = context.mRenderOutput; out << color << m << PxRenderOutput::LINES << a << b; } static void gVisualizeTri(const PxVec3& a, const PxVec3& b, const PxVec3& c, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat44 m = PxMat44::identity(); PxRenderOutput& out = context.mRenderOutput; out << color << m << PxRenderOutput::TRIANGLES << a << b << c; } static PxU32 gColors[8] = { 0xff0000ff, 0xff00ff00, 0xffff0000, 0xff00ffff, 0xffff00ff, 0xffffff00, 0xff000080, 0xff008000}; #endif static const float fatBoxEdgeCoeff = 0.01f; static bool PxcTestAxis(const PxVec3& axis, const Segment& segment, PxReal radius, const PxVec3* PX_RESTRICT triVerts, PxReal& depth) { // Project capsule PxReal min0 = segment.p0.dot(axis); PxReal max0 = segment.p1.dot(axis); if(min0>max0) PxSwap(min0, max0); min0 -= radius; max0 += radius; // Project triangle float Min1, Max1; { Min1 = Max1 = triVerts[0].dot(axis); const PxReal dp1 = triVerts[1].dot(axis); Min1 = physx::intrinsics::selectMin(Min1, dp1); Max1 = physx::intrinsics::selectMax(Max1, dp1); const PxReal dp2 = triVerts[2].dot(axis); Min1 = physx::intrinsics::selectMin(Min1, dp2); Max1 = physx::intrinsics::selectMax(Max1, dp2); } // Test projections if(max0<Min1 || Max1<min0) return false; const PxReal d0 = max0 - Min1; PX_ASSERT(d0>=0.0f); const PxReal d1 = Max1 - min0; PX_ASSERT(d1>=0.0f); depth = physx::intrinsics::selectMin(d0, d1); return true; } PX_FORCE_INLINE static PxVec3 PxcComputeTriangleNormal(const PxVec3* PX_RESTRICT triVerts) { return ((triVerts[0]-triVerts[1]).cross(triVerts[0]-triVerts[2])).getNormalized(); } PX_FORCE_INLINE static PxVec3 PxcComputeTriangleCenter(const PxVec3* PX_RESTRICT triVerts) { static const PxReal inv3 = 1.0f / 3.0f; return (triVerts[0] + triVerts[1] + triVerts[2]) * inv3; } static bool PxcCapsuleTriOverlap3(PxU8 edgeFlags, const Segment& segment, PxReal radius, const PxVec3* PX_RESTRICT triVerts, PxReal* PX_RESTRICT t=NULL, PxVec3* PX_RESTRICT pp=NULL) { PxReal penDepth = PX_MAX_REAL; // Test normal PxVec3 sep = PxcComputeTriangleNormal(triVerts); if(!PxcTestAxis(sep, segment, radius, triVerts, penDepth)) return false; // Test edges // ML:: use the active edge flag instead of the concave flag const PxU32 activeEdgeFlag[] = {ETD_CONVEX_EDGE_01, ETD_CONVEX_EDGE_12, ETD_CONVEX_EDGE_20}; const PxVec3 capsuleAxis = (segment.p1 - segment.p0).getNormalized(); for(PxU32 i=0;i<3;i++) { //bool active =((edgeFlags & ignoreEdgeFlag[i]) == 0); if(edgeFlags & activeEdgeFlag[i]) { const PxVec3 e0 = triVerts[i]; // const PxVec3 e1 = triVerts[(i+1)%3]; const PxVec3 e1 = triVerts[PxGetNextIndex3(i)]; const PxVec3 edge = e0 - e1; PxVec3 cross = capsuleAxis.cross(edge); if(!isAlmostZero(cross)) { cross = cross.getNormalized(); PxReal d; if(!PxcTestAxis(cross, segment, radius, triVerts, d)) return false; if(d<penDepth) { penDepth = d; sep = cross; } } } } const PxVec3 capsuleCenter = segment.computeCenter(); const PxVec3 triCenter = PxcComputeTriangleCenter(triVerts); const PxVec3 witness = capsuleCenter - triCenter; if(sep.dot(witness) < 0.0f) sep = -sep; if(t) *t = penDepth; if(pp) *pp = sep; return true; } static void PxcGenerateVFContacts( const PxMat34& meshAbsPose, PxContactBuffer& contactBuffer, const Segment& segment, const PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, PxU32 triangleIndex, PxReal contactDistance) { const PxVec3* PX_RESTRICT Ptr = &segment.p0; for(PxU32 i=0;i<2;i++) { const PxVec3& Pos = Ptr[i]; PxReal t,u,v; if(intersectRayTriangleCulling(Pos, -normal, triVerts[0], triVerts[1], triVerts[2], t, u, v, 1e-3f) && t < radius + contactDistance) { const PxVec3 Hit = meshAbsPose.transform(Pos - t * normal); const PxVec3 wn = meshAbsPose.rotate(normal); contactBuffer.contact(Hit, wn, t-radius, triangleIndex); #if DEBUG_RENDER_MESHCONTACTS PxScene *s; PxGetPhysics().getScenes(&s, 1, 0); PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer()) << PxRenderOutput::LINES << PxDebugColor::eARGB_BLUE // red << Hit << (Hit + wn * 10.0f); #endif } } } // PT: PxcGenerateEEContacts2 uses a segment-triangle distance function, which breaks when the segment // intersects the triangle, in which case you need to switch to a penetration-depth computation. // If you don't do this thin capsules don't work. static void PxcGenerateEEContacts( const PxMat34& meshAbsPose, PxContactBuffer& contactBuffer, const Segment& segment, const PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, PxU32 triangleIndex) { PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); for(PxU32 i=0;i<3;i++) { PxReal dist; PxVec3 ip; if(intersectEdgeEdge(triVerts[i], triVerts[PxGetNextIndex3(i)], -normal, s0, s1, dist, ip)) { ip = meshAbsPose.transform(ip); const PxVec3 wn = meshAbsPose.rotate(normal); contactBuffer.contact(ip, wn, - (radius + dist), triangleIndex); #if DEBUG_RENDER_MESHCONTACTS PxScene *s; PxGetPhysics().getScenes(&s, 1, 0); PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer()) << PxRenderOutput::LINES << PxDebugColor::eARGB_BLUE // red << ip << (ip + wn * 10.0f); #endif } } } static void PxcGenerateEEContacts2( const PxMat34& meshAbsPose, PxContactBuffer& contactBuffer, const Segment& segment, const PxReal radius, const PxVec3* PX_RESTRICT triVerts, const PxVec3& normal, PxU32 triangleIndex, PxReal contactDistance) { PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); for(PxU32 i=0;i<3;i++) { PxReal dist; PxVec3 ip; if(intersectEdgeEdge(triVerts[i], triVerts[PxGetNextIndex3(i)], normal, s0, s1, dist, ip) && dist < radius+contactDistance) { ip = meshAbsPose.transform(ip); const PxVec3 wn = meshAbsPose.rotate(normal); contactBuffer.contact(ip, wn, dist - radius, triangleIndex); #if DEBUG_RENDER_MESHCONTACTS PxScene *s; PxGetPhysics().getScenes(&s, 1, 0); PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer()) << PxRenderOutput::LINES << PxDebugColor::eARGB_BLUE // red << ip << (ip + wn * 10.0f); #endif } } } namespace { struct CapsuleMeshContactGeneration { PxContactBuffer& mContactBuffer; const PxMat34 mMeshAbsPose; const Segment& mMeshCapsule; #ifdef USE_AABB_TRI_CULLING PxVec3p mBC; PxVec3p mBE; #endif PxReal mInflatedRadius; PxReal mContactDistance; PxReal mShapeCapsuleRadius; CapsuleMeshContactGeneration(PxContactBuffer& contactBuffer, const PxTransform& transform1, const Segment& meshCapsule, PxReal inflatedRadius, PxReal contactDistance, PxReal shapeCapsuleRadius) : mContactBuffer (contactBuffer), mMeshAbsPose (Matrix34FromTransform(transform1)), mMeshCapsule (meshCapsule), mInflatedRadius (inflatedRadius), mContactDistance (contactDistance), mShapeCapsuleRadius (shapeCapsuleRadius) { PX_ASSERT(contactBuffer.count==0); #ifdef USE_AABB_TRI_CULLING mBC = (meshCapsule.p0 + meshCapsule.p1)*0.5f; const PxVec3p be = (meshCapsule.p0 - meshCapsule.p1)*0.5f; mBE.x = fabsf(be.x) + inflatedRadius; mBE.y = fabsf(be.y) + inflatedRadius; mBE.z = fabsf(be.z) + inflatedRadius; #endif } void processTriangle(PxU32 triangleIndex, const PxTrianglePadded& tri, PxU8 extraData/*, const PxU32* vertInds*/) { #ifdef USE_AABB_TRI_CULLING #if VISUALIZE_CULLING_BOX { PxRenderOutput& out = context.mRenderOutput; PxTransform idt = PxTransform(PxIdentity); out << idt; out << 0xffffffff; out << PxDebugBox(mBC, mBE, true); } #endif #endif const PxVec3& p0 = tri.verts[0]; const PxVec3& p1 = tri.verts[1]; const PxVec3& p2 = tri.verts[2]; #ifdef USE_AABB_TRI_CULLING // PT: this one is safe because triangle class is padded // PT: TODO: is this test really needed? Not done in midphase already? if(!intersectTriangleBox_Unsafe(mBC, mBE, p0, p1, p2)) return; #endif #ifdef USE_CAPSULE_TRI_PROJ_CULLING PxVec3 triCenter = (p0 + p1 + p2)*0.33333333f; PxVec3 delta = mBC - triCenter; PxReal depth; if(!PxcTestAxis(delta, mMeshCapsule, mInflatedRadius, tri.verts, depth)) return; #endif #if VISUALIZE_TOUCHED_TRIS gVisualizeTri(p0, p1, p2, context, PxDebugColor::eARGB_RED); #endif #ifdef USE_CAPSULE_TRI_SAT_CULLING PxVec3 SepAxis; if(!PxcCapsuleTriOverlap3(extraData, mMeshCapsule, mInflatedRadius, tri.verts, NULL, &SepAxis)) return; #endif PxReal t,u,v; const PxVec3 p1_p0 = p1 - p0; const PxVec3 p2_p0 = p2 - p0; const PxReal squareDist = distanceSegmentTriangleSquared(mMeshCapsule, p0, p1_p0, p2_p0, &t, &u, &v); // PT: do cheaper test first! if(squareDist >= mInflatedRadius*mInflatedRadius) return; // PT: backface culling without the normalize // PT: TODO: consider doing before the segment-triangle distance test if it's cheaper const PxVec3 planeNormal = p1_p0.cross(p2_p0); const PxF32 planeD = planeNormal.dot(p0); // PT: actually -d compared to PxcPlane if(planeNormal.dot(mBC) < planeD) return; if(squareDist > 0.001f*0.001f) { // Contact information PxVec3 normal; if(selectNormal(extraData, u, v)) { normal = planeNormal.getNormalized(); } else { const PxVec3 pointOnTriangle = computeBarycentricPoint(p0, p1, p2, u, v); const PxVec3 pointOnSegment = mMeshCapsule.getPointAt(t); normal = pointOnSegment - pointOnTriangle; const PxReal l = normal.magnitude(); if(l == 0.0f) return; normal = normal / l; } PxcGenerateEEContacts2(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, normal, triangleIndex, mContactDistance); PxcGenerateVFContacts(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, normal, triangleIndex, mContactDistance); } else { PxVec3 SepAxis; if(!PxcCapsuleTriOverlap3(extraData, mMeshCapsule, mInflatedRadius, tri.verts, NULL, &SepAxis)) return; PxcGenerateEEContacts(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, SepAxis, triangleIndex); PxcGenerateVFContacts(mMeshAbsPose, mContactBuffer, mMeshCapsule, mShapeCapsuleRadius, tri.verts, SepAxis, triangleIndex, mContactDistance); } } private: CapsuleMeshContactGeneration& operator=(const CapsuleMeshContactGeneration&); }; struct CapsuleMeshContactGenerationCallback_NoScale : MeshHitCallback<PxGeomRaycastHit> { CapsuleMeshContactGeneration mGeneration; const TriangleMesh* mMeshData; CapsuleMeshContactGenerationCallback_NoScale( PxContactBuffer& contactBuffer, const PxTransform& transform1, const Segment& meshCapsule, PxReal inflatedRadius, PxReal contactDistance, PxReal shapeCapsuleRadius, const TriangleMesh* meshData ) : MeshHitCallback<PxGeomRaycastHit> (CallbackMode::eMULTIPLE), mGeneration (contactBuffer, transform1, meshCapsule, inflatedRadius, contactDistance, shapeCapsuleRadius), mMeshData (meshData) { PX_ASSERT(contactBuffer.count==0); } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* /*vInds*/) { PxTrianglePadded tri; // PT: TODO: revisit this, avoid the copy tri.verts[0] = v0; tri.verts[1] = v1; tri.verts[2] = v2; const PxU32 triangleIndex = hit.faceIndex; //ML::set all the edges to be active, if the mExtraTrigData exist, we overwrite this flag const PxU8 extraData = getConvexEdgeFlags(mMeshData->getExtraTrigData(), triangleIndex); mGeneration.processTriangle(triangleIndex, tri, extraData); return true; } private: CapsuleMeshContactGenerationCallback_NoScale& operator=(const CapsuleMeshContactGenerationCallback_NoScale&); }; struct CapsuleMeshContactGenerationCallback_Scale : CapsuleMeshContactGenerationCallback_NoScale { const FastVertex2ShapeScaling& mScaling; CapsuleMeshContactGenerationCallback_Scale( PxContactBuffer& contactBuffer, const PxTransform& transform1, const Segment& meshCapsule, PxReal inflatedRadius, const FastVertex2ShapeScaling& scaling, PxReal contactDistance, PxReal shapeCapsuleRadius, const TriangleMesh* meshData ) : CapsuleMeshContactGenerationCallback_NoScale(contactBuffer, transform1, meshCapsule, inflatedRadius, contactDistance, shapeCapsuleRadius, meshData), mScaling (scaling) { } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* /*vInds*/) { PxTrianglePadded tri; getScaledVertices(tri.verts, v0, v1, v2, false, mScaling); const PxU32 triangleIndex = hit.faceIndex; //ML::set all the edges to be active, if the mExtraTrigData exist, we overwrite this flag PxU8 extraData = getConvexEdgeFlags(mMeshData->getExtraTrigData(), triangleIndex); if(mScaling.flipsNormal()) flipConvexEdgeFlags(extraData); mGeneration.processTriangle(triangleIndex, tri, extraData); return true; } private: CapsuleMeshContactGenerationCallback_Scale& operator=(const CapsuleMeshContactGenerationCallback_Scale&); }; } // PT: computes local capsule without going to world-space static PX_FORCE_INLINE Segment computeLocalCapsule(const PxTransform& transform0, const PxTransform& transform1, const PxCapsuleGeometry& shapeCapsule) { const PxVec3 halfHeight = getCapsuleHalfHeightVector(transform0, shapeCapsule); const PxVec3 delta = transform1.p - transform0.p; return Segment( transform1.rotateInv(halfHeight - delta), transform1.rotateInv(-halfHeight - delta)); } bool Gu::contactCapsuleMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; //AM: inflate! const Segment meshCapsule = computeLocalCapsule(transform0, transform1, shapeCapsule); const TriangleMesh* meshData = _getMeshData(shapeMesh); //bound the capsule in shape space by an OBB: Box queryBox; { const Capsule queryCapsule(meshCapsule, inflatedRadius); queryBox.create(queryCapsule); } if(shapeMesh.scale.isIdentity()) { CapsuleMeshContactGenerationCallback_NoScale callback(contactBuffer, transform1, meshCapsule, inflatedRadius, params.mContactDistance, shapeCapsule.radius, meshData); // PT: TODO: switch to capsule query here Midphase::intersectOBB(meshData, queryBox, callback, true); } else { const FastVertex2ShapeScaling meshScaling(shapeMesh.scale); CapsuleMeshContactGenerationCallback_Scale callback(contactBuffer, transform1, meshCapsule, inflatedRadius, meshScaling, params.mContactDistance, shapeCapsule.radius, meshData); //switched from capsuleCollider to boxCollider so we can support nonuniformly scaled meshes by scaling the query region: //apply the skew transform to the box: meshScaling.transformQueryBounds(queryBox.center, queryBox.extents, queryBox.rot); Midphase::intersectOBB(meshData, queryBox, callback, true); } return contactBuffer.count > 0; } namespace { struct CapsuleHeightfieldContactGenerationCallback : OverlapReport { CapsuleMeshContactGeneration mGeneration; const HeightFieldUtil& mHfUtil; const PxTransform& mTransform1; CapsuleHeightfieldContactGenerationCallback( PxContactBuffer& contactBuffer, const PxTransform& transform1, const HeightFieldUtil& hfUtil, const Segment& meshCapsule, PxReal inflatedRadius, PxReal contactDistance, PxReal shapeCapsuleRadius ) : mGeneration (contactBuffer, transform1, meshCapsule, inflatedRadius, contactDistance, shapeCapsuleRadius), mHfUtil (hfUtil), mTransform1 (transform1) { PX_ASSERT(contactBuffer.count==0); } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { const PxU8 nextInd[] = {2,0,1}; while(nb--) { const PxU32 triangleIndex = *indices++; PxU32 vertIndices[3]; PxTrianglePadded currentTriangle; // in world space PxU32 adjInds[3]; mHfUtil.getTriangle(mTransform1, currentTriangle, vertIndices, adjInds, triangleIndex, false, false); PxVec3 normal; currentTriangle.normal(normal); PxU8 triFlags = 0; //KS - temporary until we can calculate triFlags for HF for(PxU32 a = 0; a < 3; ++a) { if(adjInds[a] != 0xFFFFFFFF) { PxTriangle adjTri; mHfUtil.getTriangle(mTransform1, adjTri, NULL, NULL, adjInds[a], false, false); //We now compare the triangles to see if this edge is active PxVec3 adjNormal; adjTri.denormalizedNormal(adjNormal); PxU32 otherIndex = nextInd[a]; PxF32 projD = adjNormal.dot(currentTriangle.verts[otherIndex] - adjTri.verts[0]); if(projD < 0.f) { adjNormal.normalize(); PxF32 proj = adjNormal.dot(normal); if(proj < 0.999f) { triFlags |= 1 << (a+3); } } } else { triFlags |= 1 << (a+3); } } mGeneration.processTriangle(triangleIndex, currentTriangle, triFlags); } return true; } private: CapsuleHeightfieldContactGenerationCallback& operator=(const CapsuleHeightfieldContactGenerationCallback&); }; } bool Gu::contactCapsuleHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; //AM: inflate! const Segment meshCapsule = computeLocalCapsule(transform0, transform1, shapeCapsule); // We must be in local space to use the cache const HeightFieldUtil hfUtil(shapeMesh); CapsuleHeightfieldContactGenerationCallback callback( contactBuffer, transform1, hfUtil, meshCapsule, inflatedRadius, params.mContactDistance, shapeCapsule.radius); //switched from capsuleCollider to boxCollider so we can support nonuniformly scaled meshes by scaling the query region: //bound the capsule in shape space by an AABB: // PT: TODO: improve these bounds (see computeCapsuleBounds) hfUtil.overlapAABBTriangles(transform0, transform1, getLocalCapsuleBounds(inflatedRadius, shapeCapsule.halfHeight), callback); return contactBuffer.count > 0; }
21,271
C++
32.341693
196
0.74162
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactConvexMesh.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 "geomutils/PxContactBuffer.h" #include "GuConvexUtilsInternal.h" #include "GuInternal.h" #include "GuContactPolygonPolygon.h" #include "GuConvexEdgeFlags.h" #include "GuSeparatingAxes.h" #include "GuContactMethodImpl.h" #include "GuMidphaseInterface.h" #include "GuConvexHelper.h" #include "GuTriangleCache.h" #include "GuHeightFieldUtil.h" #include "GuEntityReport.h" #include "GuIntersectionTriangleBox.h" #include "GuBox.h" #include "CmUtils.h" #include "foundation/PxAlloca.h" #include "foundation/PxFPU.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace aos; using namespace intrinsics; //sizeof(SavedContactData)/sizeof(PxU32) = 17, 1088/17 = 64 triangles in the local array #define LOCAL_CONTACTS_SIZE 1088 #define LOCAL_TOUCHED_TRIG_SIZE 192 //#define USE_TRIANGLE_NORMAL #define TEST_INTERNAL_OBJECTS static PX_FORCE_INLINE void projectTriangle(const PxVec3& localSpaceDirection, const PxVec3* PX_RESTRICT triangle, PxReal& min1, PxReal& max1) { const PxReal dp0 = triangle[0].dot(localSpaceDirection); const PxReal dp1 = triangle[1].dot(localSpaceDirection); min1 = selectMin(dp0, dp1); max1 = selectMax(dp0, dp1); const PxReal dp2 = triangle[2].dot(localSpaceDirection); min1 = selectMin(min1, dp2); max1 = selectMax(max1, dp2); } #ifdef TEST_INTERNAL_OBJECTS static PX_FORCE_INLINE void boxSupport(const float extents[3], const PxVec3& sv, float p[3]) { const PxU32* iextents = reinterpret_cast<const PxU32*>(extents); const PxU32* isv = reinterpret_cast<const PxU32*>(&sv); PxU32* ip = reinterpret_cast<PxU32*>(p); ip[0] = iextents[0]|(isv[0]&PX_SIGN_BITMASK); ip[1] = iextents[1]|(isv[1]&PX_SIGN_BITMASK); ip[2] = iextents[2]|(isv[2]&PX_SIGN_BITMASK); } #if PX_DEBUG static const PxReal testInternalObjectsEpsilon = 1.0e-3f; #endif static PX_FORCE_INLINE bool testInternalObjects(const PxVec3& localAxis0, const PolygonalData& polyData0, const PxVec3* PX_RESTRICT triangleInHullSpace, float dmin) { PxReal min1, max1; projectTriangle(localAxis0, triangleInHullSpace, min1, max1); const float dp = polyData0.mCenter.dot(localAxis0); float p0[3]; boxSupport(polyData0.mInternal.mExtents, localAxis0, p0); const float Radius0 = p0[0]*localAxis0.x + p0[1]*localAxis0.y + p0[2]*localAxis0.z; const float bestRadius = selectMax(Radius0, polyData0.mInternal.mRadius); const PxReal min0 = dp - bestRadius; const PxReal max0 = dp + bestRadius; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; const float depth = selectMin(d0, d1); if(depth>dmin) return false; return true; } #endif static PX_FORCE_INLINE bool testNormal( const PxVec3& sepAxis, PxReal min0, PxReal max0, const PxVec3* PX_RESTRICT triangle, PxReal& depth, PxReal contactDistance) { PxReal min1, max1; projectTriangle(sepAxis, triangle, min1, max1); if(max0+contactDistance<min1 || max1+contactDistance<min0) return false; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; depth = selectMin(d0, d1); return true; } static PX_FORCE_INLINE bool testSepAxis(const PxVec3& sepAxis, const PolygonalData& polyData0, const PxVec3* PX_RESTRICT triangle, const PxMat34& m0to1, const FastVertex2ShapeScaling& convexScaling, PxReal& depth, PxReal contactDistance) { PxReal min0, max0; (polyData0.mProjectHull)(polyData0, sepAxis, m0to1, convexScaling, min0, max0); PxReal min1, max1; projectTriangle(sepAxis, triangle, min1, max1); if(max0+contactDistance < min1 || max1+contactDistance < min0) return false; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; depth = selectMin(d0, d1); return true; } static bool testFacesSepAxesBackface( const PolygonalData& polyData0, const PxMat34& /*world0*/, const PxMat34& /*world1*/, const PxMat34& m0to1, const PxVec3& witness, const PxVec3* PX_RESTRICT triangle, const FastVertex2ShapeScaling& convexScaling, PxU32& numHullIndices, PxU32* hullIndices_, PxReal& dmin, PxVec3& sep, PxU32& id, PxReal contactDistance, bool idtConvexScale ) { id = PX_INVALID_U32; const PxU32 numHullPolys = polyData0.mNbPolygons; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; const PxVec3* PX_RESTRICT vertices = polyData0.mVerts; const PxVec3& trans = m0to1.p; { PxU32* hullIndices = hullIndices_; // PT: when the center of one object is inside the other object (deep penetrations) this discards everything! // PT: when this happens, the backup procedure is used to come up with good results anyway. // PT: it's worth having a special codepath here for identity scales, to skip all the normalizes/division. Lot faster without. if(idtConvexScale) { for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; #ifdef USE_TRIANGLE_NORMAL if(PL.normal.dot(witness) > 0.0f) #else // ### this is dubious since the triangle center is likely to be very close to the hull, if not inside. Why not use the triangle normal? if(PL.distance(witness) < 0.0f) #endif continue; //backface culled *hullIndices++ = i; const PxVec3 sepAxis = m0to1.rotate(PL.n); const PxReal dp = sepAxis.dot(trans); PxReal d; if(!testNormal(sepAxis, P.getMin(vertices) + dp, P.getMax() + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } } } else { #ifndef USE_TRIANGLE_NORMAL //transform delta from hull0 shape into vertex space: const PxVec3 vertSpaceWitness = convexScaling % witness; #endif for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; #ifdef USE_TRIANGLE_NORMAL if(PL.normal.dot(witness) > 0.0f) #else // ### this is dubious since the triangle center is likely to be very close to the hull, if not inside. Why not use the triangle normal? if(PL.distance(vertSpaceWitness) < 0.0f) #endif continue; //backface culled //normals transform by inverse transpose: (and transpose(skew) == skew as its symmetric) PxVec3 shapeSpaceNormal = convexScaling % PL.n; //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); *hullIndices++ = i; const PxVec3 sepAxis = m0to1.rotate(shapeSpaceNormal); PxReal d; const PxReal dp = sepAxis.dot(trans); const float oneOverM = 1.0f / magnitude; if(!testNormal(sepAxis, P.getMin(vertices) * oneOverM + dp, P.getMax() * oneOverM + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } } } numHullIndices = PxU32(hullIndices - hullIndices_); } // Backup if(id == PX_INVALID_U32) { if(idtConvexScale) { for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; const PxVec3 sepAxis = m0to1.rotate(PL.n); const PxReal dp = sepAxis.dot(trans); PxReal d; if(!testNormal(sepAxis, P.getMin(vertices) + dp, P.getMax() + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } hullIndices_[i] = i; } } else { for(PxU32 i=0; i<numHullPolys; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; PxVec3 shapeSpaceNormal = convexScaling % PL.n; //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); const PxVec3 sepAxis = m0to1.rotate(shapeSpaceNormal); PxReal d; const PxReal dp = sepAxis.dot(trans); const float oneOverM = 1.0f / magnitude; if(!testNormal(sepAxis, P.getMin(vertices) * oneOverM + dp, P.getMax() * oneOverM + dp, triangle, d, contactDistance)) return false; if(d < dmin) { dmin = d; sep = sepAxis; id = i; } hullIndices_[i] = i; } } numHullIndices = numHullPolys; } return true; } static PX_FORCE_INLINE bool edgeCulling(const PxPlane& plane, const PxVec3& p0, const PxVec3& p1, PxReal contactDistance) { return plane.distance(p0)<=contactDistance || plane.distance(p1)<=contactDistance; } static bool performEETests( const PolygonalData& polyData0, const PxU8 triFlags, const PxMat34& m0to1, const PxMat34& m1to0, const PxVec3* PX_RESTRICT triangle, PxU32 numHullIndices, const PxU32* PX_RESTRICT hullIndices, const PxPlane& localTriPlane, const FastVertex2ShapeScaling& convexScaling, PxVec3& vec, PxReal& dmin, PxReal contactDistance, PxReal toleranceLength, PxU32 id0, PxU32 /*triangleIndex*/) { PX_UNUSED(toleranceLength); // Only used in Debug // Cull candidate triangle edges vs to hull plane PxU32 nbTriangleAxes = 0; PxVec3 triangleAxes[3]; { const HullPolygonData& P = polyData0.mPolygons[id0]; const PxPlane& vertSpacePlane = P.mPlane; const PxVec3 newN = m1to0.rotate(vertSpacePlane.n); PxPlane hullWitness(convexScaling * newN, vertSpacePlane.d - m1to0.p.dot(newN)); //technically not a fully xformed plane, just use property of x|My == Mx|y for symmetric M. if((triFlags & ETD_CONVEX_EDGE_01) && edgeCulling(hullWitness, triangle[0], triangle[1], contactDistance)) triangleAxes[nbTriangleAxes++] = (triangle[0] - triangle[1]); if((triFlags & ETD_CONVEX_EDGE_12) && edgeCulling(hullWitness, triangle[1], triangle[2], contactDistance)) triangleAxes[nbTriangleAxes++] = (triangle[1] - triangle[2]); if((triFlags & ETD_CONVEX_EDGE_20) && edgeCulling(hullWitness, triangle[2], triangle[0], contactDistance)) triangleAxes[nbTriangleAxes++] = (triangle[2] - triangle[0]); } //PxcPlane vertexSpacePlane = localTriPlane.getTransformed(m1to0); //vertexSpacePlane.normal = convexScaling * vertexSpacePlane.normal; //technically not a fully xformed plane, just use property of x|My == Mx|y for symmetric M. const PxVec3 newN = m1to0.rotate(localTriPlane.n); PxPlane vertexSpacePlane(convexScaling * newN, localTriPlane.d - m1to0.p.dot(newN)); const PxVec3* PX_RESTRICT hullVerts = polyData0.mVerts; SeparatingAxes SA; SA.reset(); const PxU8* PX_RESTRICT vrefBase0 = polyData0.mPolygonVertexRefs; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; while(numHullIndices--) { const HullPolygonData& P = polygons[*hullIndices++]; const PxU8* PX_RESTRICT data = vrefBase0 + P.mVRef8; PxU32 numEdges = nbTriangleAxes; const PxVec3* edges = triangleAxes; // TODO: cheap edge culling as in convex/convex! while(numEdges--) { const PxVec3& currentPolyEdge = *edges++; // Loop through polygon vertices == polygon edges; PxU32 numVerts = P.mNbVerts; for(PxU32 j = 0; j < numVerts; j++) { PxU32 j1 = j+1; if(j1>=numVerts) j1 = 0; const PxU32 VRef0 = data[j]; const PxU32 VRef1 = data[j1]; if(edgeCulling(vertexSpacePlane, hullVerts[VRef0], hullVerts[VRef1], contactDistance)) { const PxVec3 currentHullEdge = m0to1.rotate(convexScaling * (hullVerts[VRef0] - hullVerts[VRef1])); //matrix mult is distributive! PxVec3 sepAxis = currentHullEdge.cross(currentPolyEdge); if(!isAlmostZero(sepAxis)) SA.addAxis(sepAxis.getNormalized()); } } } } dmin = PX_MAX_REAL; PxU32 numAxes = SA.getNumAxes(); const PxVec3* PX_RESTRICT axes = SA.getAxes(); #ifdef TEST_INTERNAL_OBJECTS PxVec3 triangleInHullSpace[3]; if(numAxes) { triangleInHullSpace[0] = m1to0.transform(triangle[0]); triangleInHullSpace[1] = m1to0.transform(triangle[1]); triangleInHullSpace[2] = m1to0.transform(triangle[2]); } #endif while(numAxes--) { const PxVec3& currentAxis = *axes++; #ifdef TEST_INTERNAL_OBJECTS const PxVec3 localAxis0 = m1to0.rotate(currentAxis); if(!testInternalObjects(localAxis0, polyData0, triangleInHullSpace, dmin)) { #if PX_DEBUG PxReal dtest; if(testSepAxis(currentAxis, polyData0, triangle, m0to1, convexScaling, dtest, contactDistance)) { PX_ASSERT(dtest + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif PxReal d; if(!testSepAxis(currentAxis, polyData0, triangle, m0to1, convexScaling, d, contactDistance)) { return false; } if(d < dmin) { dmin = d; vec = currentAxis; } } return true; } static bool triangleConvexTest( const PolygonalData& polyData0, const PxU8 triFlags, PxU32 index, const PxVec3* PX_RESTRICT localPoints, const PxPlane& localPlane, const PxVec3& groupCenterHull, const PxMat34& world0, const PxMat34& world1, const PxMat34& m0to1, const PxMat34& m1to0, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, PxVec3& groupAxis, PxReal& groupMinDepth, bool& faceContact, bool idtConvexScale ) { PxU32 id0 = PX_INVALID_U32; PxReal dmin0 = PX_MAX_REAL; PxVec3 vec0; PxU32 numHullIndices = 0; PxU32* PX_RESTRICT const hullIndices = reinterpret_cast<PxU32*>(PxAlloca(polyData0.mNbPolygons*sizeof(PxU32))); // PT: we test the hull normals first because they don't need any hull projection. If we can early exit thanks // to those, we completely avoid all hull projections. bool status = testFacesSepAxesBackface(polyData0, world0, world1, m0to1, groupCenterHull, localPoints, convexScaling, numHullIndices, hullIndices, dmin0, vec0, id0, contactDistance, idtConvexScale); if(!status) return false; groupAxis = PxVec3(0); groupMinDepth = PX_MAX_REAL; const PxReal eps = 0.0001f; // DE7748 //Test in mesh-space PxVec3 sepAxis; PxReal depth; { // Test triangle normal PxReal d; if(!testSepAxis(localPlane.n, polyData0, localPoints, m0to1, convexScaling, d, contactDistance)) return false; if(d<dmin0+eps) // if(d<dmin0) { depth = d; sepAxis = localPlane.n; faceContact = true; } else { depth = dmin0; sepAxis = vec0; faceContact = false; } } if(depth < groupMinDepth) { groupMinDepth = depth; groupAxis = world1.rotate(sepAxis); } if(!performEETests(polyData0, triFlags, m0to1, m1to0, localPoints, numHullIndices, hullIndices, localPlane, convexScaling, sepAxis, depth, contactDistance, toleranceLength, id0, index)) return false; if(depth < groupMinDepth) { groupMinDepth = depth; groupAxis = world1.rotate(sepAxis); faceContact = false; } return true; } namespace { struct ConvexMeshContactGeneration { PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& mDelayedContacts; CacheMap<CachedEdge, 128> mEdgeCache; CacheMap<CachedVertex, 128> mVertCache; const Matrix34FromTransform m0to1; const Matrix34FromTransform m1to0; PxVec3 mHullCenterMesh; PxVec3 mHullCenterWorld; const PolygonalData& mPolyData0; const PxMat34& mWorld0; const PxMat34& mWorld1; const FastVertex2ShapeScaling& mConvexScaling; PxReal mContactDistance; PxReal mToleranceLength; bool mIdtMeshScale, mIdtConvexScale; PxReal mCCDEpsilon; const PxTransform& mTransform0; const PxTransform& mTransform1; PxContactBuffer& mContactBuffer; bool mAnyHits; ConvexMeshContactGeneration( PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer ); void processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds); void generateLastContacts(); bool generateContacts( const PxPlane& localPlane, const PxVec3* PX_RESTRICT localPoints, const PxVec3& triCenter, PxVec3& groupAxis, PxReal groupMinDepth, PxU32 index) const; private: ConvexMeshContactGeneration& operator=(const ConvexMeshContactGeneration&); }; // 17 entries. 1088/17 = 64 triangles in the local array struct SavedContactData { PxU32 mTriangleIndex; // 1 PxVec3 mVerts[3]; // 10 PxU32 mInds[3]; // 13 PxVec3 mGroupAxis; // 16 PxReal mGroupMinDepth; // 17 }; } ConvexMeshContactGeneration::ConvexMeshContactGeneration( PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer ) : mDelayedContacts(delayedContacts), m0to1 (t0to1), m1to0 (t1to0), mPolyData0 (polyData0), mWorld0 (world0), mWorld1 (world1), mConvexScaling (convexScaling), mContactDistance(contactDistance), mToleranceLength(toleranceLength), mIdtConvexScale (idtConvexScale), mCCDEpsilon (cCCDEpsilon), mTransform0 (transform0), mTransform1 (transform1), mContactBuffer (contactBuffer) { delayedContacts.forceSize_Unsafe(0); mAnyHits = false; // Hull center in local space const PxVec3& hullCenterLocal = mPolyData0.mCenter; // Hull center in mesh space mHullCenterMesh = m0to1.transform(hullCenterLocal); // Hull center in world space mHullCenterWorld = mWorld0.transform(hullCenterLocal); } struct ConvexMeshContactGenerationCallback : MeshHitCallback<PxGeomRaycastHit> { ConvexMeshContactGeneration mGeneration; const FastVertex2ShapeScaling& mMeshScaling; const PxU8* PX_RESTRICT mExtraTrigData; bool mIdtMeshScale; const TriangleMesh* mMeshData; const BoxPadded& mBox; ConvexMeshContactGenerationCallback( PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const TriangleMesh* meshData, const PxU8* PX_RESTRICT extraTrigData, const FastVertex2ShapeScaling& meshScaling, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtMeshScale, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const BoxPadded& box ) : MeshHitCallback<PxGeomRaycastHit> (CallbackMode::eMULTIPLE), mGeneration (delayedContacts, t0to1, t1to0, polyData0, world0, world1, convexScaling, contactDistance, toleranceLength, idtConvexScale, cCCDEpsilon, transform0, transform1, contactBuffer), mMeshScaling (meshScaling), mExtraTrigData (extraTrigData), mIdtMeshScale (idtMeshScale), mMeshData (meshData), mBox (box) { } virtual PxAgain processHit( // all reported coords are in mesh local space including hit.position const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { // PT: this one is safe because incoming vertices from midphase are always safe to V4Load (by design) // PT: TODO: is this test really needed? Not done in midphase already? if(!intersectTriangleBox(mBox, v0, v1, v2)) return true; PxVec3 verts[3]; getScaledVertices(verts, v0, v1, v2, mIdtMeshScale, mMeshScaling); const PxU32 triangleIndex = hit.faceIndex; PxU8 extraData = getConvexEdgeFlags(mExtraTrigData, triangleIndex); const PxU32* vertexIndices = vinds; PxU32 localStorage[3]; if(mMeshScaling.flipsNormal()) { flipConvexEdgeFlags(extraData); localStorage[0] = vinds[0]; localStorage[1] = vinds[2]; localStorage[2] = vinds[1]; vertexIndices = localStorage; } mGeneration.processTriangle(verts, triangleIndex, extraData, vertexIndices); return true; } protected: ConvexMeshContactGenerationCallback &operator=(const ConvexMeshContactGenerationCallback &); }; bool ConvexMeshContactGeneration::generateContacts( const PxPlane& localPlane, const PxVec3* PX_RESTRICT localPoints, const PxVec3& triCenter, PxVec3& groupAxis, PxReal groupMinDepth, PxU32 index) const { const PxVec3 worldGroupCenter = mWorld1.transform(triCenter); const PxVec3 deltaC = mHullCenterWorld - worldGroupCenter; if(deltaC.dot(groupAxis) < 0.0f) groupAxis = -groupAxis; const PxU32 id = (mPolyData0.mSelectClosestEdgeCB)(mPolyData0, mConvexScaling, mWorld0.rotateTranspose(-groupAxis)); const HullPolygonData& HP = mPolyData0.mPolygons[id]; PX_ALIGN(16, PxPlane) shapeSpacePlane0; if(mIdtConvexScale) V4StoreA(V4LoadU(&HP.mPlane.n.x), &shapeSpacePlane0.n.x); else mConvexScaling.transformPlaneToShapeSpace(HP.mPlane.n, HP.mPlane.d, shapeSpacePlane0.n, shapeSpacePlane0.d); const PxVec3 hullNormalWorld = mWorld0.rotate(shapeSpacePlane0.n); const PxReal d0 = PxAbs(hullNormalWorld.dot(groupAxis)); const PxVec3 triNormalWorld = mWorld1.rotate(localPlane.n); const PxReal d1 = PxAbs(triNormalWorld.dot(groupAxis)); const bool d0biggerd1 = d0 > d1; ////////////////////NEW DIST HANDLING////////////////////// //TODO: skip this if there is no dist involved! PxReal separation = - groupMinDepth; //convert to real distance. separation = fsel(separation, separation, 0.0f); //don't do anything when penetrating! //printf("\nseparation = %f", separation); PxReal contactGenPositionShift = separation + mCCDEpsilon; //if we're at a distance, shift so we're within penetration. PxVec3 contactGenPositionShiftVec = groupAxis * contactGenPositionShift; //shift one of the bodies this distance toward the other just for Pierre's contact generation. Then the bodies should be penetrating exactly by MIN_SEPARATION_FOR_PENALTY - ideal conditions for this contact generator. //note: for some reason this has to change sign! //this will make contact gen always generate contacts at about MSP. Shift them back to the true real distance, and then to a solver compliant distance given that //the solver converges to MSP penetration, while we want it to converge to 0 penetration. //to real distance: // PxReal polyPolySeparationShift = separation; //(+ or - depending on which way normal goes) //The system: We always shift convex 0 (arbitrary). If the contact is attached to convex 0 then we will need to shift the contact point, otherwise not. //TODO: make these overwrite orig location if its safe to do so. PxMat34 world0_(mWorld0); PxTransform transform0_(mTransform0); world0_.p -= contactGenPositionShiftVec; transform0_.p = world0_.p; //reset this too. const PxTransform t0to1_ = mTransform1.transformInv(transform0_); const PxTransform t1to0_ = transform0_.transformInv(mTransform1); const Matrix34FromTransform m0to1_(t0to1_); const Matrix34FromTransform m1to0_(t1to0_); PxVec3* scaledVertices0; PxU8* stackIndices0; GET_SCALEX_CONVEX(scaledVertices0, stackIndices0, mIdtConvexScale, HP.mNbVerts, mConvexScaling, mPolyData0.mVerts, mPolyData0.getPolygonVertexRefs(HP)) const PxU8 indices[3] = {0, 1, 2}; const PxMat33 RotT0 = findRotationMatrixFromZ(shapeSpacePlane0.n); const PxMat33 RotT1 = findRotationMatrixFromZ(localPlane.n); if(d0biggerd1) { if(contactPolygonPolygonExt( HP.mNbVerts, scaledVertices0, stackIndices0, world0_, shapeSpacePlane0, RotT0, 3, localPoints, indices, mWorld1, localPlane, RotT1, hullNormalWorld, m0to1_, m1to0_, PXC_CONTACT_NO_FACE_INDEX, index, mContactBuffer, true, contactGenPositionShiftVec, contactGenPositionShift)) { return true; } } else { if(contactPolygonPolygonExt( 3, localPoints, indices, mWorld1, localPlane, RotT1, HP.mNbVerts, scaledVertices0, stackIndices0, world0_, shapeSpacePlane0, RotT0, triNormalWorld, m1to0_, m0to1_, PXC_CONTACT_NO_FACE_INDEX, index, mContactBuffer, false, contactGenPositionShiftVec, contactGenPositionShift)) { return true; } } return false; } enum FeatureCode { FC_VERTEX0, FC_VERTEX1, FC_VERTEX2, FC_EDGE01, FC_EDGE12, FC_EDGE20, FC_FACE, FC_UNDEFINED }; static FeatureCode computeFeatureCode(const PxVec3& point, const PxVec3* verts) { const PxVec3& triangleOrigin = verts[0]; const PxVec3 triangleEdge0 = verts[1] - verts[0]; const PxVec3 triangleEdge1 = verts[2] - verts[0]; const PxVec3 kDiff = triangleOrigin - point; const PxReal fA00 = triangleEdge0.magnitudeSquared(); const PxReal fA01 = triangleEdge0.dot(triangleEdge1); const PxReal fA11 = triangleEdge1.magnitudeSquared(); const PxReal fB0 = kDiff.dot(triangleEdge0); const PxReal fB1 = kDiff.dot(triangleEdge1); const PxReal fDet = PxAbs(fA00*fA11 - fA01*fA01); const PxReal u = fA01*fB1-fA11*fB0; const PxReal v = fA01*fB0-fA00*fB1; FeatureCode fc = FC_UNDEFINED; if(u + v <= fDet) { if(u < 0.0f) { if(v < 0.0f) // region 4 { if(fB0 < 0.0f) { if(-fB0 >= fA00) fc = FC_VERTEX1; else fc = FC_EDGE01; } else { if(fB1 >= 0.0f) fc = FC_VERTEX0; else if(-fB1 >= fA11) fc = FC_VERTEX2; else fc = FC_EDGE20; } } else // region 3 { if(fB1 >= 0.0f) fc = FC_VERTEX0; else if(-fB1 >= fA11) fc = FC_VERTEX2; else fc = FC_EDGE20; } } else if(v < 0.0f) // region 5 { if(fB0 >= 0.0f) fc = FC_VERTEX0; else if(-fB0 >= fA00) fc = FC_VERTEX1; else fc = FC_EDGE01; } else // region 0 { // minimum at interior PxVec3 if(fDet==0.0f) fc = FC_VERTEX0; else fc = FC_FACE; } } else { PxReal fTmp0, fTmp1, fNumer, fDenom; if(u < 0.0f) // region 2 { fTmp0 = fA01 + fB0; fTmp1 = fA11 + fB1; if(fTmp1 > fTmp0) { fNumer = fTmp1 - fTmp0; fDenom = fA00-2.0f*fA01+fA11; if(fNumer >= fDenom) fc = FC_VERTEX1; else fc = FC_EDGE12; } else { if(fTmp1 <= 0.0f) fc = FC_VERTEX2; else if(fB1 >= 0.0f) fc = FC_VERTEX0; else fc = FC_EDGE20; } } else if(v < 0.0f) // region 6 { fTmp0 = fA01 + fB1; fTmp1 = fA00 + fB0; if(fTmp1 > fTmp0) { fNumer = fTmp1 - fTmp0; fDenom = fA00-2.0f*fA01+fA11; if(fNumer >= fDenom) fc = FC_VERTEX2; else fc = FC_EDGE12; } else { if(fTmp1 <= 0.0f) fc = FC_VERTEX1; else if(fB0 >= 0.0f) fc = FC_VERTEX0; else fc = FC_EDGE01; } } else // region 1 { fNumer = fA11 + fB1 - fA01 - fB0; if(fNumer <= 0.0f) { fc = FC_VERTEX2; } else { fDenom = fA00-2.0f*fA01+fA11; if(fNumer >= fDenom) fc = FC_VERTEX1; else fc = FC_EDGE12; } } } return fc; } //static bool validateVertex(PxU32 vref, const PxU32 count, const ContactPoint* PX_RESTRICT contacts, const TriangleMesh& meshData) //{ // PxU32 previous = 0xffffffff; // for(PxU32 i=0;i<count;i++) // { // if(contacts[i].internalFaceIndex1==previous) // continue; // previous = contacts[i].internalFaceIndex1; // // const TriangleIndices T(meshData, contacts[i].internalFaceIndex1); // if( T.mVRefs[0]==vref // || T.mVRefs[1]==vref // || T.mVRefs[2]==vref) // return false; // } // return true; //} //static PX_FORCE_INLINE bool testEdge(PxU32 vref0, PxU32 vref1, PxU32 tvref0, PxU32 tvref1) //{ // if(tvref0>tvref1) // PxSwap(tvref0, tvref1); // // if(tvref0==vref0 && tvref1==vref1) // return false; // return true; //} //static bool validateEdge(PxU32 vref0, PxU32 vref1, const PxU32 count, const ContactPoint* PX_RESTRICT contacts, const TriangleMesh& meshData) //{ // if(vref0>vref1) // PxSwap(vref0, vref1); // // PxU32 previous = 0xffffffff; // for(PxU32 i=0;i<count;i++) // { // if(contacts[i].internalFaceIndex1==previous) // continue; // previous = contacts[i].internalFaceIndex1; // // const TriangleIndices T(meshData, contacts[i].internalFaceIndex1); // ///* if(T.mVRefs[0]==vref0 || T.mVRefs[0]==vref1) // return false; // if(T.mVRefs[1]==vref0 || T.mVRefs[1]==vref1) // return false; // if(T.mVRefs[2]==vref0 || T.mVRefs[2]==vref1) // return false;*/ // // PT: wow, this was wrong??? ###FIX // if(!testEdge(vref0, vref1, T.mVRefs[0], T.mVRefs[1])) // return false; // if(!testEdge(vref0, vref1, T.mVRefs[1], T.mVRefs[2])) // return false; // if(!testEdge(vref0, vref1, T.mVRefs[2], T.mVRefs[0])) // return false; // } // return true; //} //static bool validateEdge(PxU32 vref0, PxU32 vref1, const PxU32* vertIndices, const PxU32 nbIndices) //{ // if(vref0>vref1) // PxSwap(vref0, vref1); // // for(PxU32 i=0;i<nbIndices;i+=3) // { // if(!testEdge(vref0, vref1, vertIndices[i+0], vertIndices[i+1])) // return false; // if(!testEdge(vref0, vref1, vertIndices[i+1], vertIndices[i+2])) // return false; // if(!testEdge(vref0, vref1, vertIndices[i+2], vertIndices[i+0])) // return false; // } // return true; //} //#endif void ConvexMeshContactGeneration::processTriangle(const PxVec3* verts, PxU32 triangleIndex, PxU8 triFlags, const PxU32* vertInds) { const PxPlane localPlane(verts[0], verts[1], verts[2]); // Backface culling if(localPlane.distance(mHullCenterMesh)<0.0f) // if(localPlane.normal.dot(mHullCenterMesh - T.mVerts[0]) <= 0.0f) return; ////////////////////////////////////////////////////////////////////////// const PxVec3 triCenter = (verts[0] + verts[1] + verts[2])*(1.0f/3.0f); // Group center in hull space #ifdef USE_TRIANGLE_NORMAL const PxVec3 groupCenterHull = m1to0.rotate(localPlane.normal); #else const PxVec3 groupCenterHull = m1to0.transform(triCenter); #endif ////////////////////////////////////////////////////////////////////////// PxVec3 groupAxis; PxReal groupMinDepth; bool faceContact; if(!triangleConvexTest( mPolyData0, triFlags, triangleIndex, verts, localPlane, groupCenterHull, mWorld0, mWorld1, m0to1, m1to0, mConvexScaling, mContactDistance, mToleranceLength, groupAxis, groupMinDepth, faceContact, mIdtConvexScale )) return; if(faceContact) { // PT: generate face contacts immediately to save memory & avoid recomputing triangle data later if(generateContacts( localPlane, verts, triCenter, groupAxis, groupMinDepth, triangleIndex)) { mAnyHits = true; mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[1])); mEdgeCache.addData(CachedEdge(vertInds[0], vertInds[2])); mEdgeCache.addData(CachedEdge(vertInds[1], vertInds[2])); mVertCache.addData(CachedVertex(vertInds[0])); mVertCache.addData(CachedVertex(vertInds[1])); mVertCache.addData(CachedVertex(vertInds[2])); } else { int stop=1; (void)stop; } } else { const PxU32 nb = sizeof(SavedContactData)/sizeof(PxU32); // PT: no "pushBack" please (useless data copy + LHS) PxU32 newSize = nb + mDelayedContacts.size(); mDelayedContacts.reserve(newSize); SavedContactData* PX_RESTRICT cd = reinterpret_cast<SavedContactData*>(mDelayedContacts.end()); mDelayedContacts.forceSize_Unsafe(newSize); cd->mTriangleIndex = triangleIndex; cd->mVerts[0] = verts[0]; cd->mVerts[1] = verts[1]; cd->mVerts[2] = verts[2]; cd->mInds[0] = vertInds[0]; cd->mInds[1] = vertInds[1]; cd->mInds[2] = vertInds[2]; cd->mGroupAxis = groupAxis; cd->mGroupMinDepth = groupMinDepth; } } void ConvexMeshContactGeneration::generateLastContacts() { // Process delayed contacts PxU32 nbEntries = mDelayedContacts.size(); if(nbEntries) { nbEntries /= sizeof(SavedContactData)/sizeof(PxU32); // PT: TODO: replicate this fix in sphere-vs-mesh ###FIX //const PxU32 count = mContactBuffer.count; //const ContactPoint* PX_RESTRICT contacts = mContactBuffer.contacts; const SavedContactData* PX_RESTRICT cd = reinterpret_cast<const SavedContactData*>(mDelayedContacts.begin()); for(PxU32 i=0;i<nbEntries;i++) { const SavedContactData& currentContact = cd[i]; const PxU32 triangleIndex = currentContact.mTriangleIndex; // PT: unfortunately we must recompute this triangle-data here. // PT: TODO: find a way not to // const TriangleVertices T(*mMeshData, mMeshScaling, triangleIndex); // const TriangleIndices T(*mMeshData, triangleIndex); const PxU32 ref0 = currentContact.mInds[0]; const PxU32 ref1 = currentContact.mInds[1]; const PxU32 ref2 = currentContact.mInds[2]; // PT: TODO: why bother with the feature code at all? Use edge cache directly? // const FeatureCode FC = computeFeatureCode(mHullCenterMesh, T.mVerts); const FeatureCode FC = computeFeatureCode(mHullCenterMesh, currentContact.mVerts); bool generateContact = false; switch(FC) { // PT: trying the same as in sphere-mesh here case FC_VERTEX0: generateContact = !mVertCache.contains(CachedVertex(ref0)); break; case FC_VERTEX1: generateContact =!mVertCache.contains(CachedVertex(ref1)); break; case FC_VERTEX2: generateContact = !mVertCache.contains(CachedVertex(ref2)); break; case FC_EDGE01: generateContact = !mEdgeCache.contains(CachedEdge(ref0, ref1)); break; case FC_EDGE12: generateContact = !mEdgeCache.contains(CachedEdge(ref1, ref2)); break; case FC_EDGE20: generateContact = !mEdgeCache.contains(CachedEdge(ref0, ref2)); break; case FC_FACE: generateContact = true; break; case FC_UNDEFINED: break; }; if(!generateContact) continue; // const PxcPlane localPlane(T.mVerts[0], T.mVerts[1], T.mVerts[2]); const PxPlane localPlane(currentContact.mVerts[0], currentContact.mVerts[1], currentContact.mVerts[2]); // const PxVec3 triCenter = (T.mVerts[0] + T.mVerts[1] + T.mVerts[2])*(1.0f/3.0f); const PxVec3 triCenter = (currentContact.mVerts[0] + currentContact.mVerts[1] + currentContact.mVerts[2])*(1.0f/3.0f); PxVec3 groupAxis = currentContact.mGroupAxis; if(generateContacts( localPlane, // T.mVerts, currentContact.mVerts, triCenter, groupAxis, currentContact.mGroupMinDepth, triangleIndex)) { mAnyHits = true; //We don't add the edges to the data - this is important because we don't want to reject triangles //because we generated an edge contact with an adjacent triangle /*mEdgeCache.addData(CachedEdge(ref0, ref1)); mEdgeCache.addData(CachedEdge(ref0, ref2)); mEdgeCache.addData(CachedEdge(ref1, ref2)); mVertCache.addData(CachedVertex(ref0)); mVertCache.addData(CachedVertex(ref1)); mVertCache.addData(CachedVertex(ref2));*/ } } } } ///////////// static bool contactHullMesh2(const PolygonalData& polyData0, const PxBounds3& hullAABB, const PxTriangleMeshGeometry& shape1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& convexScaling, const FastVertex2ShapeScaling& meshScaling, bool idtConvexScale, bool idtMeshScale) { //Just a sanity-check in debug-mode PX_ASSERT(shape1.getType() == PxGeometryType::eTRIANGLEMESH); //////////////////// // Compute matrices const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); // Compute relative transforms const PxTransform t0to1 = transform1.transformInv(transform0); const PxTransform t1to0 = transform0.transformInv(transform1); BoxPadded hullOBB; computeHullOBB(hullOBB, hullAABB, params.mContactDistance, world0, world1, meshScaling, idtMeshScale); // Setup the collider const TriangleMesh* PX_RESTRICT meshData = _getMeshData(shape1); PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE> delayedContacts; ConvexMeshContactGenerationCallback blockCallback( delayedContacts, t0to1, t1to0, polyData0, world0, world1, meshData, meshData->getExtraTrigData(), meshScaling, convexScaling, params.mContactDistance, params.mToleranceLength, idtMeshScale, idtConvexScale, params.mMeshContactMargin, transform0, transform1, contactBuffer, hullOBB ); Midphase::intersectOBB(meshData, hullOBB, blockCallback, false); blockCallback.mGeneration.generateLastContacts(); return blockCallback.mGeneration.mAnyHits; } ///////////// bool Gu::contactConvexMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); const bool idtScaleMesh = shapeMesh.scale.isIdentity(); FastVertex2ShapeScaling meshScaling; if(!idtScaleMesh) meshScaling.init(shapeMesh.scale); FastVertex2ShapeScaling convexScaling; PxBounds3 hullAABB; PolygonalData polyData0; const bool idtScaleConvex = getConvexData(shapeConvex, convexScaling, hullAABB, polyData0); return contactHullMesh2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, convexScaling, meshScaling, idtScaleConvex, idtScaleMesh); } bool Gu::contactBoxMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); PolygonalData polyData0; PolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData0); const PxBounds3 hullAABB(-shapeBox.halfExtents, shapeBox.halfExtents); const bool idtScaleMesh = shapeMesh.scale.isIdentity(); FastVertex2ShapeScaling meshScaling; if(!idtScaleMesh) meshScaling.init(shapeMesh.scale); FastVertex2ShapeScaling idtScaling; return contactHullMesh2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, idtScaling, meshScaling, true, idtScaleMesh); } ///////////// namespace { struct ConvexVsHeightfieldContactGenerationCallback : OverlapReport { ConvexMeshContactGeneration mGeneration; HeightFieldUtil& mHfUtil; ConvexVsHeightfieldContactGenerationCallback( HeightFieldUtil& hfUtil, PxInlineArray<PxU32,LOCAL_CONTACTS_SIZE>& delayedContacts, const PxTransform& t0to1, const PxTransform& t1to0, const PolygonalData& polyData0, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& convexScaling, PxReal contactDistance, PxReal toleranceLength, bool idtConvexScale, PxReal cCCDEpsilon, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer ) : mGeneration(delayedContacts, t0to1, t1to0, polyData0, world0, world1, convexScaling, contactDistance, toleranceLength, idtConvexScale, cCCDEpsilon, transform0, transform1, contactBuffer), mHfUtil(hfUtil) { } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { const PxU8 nextInd[] = {2,0,1}; while(nb--) { const PxU32 triangleIndex = *indices++; PxU32 vertIndices[3]; PxTriangle currentTriangle; // in world space PxU32 adjInds[3]; mHfUtil.getTriangle(mGeneration.mTransform1, currentTriangle, vertIndices, adjInds, triangleIndex, false, false); PxVec3 normal; currentTriangle.normal(normal); PxU8 triFlags = 0; //KS - temporary until we can calculate triFlags for HF for(PxU32 a = 0; a < 3; ++a) { if(adjInds[a] != 0xFFFFFFFF) { PxTriangle adjTri; mHfUtil.getTriangle(mGeneration.mTransform1, adjTri, NULL, NULL, adjInds[a], false, false); //We now compare the triangles to see if this edge is active PxVec3 adjNormal; adjTri.denormalizedNormal(adjNormal); PxU32 otherIndex = nextInd[a]; PxF32 projD = adjNormal.dot(currentTriangle.verts[otherIndex] - adjTri.verts[0]); if(projD < 0.f) { adjNormal.normalize(); PxF32 proj = adjNormal.dot(normal); if(proj < 0.999f) { triFlags |= 1 << (a+3); } } } else triFlags |= (1 << (a+3)); } mGeneration.processTriangle(currentTriangle.verts, triangleIndex, triFlags, vertIndices); } return true; } protected: ConvexVsHeightfieldContactGenerationCallback &operator=(const ConvexVsHeightfieldContactGenerationCallback &); }; } static bool contactHullHeightfield2(const PolygonalData& polyData0, const PxBounds3& hullAABB, const PxHeightFieldGeometry& shape1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& convexScaling, bool idtConvexScale) { //We need to create a callback that fills triangles from the HF HeightFieldUtil hfUtil(shape1); const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); //////////////////// // Compute relative transforms const PxTransform t0to1 = transform1.transformInv(transform0); const PxTransform t1to0 = transform0.transformInv(transform1); PxInlineArray<PxU32, LOCAL_CONTACTS_SIZE> delayedContacts; ConvexVsHeightfieldContactGenerationCallback blockCallback(hfUtil, delayedContacts, t0to1, t1to0, polyData0, world0, world1, convexScaling, params.mContactDistance, params.mToleranceLength, idtConvexScale, params.mMeshContactMargin, transform0, transform1, contactBuffer); hfUtil.overlapAABBTriangles0to1(t0to1, hullAABB, blockCallback); blockCallback.mGeneration.generateLastContacts(); return blockCallback.mGeneration.mAnyHits; } bool Gu::contactConvexHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); //Create a triangle cache from the HF triangles and then feed triangles to NP mesh methods const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape0); const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); FastVertex2ShapeScaling convexScaling; PxBounds3 hullAABB; PolygonalData polyData0; const bool idtScaleConvex = getConvexData(shapeConvex, convexScaling, hullAABB, polyData0); const PxVec3 inflation(params.mContactDistance); hullAABB.minimum -= inflation; hullAABB.maximum += inflation; return contactHullHeightfield2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, convexScaling, idtScaleConvex); } bool Gu::contactBoxHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); //Create a triangle cache from the HF triangles and then feed triangles to NP mesh methods const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); PolygonalData polyData0; PolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData0); const PxVec3 inflatedExtents = shapeBox.halfExtents + PxVec3(params.mContactDistance); const PxBounds3 hullAABB = PxBounds3(-inflatedExtents, inflatedExtents); const FastVertex2ShapeScaling idtScaling; return contactHullHeightfield2(polyData0, hullAABB, shapeMesh, transform0, transform1, params, contactBuffer, idtScaling, true); }
44,847
C++
29.592087
291
0.715722
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPolygonPolygon.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONTACTPOLYGONPOLYGON_H #define GU_CONTACTPOLYGONPOLYGON_H #include "foundation/Px.h" #include "common/PxPhysXCommonConfig.h" namespace physx { class PxContactBuffer; namespace Cm { class FastVertex2ShapeScaling; } namespace Gu { PX_PHYSX_COMMON_API PxMat33 findRotationMatrixFromZ(const PxVec3& to); PX_PHYSX_COMMON_API bool contactPolygonPolygonExt( PxU32 numVerts0, const PxVec3* vertices0, const PxU8* indices0,//polygon 0 const PxMat34& world0, const PxPlane& localPlane0, //xform of polygon 0, plane of polygon const PxMat33& RotT0, PxU32 numVerts1, const PxVec3* vertices1, const PxU8* indices1,//polygon 1 const PxMat34& world1, const PxPlane& localPlane1, //xform of polygon 1, plane of polygon const PxMat33& RotT1, const PxVec3& worldSepAxis, //world normal of separating plane - this is the world space normal of polygon0!! const PxMat34& transform0to1, const PxMat34& transform1to0,//transforms between polygons PxU32 polyIndex0, PxU32 polyIndex1, //face indices for contact callback, PxContactBuffer& contactBuffer, bool flipNormal, const PxVec3& posShift, float sepShift ); // shape order, post gen shift. } } #endif
3,006
C
43.880596
130
0.736527
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleConvex.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 "geomutils/PxContactBuffer.h" #include "GuConvexMesh.h" #include "GuConvexHelper.h" #include "GuContactMethodImpl.h" #include "GuVecConvexHull.h" #include "GuVecCapsule.h" #include "GuInternal.h" #include "GuGJK.h" #include "CmMatrix34.h" using namespace physx; using namespace Gu; using namespace Cm; /////////// // #include "PxRenderOutput.h" // #include "PxsContext.h" // static void gVisualizeLine(const PxVec3& a, const PxVec3& b, PxcNpThreadContext& context, PxU32 color=0xffffff) // { // PxMat44 m = PxMat44::identity(); // // PxRenderOutput& out = context.mRenderOutput; // out << color << m << RenderOutput::LINES << a << b; // } /////////// static const PxReal fatConvexEdgeCoeff = 0.01f; static bool intersectEdgeEdgePreca(const PxVec3& p1, const PxVec3& p2, const PxVec3& v1, const PxPlane& plane, PxU32 i, PxU32 j, float coeff, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip, float limit) { // if colliding edge (p3,p4) does not cross plane return no collision // same as if p3 and p4 on same side of plane return 0 // // Derivation: // d3 = d(p3, P) = (p3 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // d4 = d(p4, P) = (p4 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // if d3 and d4 have the same sign, they're on the same side of the plane => no collision // We test both sides at the same time by only testing Sign(d3 * d4). // ### put that in the Plane class // ### also check that code in the triangle class that might be similar const PxReal d3 = plane.distance(p3); PxReal temp = d3 * plane.distance(p4); if(temp>0.0f) return false; // if colliding edge (p3,p4) and plane are parallel return no collision PxVec3 v2 = p4 - p3; temp = plane.n.dot(v2); if(temp==0.0f) return false; // ### epsilon would be better // compute intersection point of plane and colliding edge (p3,p4) ip = p3-v2*(d3/temp); // compute distance of intersection from line (ip, -dir) to line (p1,p2) dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i]))*coeff; if(dist<limit) return false; // compute intersection point on edge (p1,p2) line ip -= dist*dir; // check if intersection point (ip) is between edge (p1,p2) vertices temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z); if(temp<0.0f) return true; // collision found return false; // no collision } static bool GuTestAxis(const PxVec3& axis, const Segment& segment, PxReal radius, const PolygonalData& polyData, const FastVertex2ShapeScaling& scaling, const PxMat34& worldTM, PxReal& depth) { // Project capsule PxReal min0 = segment.p0.dot(axis); PxReal max0 = segment.p1.dot(axis); if(min0>max0) PxSwap(min0, max0); min0 -= radius; max0 += radius; // Project convex PxReal Min1, Max1; (polyData.mProjectHull)(polyData, axis, worldTM, scaling, Min1, Max1); // Test projections if(max0<Min1 || Max1<min0) return false; const PxReal d0 = max0 - Min1; PX_ASSERT(d0>=0.0f); const PxReal d1 = Max1 - min0; PX_ASSERT(d1>=0.0f); depth = physx::intrinsics::selectMin(d0, d1); return true; } static bool GuCapsuleConvexOverlap(const Segment& segment, PxReal radius, const PolygonalData& polyData, const FastVertex2ShapeScaling& scaling, const PxTransform& transform, PxReal* t, PxVec3* pp, bool isSphere) { // TODO: // - test normal & edge in same loop // - local space // - use precomputed face value // - optimize projection PxVec3 Sep(0,0,0); PxReal PenDepth = PX_MAX_REAL; PxU32 nbPolys = polyData.mNbPolygons; const HullPolygonData* polys = polyData.mPolygons; const Matrix34FromTransform worldTM(transform); // Test normals for(PxU32 i=0;i<nbPolys;i++) { const HullPolygonData& poly = polys[i]; const PxPlane& vertSpacePlane = poly.mPlane; const PxVec3 worldNormal = worldTM.rotate(vertSpacePlane.n); PxReal d; if(!GuTestAxis(worldNormal, segment, radius, polyData, scaling, worldTM, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = worldNormal; } } // Test edges if(!isSphere) { PxVec3 CapsuleAxis(segment.p1 - segment.p0); CapsuleAxis = CapsuleAxis.getNormalized(); for(PxU32 i=0;i<nbPolys;i++) { const HullPolygonData& poly = polys[i]; const PxPlane& vertSpacePlane = poly.mPlane; const PxVec3 worldNormal = worldTM.rotate(vertSpacePlane.n); PxVec3 Cross = CapsuleAxis.cross(worldNormal); if(!isAlmostZero(Cross)) { Cross = Cross.getNormalized(); PxReal d; if(!GuTestAxis(Cross, segment, radius, polyData, scaling, worldTM, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = Cross; } } } } const PxVec3 Witness = segment.computeCenter() - transform.transform(polyData.mCenter); if(Sep.dot(Witness) < 0.0f) Sep = -Sep; if(t) *t = PenDepth; if(pp) *pp = Sep; return true; } static bool raycast_convexMesh2( const PolygonalData& polyData, const PxVec3& vrayOrig, const PxVec3& vrayDir, PxReal maxDist, PxF32& t) { PxU32 nPolys = polyData.mNbPolygons; const HullPolygonData* PX_RESTRICT polys = polyData.mPolygons; /* Purely convex planes based algorithm Iterate all planes of convex, with following rules: * determine of ray origin is inside them all or not. * planes parallel to ray direction are immediate early out if we're on the outside side (plane normal is sep axis) * else - for all planes the ray direction "enters" from the front side, track the one furthest along the ray direction (A) - for all planes the ray direction "exits" from the back side, track the one furthest along the negative ray direction (B) if the ray origin is outside the convex and if along the ray, A comes before B, the directed line stabs the convex at A */ PxReal latestEntry = -FLT_MAX; PxReal earliestExit = FLT_MAX; while(nPolys--) { const HullPolygonData& poly = *polys++; const PxPlane& vertSpacePlane = poly.mPlane; const PxReal distToPlane = vertSpacePlane.distance(vrayOrig); const PxReal dn = vertSpacePlane.n.dot(vrayDir); const PxReal distAlongRay = -distToPlane/dn; if (dn > 1E-7f) //the ray direction "exits" from the back side { earliestExit = physx::intrinsics::selectMin(earliestExit, distAlongRay); } else if (dn < -1E-7f) //the ray direction "enters" from the front side { /* if (distAlongRay > latestEntry) { latestEntry = distAlongRay; }*/ latestEntry = physx::intrinsics::selectMax(latestEntry, distAlongRay); } else { //plane normal and ray dir are orthogonal if(distToPlane > 0.0f) return false; //a plane is parallel with ray -- and we're outside the ray -- we definitely miss the entire convex! } } if(latestEntry < earliestExit && latestEntry != -FLT_MAX && latestEntry < maxDist-1e-5f) { t = latestEntry; return true; } return false; } // PT: version based on Gu::raycast_convexMesh to handle scaling, but modified to make sure it works when ray starts inside the convex static void GuGenerateVFContacts2(PxContactBuffer& contactBuffer, // const PxTransform& convexPose, const PolygonalData& polyData, // Convex data const PxMeshScale& scale, // PxU32 nbPts, const PxVec3* PX_RESTRICT points, const PxReal radius, // Capsule's radius // const PxVec3& normal, const PxReal contactDistance) { PX_ASSERT(PxAbs(normal.magnitudeSquared()-1)<1e-4f); //scaling: transform the ray to vertex space const PxMat34 world2vertexSkew = scale.getInverse() * convexPose.getInverse(); const PxVec3 vrayDir = world2vertexSkew.rotate( -normal ); const PxReal maxDist = contactDistance + radius; for(PxU32 i=0;i<nbPts;i++) { const PxVec3& rayOrigin = points[i]; const PxVec3 vrayOrig = world2vertexSkew.transform(rayOrigin); PxF32 t; if(raycast_convexMesh2(polyData, vrayOrig, vrayDir, maxDist, t)) { contactBuffer.contact(rayOrigin - t * normal, normal, t - radius); } } } static void GuGenerateEEContacts( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, const PxReal contactDistance, // const PolygonalData& polyData, const PxTransform& transform, const FastVertex2ShapeScaling& scaling, // const PxVec3& normal) { PxU32 numPolygons = polyData.mNbPolygons; const HullPolygonData* PX_RESTRICT polygons = polyData.mPolygons; const PxU8* PX_RESTRICT vertexData = polyData.mPolygonVertexRefs; ConvexEdge edges[512]; PxU32 nbEdges = findUniqueConvexEdges(512, edges, numPolygons, polygons, vertexData); // PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatConvexEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = v1.cross(normal); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[ii]*normal[jj]-v1[jj]*normal[ii]); // const PxVec3* PX_RESTRICT verts = polyData.mVerts; for(PxU32 i=0;i<nbEdges;i++) { const PxU8 vi0 = edges[i].vref0; const PxU8 vi1 = edges[i].vref1; // PxVec3 p1 = transform.transform(verts[vi0]); // PxVec3 p2 = transform.transform(verts[vi1]); // makeFatEdge(p1, p2, fatConvexEdgeCoeff); // PT: TODO: make fat segment instead const PxVec3 p1 = transform.transform(scaling * verts[vi0]); const PxVec3 p2 = transform.transform(scaling * verts[vi1]); PxReal dist; PxVec3 ip; // if(intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip)) // if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip, -FLT_MAX)) if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip, -radius-contactDistance)) // if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip, 0)) { contactBuffer.contact(ip-normal*dist, normal, - (radius + dist)); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } } } static void GuGenerateEEContacts2b(PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const PxMat34& transform, const PolygonalData& polyData, const FastVertex2ShapeScaling& scaling, // const PxVec3& normal, const PxReal contactDistance) { // TODO: // - local space const PxVec3 localDir = transform.rotateTranspose(normal); PxU32 polyIndex = (polyData.mSelectClosestEdgeCB)(polyData, scaling, localDir); PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatConvexEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = -(v1.cross(normal)); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[jj]*normal[ii]-v1[ii]*normal[jj]); // const PxVec3* PX_RESTRICT verts = polyData.mVerts; const HullPolygonData& polygon = polyData.mPolygons[polyIndex]; const PxU8* PX_RESTRICT vRefBase = polyData.mPolygonVertexRefs + polygon.mVRef8; PxU32 numEdges = polygon.mNbVerts; PxU32 a = numEdges - 1; PxU32 b = 0; while(numEdges--) { // const PxVec3 p1 = transform.transform(verts[vRefBase[a]]); // const PxVec3 p2 = transform.transform(verts[vRefBase[b]]); const PxVec3 p1 = transform.transform(scaling * verts[vRefBase[a]]); const PxVec3 p2 = transform.transform(scaling * verts[vRefBase[b]]); PxReal dist; PxVec3 ip; // bool contact = intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip); bool contact = intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip, 0.0f); if(contact && dist < radius + contactDistance) { contactBuffer.contact(ip-normal*dist, normal, dist - radius); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } a = b; b++; } } bool Gu::contactCapsuleConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); // Get actual shape data // PT: the capsule can be a sphere in this case so we do this special piece of code: PxCapsuleGeometry shapeCapsule = static_cast<const PxCapsuleGeometry&>(shape0); if(shape0.getType()==PxGeometryType::eSPHERE) shapeCapsule.halfHeight = 0.0f; const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); PxVec3 onSegment, onConvex; PxReal distance; PxVec3 normal_; { const ConvexMesh* cm = static_cast<const ConvexMesh*>(shapeConvex.convexMesh); using namespace aos; Vec3V closA, closB, normalV; GjkStatus status; FloatV dist; { const Vec3V zeroV = V3Zero(); const ConvexHullData* hullData = &cm->getHull(); const FloatV capsuleHalfHeight = FLoad(shapeCapsule.halfHeight); const Vec3V vScale = V3LoadU_SafeReadW(shapeConvex.scale.scale); // PT: safe because 'rotation' follows 'scale' in PxMeshScale const QuatV vQuat = QuatVLoadU(&shapeConvex.scale.rotation.x); const PxMatTransformV aToB(transform1.transformInv(transform0)); const ConvexHullV convexHull(hullData, zeroV, vScale, vQuat, shapeConvex.scale.isIdentity()); //transform capsule(a) into the local space of convexHull(b), treat capsule as segment const CapsuleV capsule(aToB.p, aToB.rotate(V3Scale(V3UnitX(), capsuleHalfHeight)), FZero()); const LocalConvex<CapsuleV> convexA(capsule); const LocalConvex<ConvexHullV> convexB(convexHull); const Vec3V initialSearchDir = V3Sub(convexA.getCenter(), convexB.getCenter()); status = gjk<LocalConvex<CapsuleV>, LocalConvex<ConvexHullV> >(convexA, convexB, initialSearchDir, FMax(),closA, closB, normalV, dist); } if(status == GJK_CONTACT) distance = 0.f; else { //const FloatV sqDist = FMul(dist, dist); V3StoreU(closB, onConvex); FStore(dist, &distance); V3StoreU(normalV, normal_); onConvex = transform1.transform(onConvex); normal_ = transform1.rotate(normal_); } } const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; if(distance >= inflatedRadius) return false; Segment worldSegment; getCapsuleSegment(transform0, shapeCapsule, worldSegment); const bool isSphere = worldSegment.p0 == worldSegment.p1; const PxU32 nbPts = PxU32(isSphere ? 1 : 2); PX_ASSERT(contactBuffer.count==0); FastVertex2ShapeScaling convexScaling; const bool idtConvexScale = shapeConvex.scale.isIdentity(); if(!idtConvexScale) convexScaling.init(shapeConvex.scale); PolygonalData polyData; getPolygonalData_Convex(&polyData, _getHullData(shapeConvex), convexScaling); // if(0) if(distance > 0.f) { // PT: the capsule segment doesn't intersect the convex => distance-based version PxVec3 normal = -normal_; // PT: generate VF contacts for segment's vertices vs convex GuGenerateVFContacts2( contactBuffer, transform1, polyData, shapeConvex.scale, nbPts, &worldSegment.p0, shapeCapsule.radius, normal, params.mContactDistance); // PT: early exit if we already have 2 stable contacts if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts if(!isSphere) { const Matrix34FromTransform worldTM(transform1); GuGenerateEEContacts2b(contactBuffer, worldSegment, shapeCapsule.radius, worldTM, polyData, convexScaling, normal, params.mContactDistance); } // PT: run VF case for convex-vertex-vs-capsule only if we don't have any contact yet if(!contactBuffer.count) { // gVisualizeLine(onConvex, onConvex + normal, context, PxDebugColor::eARGB_RED); //PxReal distance = PxSqrt(sqDistance); contactBuffer.contact(onConvex, normal, distance - shapeCapsule.radius); } } else { // PT: the capsule segment intersects the convex => penetration-based version //printf("Penetration-based:\n"); // PT: compute penetration vector (MTD) PxVec3 SepAxis; if(!GuCapsuleConvexOverlap(worldSegment, shapeCapsule.radius, polyData, convexScaling, transform1, NULL, &SepAxis, isSphere)) { //printf("- no overlap\n"); return false; } // PT: generate VF contacts for segment's vertices vs convex GuGenerateVFContacts2( contactBuffer, transform1, polyData, shapeConvex.scale, nbPts, &worldSegment.p0, shapeCapsule.radius, SepAxis, params.mContactDistance); // PT: early exit if we already have 2 stable contacts //printf("- %d VF contacts\n", contactBuffer.count); if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts if(!isSphere) { GuGenerateEEContacts(contactBuffer, worldSegment, shapeCapsule.radius, params.mContactDistance, polyData, transform1, convexScaling, SepAxis); //printf("- %d total contacts\n", contactBuffer.count); } } return true; }
18,893
C++
31.688581
235
0.703806
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereMesh.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 "geomutils/PxContactBuffer.h" #include "common/PxRenderOutput.h" #include "GuDistancePointTriangle.h" #include "GuContactMethodImpl.h" #include "GuFeatureCode.h" #include "GuMidphaseInterface.h" #include "GuEntityReport.h" #include "GuHeightFieldUtil.h" #include "GuBox.h" #include "foundation/PxSort.h" #define DEBUG_RENDER_MESHCONTACTS 0 using namespace physx; using namespace Gu; static const bool gDrawTouchedTriangles = false; static void outputErrorMessage() { #if PX_CHECKED PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Dropping contacts in sphere vs mesh: exceeded limit of 64 "); #endif } /////////////////////////////////////////////////////////////////////////////// // PT: a customized version that also returns the feature code static PxVec3 closestPtPointTriangle(const PxVec3& p, const PxVec3& a, const PxVec3& b, const PxVec3& c, float& s, float& t, FeatureCode& fc) { // Check if P in vertex region outside A const PxVec3 ab = b - a; const PxVec3 ac = c - a; const PxVec3 ap = p - a; const float d1 = ab.dot(ap); const float d2 = ac.dot(ap); if(d1<=0.0f && d2<=0.0f) { s = 0.0f; t = 0.0f; fc = FC_VERTEX0; return a; // Barycentric coords 1,0,0 } // Check if P in vertex region outside B const PxVec3 bp = p - b; const float d3 = ab.dot(bp); const float d4 = ac.dot(bp); if(d3>=0.0f && d4<=d3) { s = 1.0f; t = 0.0f; fc = FC_VERTEX1; return b; // Barycentric coords 0,1,0 } // Check if P in edge region of AB, if so return projection of P onto AB const float vc = d1*d4 - d3*d2; if(vc<=0.0f && d1>=0.0f && d3<=0.0f) { const float v = d1 / (d1 - d3); s = v; t = 0.0f; fc = FC_EDGE01; return a + v * ab; // barycentric coords (1-v, v, 0) } // Check if P in vertex region outside C const PxVec3 cp = p - c; const float d5 = ab.dot(cp); const float d6 = ac.dot(cp); if(d6>=0.0f && d5<=d6) { s = 0.0f; t = 1.0f; fc = FC_VERTEX2; return c; // Barycentric coords 0,0,1 } // Check if P in edge region of AC, if so return projection of P onto AC const float vb = d5*d2 - d1*d6; if(vb<=0.0f && d2>=0.0f && d6<=0.0f) { const float w = d2 / (d2 - d6); s = 0.0f; t = w; fc = FC_EDGE20; return a + w * ac; // barycentric coords (1-w, 0, w) } // Check if P in edge region of BC, if so return projection of P onto BC const float va = d3*d6 - d5*d4; if(va<=0.0f && (d4-d3)>=0.0f && (d5-d6)>=0.0f) { const float w = (d4-d3) / ((d4 - d3) + (d5-d6)); s = 1.0f-w; t = w; fc = FC_EDGE12; return b + w * (c-b); // barycentric coords (0, 1-w, w) } // P inside face region. Compute Q through its barycentric coords (u,v,w) const float denom = 1.0f / (va + vb + vc); const float v = vb * denom; const float w = vc * denom; s = v; t = w; fc = FC_FACE; return a + ab*v + ac*w; } /////////////////////////////////////////////////////////////////////////////// // PT: we use a separate structure to make sorting faster struct SortKey { float mSquareDist; PxU32 mIndex; PX_FORCE_INLINE bool operator < (const SortKey& data) const { return mSquareDist < data.mSquareDist; } }; struct TriangleData { PxVec3 mDelta; FeatureCode mFC; PxU32 mTriangleIndex; PxU32 mVRef[3]; }; struct CachedTriangleIndices { PxU32 mVRef[3]; }; static PX_FORCE_INLINE bool validateSquareDist(PxReal squareDist) { return squareDist>0.0001f; } static bool validateEdge(PxU32 vref0, PxU32 vref1, const CachedTriangleIndices* cachedTris, PxU32 nbCachedTris) { while(nbCachedTris--) { const CachedTriangleIndices& inds = *cachedTris++; const PxU32 vi0 = inds.mVRef[0]; const PxU32 vi1 = inds.mVRef[1]; const PxU32 vi2 = inds.mVRef[2]; if(vi0==vref0) { if(vi1==vref1 || vi2==vref1) return false; } else if(vi1==vref0) { if(vi0==vref1 || vi2==vref1) return false; } else if(vi2==vref0) { if(vi1==vref1 || vi0==vref1) return false; } } return true; } static bool validateVertex(PxU32 vref, const CachedTriangleIndices* cachedTris, PxU32 nbCachedTris) { while(nbCachedTris--) { const CachedTriangleIndices& inds = *cachedTris++; if(inds.mVRef[0]==vref || inds.mVRef[1]==vref || inds.mVRef[2]==vref) return false; } return true; } namespace { class NullAllocator { public: PX_FORCE_INLINE NullAllocator() { } PX_FORCE_INLINE void* allocate(size_t, const char*, int) { return NULL; } PX_FORCE_INLINE void deallocate(void*) { } }; struct SphereMeshContactGeneration { const PxSphereGeometry& mShapeSphere; const PxTransform& mTransform0; const PxTransform& mTransform1; PxContactBuffer& mContactBuffer; const PxVec3& mSphereCenterShape1Space; PxF32 mInflatedRadius2; PxU32 mNbDelayed; TriangleData mSavedData[PxContactBuffer::MAX_CONTACTS]; SortKey mSortKey[PxContactBuffer::MAX_CONTACTS]; PxU32 mNbCachedTris; CachedTriangleIndices mCachedTris[PxContactBuffer::MAX_CONTACTS]; PxRenderOutput* mRenderOutput; SphereMeshContactGeneration(const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterShape1Space, PxF32 inflatedRadius, PxRenderOutput* renderOutput) : mShapeSphere (shapeSphere), mTransform0 (transform0), mTransform1 (transform1), mContactBuffer (contactBuffer), mSphereCenterShape1Space (sphereCenterShape1Space), mInflatedRadius2 (inflatedRadius*inflatedRadius), mNbDelayed (0), mNbCachedTris (0), mRenderOutput (renderOutput) { } PX_FORCE_INLINE void cacheTriangle(PxU32 ref0, PxU32 ref1, PxU32 ref2) { const PxU32 nb = mNbCachedTris++; mCachedTris[nb].mVRef[0] = ref0; mCachedTris[nb].mVRef[1] = ref1; mCachedTris[nb].mVRef[2] = ref2; } PX_FORCE_INLINE void addContact(const PxVec3& d, PxReal squareDist, PxU32 triangleIndex) { float dist; PxVec3 delta; if(validateSquareDist(squareDist)) { // PT: regular contact. Normalize 'delta'. dist = PxSqrt(squareDist); delta = d / dist; } else { // PT: singular contact: 'd' is the non-unit triangle's normal in this case. dist = 0.0f; delta = -d.getNormalized(); } const PxVec3 worldNormal = -mTransform1.rotate(delta); const PxVec3 localHit = mSphereCenterShape1Space + mShapeSphere.radius*delta; const PxVec3 hit = mTransform1.transform(localHit); if(!mContactBuffer.contact(hit, worldNormal, dist - mShapeSphere.radius, triangleIndex)) outputErrorMessage(); } void processTriangle(PxU32 triangleIndex, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, const PxU32* vertInds) { // PT: compute closest point between sphere center and triangle PxReal u, v; FeatureCode fc; const PxVec3 cp = closestPtPointTriangle(mSphereCenterShape1Space, v0, v1, v2, u, v, fc); // PT: compute 'delta' vector between closest point and sphere center const PxVec3 delta = cp - mSphereCenterShape1Space; const PxReal squareDist = delta.magnitudeSquared(); if(squareDist >= mInflatedRadius2) return; // PT: backface culling without the normalize // PT: TODO: consider doing before the pt-triangle distance test if it's cheaper // PT: TODO: e0/e1 already computed in closestPtPointTriangle const PxVec3 e0 = v1 - v0; const PxVec3 e1 = v2 - v0; const PxVec3 planeNormal = e0.cross(e1); const PxF32 planeD = planeNormal.dot(v0); // PT: actually -d compared to PxcPlane if(planeNormal.dot(mSphereCenterShape1Space) < planeD) return; // PT: for a regular contact, 'delta' is non-zero (and so is 'squareDist'). However when the sphere's center exactly touches // the triangle, then both 'delta' and 'squareDist' become zero. This needs to be handled as a special case to avoid dividing // by zero. We will use the triangle's normal as a contact normal in this special case. // // 'validateSquareDist' is called twice because there are conflicting goals here. We could call it once now and already // compute the proper data for generating the contact. But this would mean doing a square-root and a division right here, // even when the contact is not actually needed in the end. We could also call it only once in "addContact', but the plane's // normal would not always be available (in case of delayed contacts), and thus it would need to be either recomputed (slower) // or stored within 'TriangleData' (using more memory). Calling 'validateSquareDist' twice is a better option overall. PxVec3 d; if(validateSquareDist(squareDist)) d = delta; else d = planeNormal; if(fc==FC_FACE) { addContact(d, squareDist, triangleIndex); if(mNbCachedTris<PxContactBuffer::MAX_CONTACTS) cacheTriangle(vertInds[0], vertInds[1], vertInds[2]); } else { if(mNbDelayed<PxContactBuffer::MAX_CONTACTS) { const PxU32 index = mNbDelayed++; mSortKey[index].mSquareDist = squareDist; mSortKey[index].mIndex = index; TriangleData* saved = mSavedData + index; saved->mDelta = d; saved->mVRef[0] = vertInds[0]; saved->mVRef[1] = vertInds[1]; saved->mVRef[2] = vertInds[2]; saved->mFC = fc; saved->mTriangleIndex = triangleIndex; } else outputErrorMessage(); } } void generateLastContacts() { const PxU32 count = mNbDelayed; if(!count) return; PxSort(mSortKey, count, PxLess<SortKey>(), NullAllocator(), PxContactBuffer::MAX_CONTACTS); TriangleData* touchedTris = mSavedData; for(PxU32 i=0;i<count;i++) { const TriangleData& data = touchedTris[mSortKey[i].mIndex]; const PxU32 ref0 = data.mVRef[0]; const PxU32 ref1 = data.mVRef[1]; const PxU32 ref2 = data.mVRef[2]; bool generateContact = false; switch(data.mFC) { case FC_VERTEX0: generateContact = ::validateVertex(ref0, mCachedTris, mNbCachedTris); break; case FC_VERTEX1: generateContact = ::validateVertex(ref1, mCachedTris, mNbCachedTris); break; case FC_VERTEX2: generateContact = ::validateVertex(ref2, mCachedTris, mNbCachedTris); break; case FC_EDGE01: generateContact = ::validateEdge(ref0, ref1, mCachedTris, mNbCachedTris); break; case FC_EDGE12: generateContact = ::validateEdge(ref1, ref2, mCachedTris, mNbCachedTris); break; case FC_EDGE20: generateContact = ::validateEdge(ref0, ref2, mCachedTris, mNbCachedTris); break; case FC_FACE: case FC_UNDEFINED: PX_ASSERT(0); // PT: should not be possible break; }; if(generateContact) addContact(data.mDelta, mSortKey[i].mSquareDist, data.mTriangleIndex); if(mNbCachedTris<PxContactBuffer::MAX_CONTACTS) cacheTriangle(ref0, ref1, ref2); else outputErrorMessage(); } } private: SphereMeshContactGeneration& operator=(const SphereMeshContactGeneration&); }; struct SphereMeshContactGenerationCallback_NoScale : MeshHitCallback<PxGeomRaycastHit> { SphereMeshContactGeneration mGeneration; const TriangleMesh& mMeshData; SphereMeshContactGenerationCallback_NoScale(const TriangleMesh& meshData, const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterShape1Space, PxF32 inflatedRadius, PxRenderOutput* renderOutput ) : MeshHitCallback<PxGeomRaycastHit> (CallbackMode::eMULTIPLE), mGeneration (shapeSphere, transform0, transform1, contactBuffer, sphereCenterShape1Space, inflatedRadius, renderOutput), mMeshData (meshData) { } virtual ~SphereMeshContactGenerationCallback_NoScale() { mGeneration.generateLastContacts(); } virtual PxAgain processHit( const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { if(gDrawTouchedTriangles) { (*mGeneration.mRenderOutput) << 0xffffffff; (*mGeneration.mRenderOutput) << PxMat44(PxIdentity); const PxVec3 wp0 = mGeneration.mTransform1.transform(v0); const PxVec3 wp1 = mGeneration.mTransform1.transform(v1); const PxVec3 wp2 = mGeneration.mTransform1.transform(v2); mGeneration.mRenderOutput->outputSegment(wp0, wp1); mGeneration.mRenderOutput->outputSegment(wp1, wp2); mGeneration.mRenderOutput->outputSegment(wp2, wp0); } mGeneration.processTriangle(hit.faceIndex, v0, v1, v2, vinds); return true; } protected: SphereMeshContactGenerationCallback_NoScale &operator=(const SphereMeshContactGenerationCallback_NoScale &); }; struct SphereMeshContactGenerationCallback_Scale : SphereMeshContactGenerationCallback_NoScale { const Cm::FastVertex2ShapeScaling& mMeshScaling; SphereMeshContactGenerationCallback_Scale(const TriangleMesh& meshData, const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, const Cm::FastVertex2ShapeScaling& meshScaling, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterShape1Space, PxF32 inflatedRadius, PxRenderOutput* renderOutput ) : SphereMeshContactGenerationCallback_NoScale(meshData, shapeSphere, transform0, transform1, contactBuffer, sphereCenterShape1Space, inflatedRadius, renderOutput), mMeshScaling (meshScaling) { } virtual ~SphereMeshContactGenerationCallback_Scale() {} virtual PxAgain processHit(const PxGeomRaycastHit& hit, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, PxReal&, const PxU32* vinds) { PxVec3 verts[3]; getScaledVertices(verts, v0, v1, v2, false, mMeshScaling); const PxU32* vertexIndices = vinds; PxU32 localStorage[3]; if(mMeshScaling.flipsNormal()) { localStorage[0] = vinds[0]; localStorage[1] = vinds[2]; localStorage[2] = vinds[1]; vertexIndices = localStorage; } if(gDrawTouchedTriangles) { (*mGeneration.mRenderOutput) << 0xffffffff; (*mGeneration.mRenderOutput) << PxMat44(PxIdentity); const PxVec3 wp0 = mGeneration.mTransform1.transform(verts[0]); const PxVec3 wp1 = mGeneration.mTransform1.transform(verts[1]); const PxVec3 wp2 = mGeneration.mTransform1.transform(verts[2]); mGeneration.mRenderOutput->outputSegment(wp0, wp1); mGeneration.mRenderOutput->outputSegment(wp1, wp2); mGeneration.mRenderOutput->outputSegment(wp2, wp0); } mGeneration.processTriangle(hit.faceIndex, verts[0], verts[1], verts[2], vertexIndices); return true; } protected: SphereMeshContactGenerationCallback_Scale &operator=(const SphereMeshContactGenerationCallback_Scale &); }; } /////////////////////////////////////////////////////////////////////////////// bool Gu::contactSphereMesh(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxTriangleMeshGeometry& shapeMesh = checkedCast<PxTriangleMeshGeometry>(shape1); // We must be in local space to use the cache const PxVec3 sphereCenterInMeshSpace = transform1.transformInv(transform0.p); const PxReal inflatedRadius = shapeSphere.radius + params.mContactDistance; const TriangleMesh* meshData = _getMeshData(shapeMesh); // mesh scale is not baked into cached verts if(shapeMesh.scale.isIdentity()) { SphereMeshContactGenerationCallback_NoScale callback( *meshData, shapeSphere, transform0, transform1, contactBuffer, sphereCenterInMeshSpace, inflatedRadius, renderOutput); // PT: TODO: switch to sphere query here const Box obb(sphereCenterInMeshSpace, PxVec3(inflatedRadius), PxMat33(PxIdentity)); Midphase::intersectOBB(meshData, obb, callback, true); } else { const Cm::FastVertex2ShapeScaling meshScaling(shapeMesh.scale); SphereMeshContactGenerationCallback_Scale callback( *meshData, shapeSphere, transform0, transform1, meshScaling, contactBuffer, sphereCenterInMeshSpace, inflatedRadius, renderOutput); PxVec3 obbCenter = sphereCenterInMeshSpace; PxVec3 obbExtents = PxVec3(inflatedRadius); PxMat33 obbRot(PxIdentity); meshScaling.transformQueryBounds(obbCenter, obbExtents, obbRot); const Box obb(obbCenter, obbExtents, obbRot); Midphase::intersectOBB(meshData, obb, callback, true); } return contactBuffer.count > 0; } /////////////////////////////////////////////////////////////////////////////// namespace { struct SphereHeightfieldContactGenerationCallback : OverlapReport { SphereMeshContactGeneration mGeneration; HeightFieldUtil& mHfUtil; SphereHeightfieldContactGenerationCallback( HeightFieldUtil& hfUtil, const PxSphereGeometry& shapeSphere, const PxTransform& transform0, const PxTransform& transform1, PxContactBuffer& contactBuffer, const PxVec3& sphereCenterInMeshSpace, PxF32 inflatedRadius, PxRenderOutput* renderOutput ) : mGeneration (shapeSphere, transform0, transform1, contactBuffer, sphereCenterInMeshSpace, inflatedRadius, renderOutput), mHfUtil (hfUtil) { } // PT: TODO: refactor/unify with similar code in other places virtual bool reportTouchedTris(PxU32 nb, const PxU32* indices) { while(nb--) { const PxU32 triangleIndex = *indices++; PxU32 vertIndices[3]; PxTriangle currentTriangle; mHfUtil.getTriangle(mGeneration.mTransform1, currentTriangle, vertIndices, NULL, triangleIndex, false, false); mGeneration.processTriangle(triangleIndex, currentTriangle.verts[0], currentTriangle.verts[1], currentTriangle.verts[2], vertIndices); } return true; } protected: SphereHeightfieldContactGenerationCallback &operator=(const SphereHeightfieldContactGenerationCallback &); }; } bool Gu::contactSphereHeightfield(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxSphereGeometry& shapeSphere = checkedCast<PxSphereGeometry>(shape0); const PxHeightFieldGeometry& shapeMesh = checkedCast<PxHeightFieldGeometry>(shape1); HeightFieldUtil hfUtil(shapeMesh); const PxReal inflatedRadius = shapeSphere.radius + params.mContactDistance; PxBounds3 localBounds; const PxVec3 localSphereCenter = getLocalSphereData(localBounds, transform0, transform1, inflatedRadius); SphereHeightfieldContactGenerationCallback blockCallback(hfUtil, shapeSphere, transform0, transform1, contactBuffer, localSphereCenter, inflatedRadius, renderOutput); hfUtil.overlapAABBTriangles(localBounds, blockCallback); blockCallback.mGeneration.generateLastContacts(); return contactBuffer.count > 0; } ///////////////////////////////////////////////////////////////////////////////
19,978
C++
31.120579
167
0.719291
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactMethodImpl.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONTACTMETHODIMPL_H #define GU_CONTACTMETHODIMPL_H #include "foundation/PxAssert.h" #include "common/PxPhysXCommonConfig.h" #include "collision/PxCollisionDefs.h" #include "GuGeometryChecks.h" namespace physx { class PxGeometry; class PxRenderOutput; class PxContactBuffer; namespace Gu { class PersistentContactManifold; class MultiplePersistentContactManifold; struct NarrowPhaseParams { PX_FORCE_INLINE NarrowPhaseParams(PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength) : mContactDistance(contactDistance), mMeshContactMargin(meshContactMargin), mToleranceLength(toleranceLength) {} PxReal mContactDistance; const PxReal mMeshContactMargin; // PT: Margin used to generate mesh contacts. Temp & unclear, should be removed once GJK is default path. const PxReal mToleranceLength; // PT: copy of PxTolerancesScale::length }; enum ManifoldFlags { IS_MANIFOLD = (1<<0), IS_MULTI_MANIFOLD = (1<<1) }; struct Cache : public PxCache { Cache() { } PX_FORCE_INLINE void setManifold(void* manifold) { PX_ASSERT((size_t(manifold) & 0xF) == 0); mCachedData = reinterpret_cast<PxU8*>(manifold); mManifoldFlags |= IS_MANIFOLD; } PX_FORCE_INLINE void setMultiManifold(void* manifold) { PX_ASSERT((size_t(manifold) & 0xF) == 0); mCachedData = reinterpret_cast<PxU8*>(manifold); mManifoldFlags |= IS_MANIFOLD|IS_MULTI_MANIFOLD; } PX_FORCE_INLINE PxU8 isManifold() const { return PxU8(mManifoldFlags & IS_MANIFOLD); } PX_FORCE_INLINE PxU8 isMultiManifold() const { return PxU8(mManifoldFlags & IS_MULTI_MANIFOLD); } PX_FORCE_INLINE PersistentContactManifold& getManifold() { PX_ASSERT(isManifold()); PX_ASSERT(!isMultiManifold()); PX_ASSERT((uintptr_t(mCachedData) & 0xf) == 0); return *reinterpret_cast<PersistentContactManifold*>(mCachedData); } PX_FORCE_INLINE MultiplePersistentContactManifold& getMultipleManifold() { PX_ASSERT(isManifold()); PX_ASSERT(isMultiManifold()); PX_ASSERT((uintptr_t(mCachedData) & 0xf) == 0); return *reinterpret_cast<MultiplePersistentContactManifold*>(mCachedData); } }; } template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE const Geom& checkedCast(const PxGeometry& geom) { checkType<Geom>(geom); return static_cast<const Geom&>(geom); } #define GU_CONTACT_METHOD_ARGS \ const PxGeometry& shape0, \ const PxGeometry& shape1, \ const PxTransform32& transform0, \ const PxTransform32& transform1, \ const Gu::NarrowPhaseParams& params, \ Gu::Cache& cache, \ PxContactBuffer& contactBuffer, \ PxRenderOutput* renderOutput #define GU_CONTACT_METHOD_ARGS_UNUSED \ const PxGeometry&, \ const PxGeometry&, \ const PxTransform32&, \ const PxTransform32&, \ const Gu::NarrowPhaseParams&, \ Gu::Cache&, \ PxContactBuffer&, \ PxRenderOutput* namespace Gu { PX_PHYSX_COMMON_API bool contactSphereSphere(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactConvexConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactConvexMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSphereHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCapsuleHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactBoxHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactConvexHeightfield(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactSpherePlane(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactPlaneBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactPlaneCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactPlaneConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactCustomGeometryGeometry(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool contactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactConvexMesh(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactConvexHeightField(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactPlaneCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactPlaneBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactPlaneConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereSphere(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSpherePlane(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactSphereConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleCapsule(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactCapsuleConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxBox(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactBoxConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactConvexConvex(GU_CONTACT_METHOD_ARGS); PX_PHYSX_COMMON_API bool pcmContactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS); } } #endif
7,987
C
38.544554
140
0.771504
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactSphereCapsule.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 "geomutils/PxContactBuffer.h" #include "GuDistancePointSegment.h" #include "GuContactMethodImpl.h" #include "GuInternal.h" using namespace physx; bool Gu::contactSphereCapsule(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxSphereGeometry& sphereGeom = checkedCast<PxSphereGeometry>(shape0); const PxCapsuleGeometry& capsuleGeom = checkedCast<PxCapsuleGeometry>(shape1); // PT: get capsule in local space const PxVec3 capsuleLocalSegment = getCapsuleHalfHeightVector(transform1, capsuleGeom); const Segment localSegment(capsuleLocalSegment, -capsuleLocalSegment); // PT: get sphere in capsule space const PxVec3 sphereCenterInCapsuleSpace = transform0.p - transform1.p; const PxReal radiusSum = sphereGeom.radius + capsuleGeom.radius; const PxReal inflatedSum = radiusSum + params.mContactDistance; // PT: compute distance between sphere center & capsule's segment PxReal u; const PxReal squareDist = distancePointSegmentSquared(localSegment, sphereCenterInCapsuleSpace, &u); if(squareDist >= inflatedSum*inflatedSum) return false; // PT: compute contact normal PxVec3 normal = sphereCenterInCapsuleSpace - localSegment.getPointAt(u); // We do a *manual* normalization to check for singularity condition const PxReal lenSq = normal.magnitudeSquared(); if(lenSq==0.0f) normal = PxVec3(1.0f, 0.0f, 0.0f); // PT: zero normal => pick up random one else normal *= PxRecipSqrt(lenSq); // PT: compute contact point const PxVec3 point = sphereCenterInCapsuleSpace + transform1.p - normal * sphereGeom.radius; // PT: output unique contact contactBuffer.contact(point, normal, PxSqrt(squareDist) - radiusSum); return true; }
3,397
C++
43.12987
101
0.771563
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactConvexConvex.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 "geomutils/PxContactBuffer.h" #include "GuContactPolygonPolygon.h" #include "GuConvexHelper.h" #include "GuInternal.h" #include "GuSeparatingAxes.h" #include "GuContactMethodImpl.h" #include "foundation/PxFPU.h" #include "foundation/PxAlloca.h" #include "CmMatrix34.h" // csigg: the single reference of gEnableOptims (below) has been // replaced with the actual value to prevent ios64 compiler crash. // static const int gEnableOptims = 1; #define CONVEX_CONVEX_ROUGH_FIRST_PASS #define TEST_INTERNAL_OBJECTS #ifdef TEST_INTERNAL_OBJECTS #define USE_BOX_DATA #endif using namespace physx; using namespace Gu; using namespace Cm; using namespace aos; using namespace intrinsics; #ifdef TEST_INTERNAL_OBJECTS #ifdef USE_BOX_DATA PX_FORCE_INLINE void BoxSupport(const float extents[3], const PxVec3& sv, float p[3]) { const PxU32* iextents = reinterpret_cast<const PxU32*>(extents); const PxU32* isv = reinterpret_cast<const PxU32*>(&sv); PxU32* ip = reinterpret_cast<PxU32*>(p); ip[0] = iextents[0]|(isv[0]&PX_SIGN_BITMASK); ip[1] = iextents[1]|(isv[1]&PX_SIGN_BITMASK); ip[2] = iextents[2]|(isv[2]&PX_SIGN_BITMASK); } #endif #if PX_DEBUG static const PxReal testInternalObjectsEpsilon = 1.0e-3f; #endif #ifdef DO_NOT_REMOVE PX_FORCE_INLINE void testInternalObjects_( const PxVec3& delta_c, const PxVec3& axis, const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& tr0, const PxMat34& tr1, float& dmin, float contactDistance) { { /* float projected0 = axis.dot(tr0.p); float projected1 = axis.dot(tr1.p); float min0 = projected0 - polyData0.mInternal.mRadius; float max0 = projected0 + polyData0.mInternal.mRadius; float min1 = projected1 - polyData1.mInternal.mRadius; float max1 = projected1 + polyData1.mInternal.mRadius; */ float MinMaxRadius = polyData0.mInternal.mRadius + polyData1.mInternal.mRadius; PxVec3 delta = tr0.p - tr1.p; const PxReal dp = axis.dot(delta); // const PxReal dp2 = axis.dot(delta_c); // const PxReal d0 = max0 - min1; // const PxReal d0 = projected0 + polyData0.mInternal.mRadius - projected1 + polyData1.mInternal.mRadius; // const PxReal d0 = projected0 - projected1 + polyData0.mInternal.mRadius + polyData1.mInternal.mRadius; // const PxReal d0 = projected0 - projected1 + MinMaxRadius; // const PxReal d0 = axis.dot(tr0.p) - axis.dot(tr1.p) + MinMaxRadius; // const PxReal d0 = axis.dot(tr0.p - tr1.p) + MinMaxRadius; // const PxReal d0 = MinMaxRadius + axis.dot(delta); const PxReal d0 = MinMaxRadius + dp; // const PxReal d1 = max1 - min0; // const PxReal d1 = projected1 + polyData1.mInternal.mRadius - projected0 + polyData0.mInternal.mRadius; // const PxReal d1 = projected1 - projected0 + polyData1.mInternal.mRadius + polyData0.mInternal.mRadius; // const PxReal d1 = projected1 - projected0 + MinMaxRadius; // const PxReal d1 = axis.dot(tr1.p) - axis.dot(tr0.p) + MinMaxRadius; // const PxReal d1 = axis.dot(tr1.p - tr0.p) + MinMaxRadius; // const PxReal d1 = MinMaxRadius - axis.dot(delta); const PxReal d1 = MinMaxRadius - dp; dmin = selectMin(d0, d1); return; } #ifdef USE_BOX_DATA const PxVec3 localAxis0 = tr0.rotateTranspose(axis); const PxVec3 localAxis1 = tr1.rotateTranspose(axis); const float dp = delta_c.dot(axis); float p0[3]; BoxSupport(polyData0.mInternal.mExtents, localAxis0, p0); float p1[3]; BoxSupport(polyData1.mInternal.mExtents, localAxis1, p1); const float Radius0 = p0[0]*localAxis0.x + p0[1]*localAxis0.y + p0[2]*localAxis0.z; const float Radius1 = p1[0]*localAxis1.x + p1[1]*localAxis1.y + p1[2]*localAxis1.z; const float MinRadius = selectMax(Radius0, polyData0.mInternal.mRadius); const float MaxRadius = selectMax(Radius1, polyData1.mInternal.mRadius); #else const float dp = delta_c.dot(axis); const float MinRadius = polyData0.mInternal.mRadius; const float MaxRadius = polyData1.mInternal.mRadius; #endif const float MinMaxRadius = MaxRadius + MinRadius; const float d0 = MinMaxRadius + dp; const float d1 = MinMaxRadius - dp; dmin = selectMin(d0, d1); } #endif static PX_FORCE_INLINE bool testInternalObjects( const PxVec3& delta_c, const PxVec3& axis, const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& tr0, const PxMat34& tr1, float dmin) { #ifdef USE_BOX_DATA const PxVec3 localAxis0 = tr0.rotateTranspose(axis); const PxVec3 localAxis1 = tr1.rotateTranspose(axis); const float dp = delta_c.dot(axis); float p0[3]; BoxSupport(polyData0.mInternal.mExtents, localAxis0, p0); float p1[3]; BoxSupport(polyData1.mInternal.mExtents, localAxis1, p1); const float Radius0 = p0[0]*localAxis0.x + p0[1]*localAxis0.y + p0[2]*localAxis0.z; const float Radius1 = p1[0]*localAxis1.x + p1[1]*localAxis1.y + p1[2]*localAxis1.z; const float MinRadius = selectMax(Radius0, polyData0.mInternal.mRadius); const float MaxRadius = selectMax(Radius1, polyData1.mInternal.mRadius); #else const float dp = delta_c.dot(axis); const float MinRadius = polyData0.mInternal.mRadius; const float MaxRadius = polyData1.mInternal.mRadius; #endif const float MinMaxRadius = MaxRadius + MinRadius; const float d0 = MinMaxRadius + dp; const float d1 = MinMaxRadius - dp; const float depth = selectMin(d0, d1); if(depth>dmin) return false; return true; } #endif PX_FORCE_INLINE float PxcMultiplyAdd3x4(PxU32 i, const PxVec3& p0, const PxVec3& p1, const PxMat34& world) { return (p1.x + p0.x) * world.m.column0[i] + (p1.y + p0.y) * world.m.column1[i] + (p1.z + p0.z) * world.m.column2[i] + 2.0f * world.p[i]; } PX_FORCE_INLINE float PxcMultiplySub3x4(PxU32 i, const PxVec3& p0, const PxVec3& p1, const PxMat34& world) { return (p1.x - p0.x) * world.m.column0[i] + (p1.y - p0.y) * world.m.column1[i] + (p1.z - p0.z) * world.m.column2[i]; } static PX_FORCE_INLINE bool testNormal( const PxVec3& axis, PxReal min0, PxReal max0, const PolygonalData& polyData1, const PxMat34& m1to0, const FastVertex2ShapeScaling& scaling1, PxReal& depth, PxReal contactDistance) { //The separating axis we want to test is a face normal of hull0 PxReal min1, max1; (polyData1.mProjectHull)(polyData1, axis, m1to0, scaling1, min1, max1); if(max0+contactDistance<min1 || max1+contactDistance<min0) return false; const PxReal d0 = max0 - min1; const PxReal d1 = max1 - min0; depth = selectMin(d0, d1); return true; } static PX_FORCE_INLINE bool testSeparatingAxis( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxVec3& axis, PxReal& depth, PxReal contactDistance) { PxReal min0, max0; (polyData0.mProjectHull)(polyData0, axis, world0, scaling0, min0, max0); return testNormal(axis, min0, max0, polyData1, world1, scaling1, depth, contactDistance); } static bool PxcSegmentAABBIntersect(const PxVec3& p0, const PxVec3& p1, const PxVec3& minimum, const PxVec3& maximum, const PxMat34& world) { PxVec3 boxExtent, diff, dir; PxReal fAWdU[3]; dir.x = PxcMultiplySub3x4(0, p0, p1, world); boxExtent.x = maximum.x - minimum.x; diff.x = (PxcMultiplyAdd3x4(0, p0, p1, world) - (maximum.x+minimum.x)); fAWdU[0] = PxAbs(dir.x); if(PxAbs(diff.x)> boxExtent.x + fAWdU[0]) return false; dir.y = PxcMultiplySub3x4(1, p0, p1, world); boxExtent.y = maximum.y - minimum.y; diff.y = (PxcMultiplyAdd3x4(1, p0, p1, world) - (maximum.y+minimum.y)); fAWdU[1] = PxAbs(dir.y); if(PxAbs(diff.y)> boxExtent.y + fAWdU[1]) return false; dir.z = PxcMultiplySub3x4(2, p0, p1, world); boxExtent.z = maximum.z - minimum.z; diff.z = (PxcMultiplyAdd3x4(2, p0, p1, world) - (maximum.z+minimum.z)); fAWdU[2] = PxAbs(dir.z); if(PxAbs(diff.z)> boxExtent.z + fAWdU[2]) return false; PxReal f; f = dir.y * diff.z - dir.z*diff.y; if(PxAbs(f)>boxExtent.y*fAWdU[2] + boxExtent.z*fAWdU[1]) return false; f = dir.z * diff.x - dir.x*diff.z; if(PxAbs(f)>boxExtent.x*fAWdU[2] + boxExtent.z*fAWdU[0]) return false; f = dir.x * diff.y - dir.y*diff.x; if(PxAbs(f)>boxExtent.x*fAWdU[1] + boxExtent.y*fAWdU[0]) return false; return true; } #define EXPERIMENT /* Edge culling can clearly be improved : in ConvexTest02 for example, edges don't even touch the other mesh sometimes. */ static void PxcFindSeparatingAxes( SeparatingAxes& sa, const PxU32* PX_RESTRICT indices, PxU32 numPolygons, const PolygonalData& polyData, const PxMat34& world0, const PxPlane& plane, const PxMat34& m0to1, const PxBounds3& aabb, PxReal contactDistance, const FastVertex2ShapeScaling& scaling) { // EdgeCache edgeCache; // PT: TODO: check this is actually useful const PxVec3* PX_RESTRICT vertices = polyData.mVerts; const HullPolygonData* PX_RESTRICT polygons = polyData.mPolygons; const PxU8* PX_RESTRICT vrefsBase = polyData.mPolygonVertexRefs; while(numPolygons--) { //Get current polygon const HullPolygonData& P = polygons[*indices++]; const PxU8* PX_RESTRICT VData = vrefsBase + P.mVRef8; // Loop through polygon vertices == polygon edges PxU32 numVerts = P.mNbVerts; #ifdef EXPERIMENT PxVec3 p0,p1; PxU8 VRef0 = VData[0]; p0 = scaling * vertices[VRef0]; bool b0 = plane.distance(p0) <= contactDistance; #endif for(PxU32 j = 0; j < numVerts; j++) { PxU32 j1 = j+1; if(j1 >= numVerts) j1 = 0; #ifndef EXPERIMENT PxU8 VRef0 = VData[j]; #endif PxU8 VRef1 = VData[j1]; // PxOrder(VRef0, VRef1); //make sure edge (a,b) == edge (b,a) // if (edgeCache.isInCache(VRef0, VRef1)) // continue; //transform points //TODO: once this works we could transform plan instead, that is more efficient!! #ifdef EXPERIMENT p1 = scaling * vertices[VRef1]; #else const PxVec3 p0 = scaling * vertices[VRef0]; const PxVec3 p1 = scaling * vertices[VRef1]; #endif // Cheap but effective culling! #ifdef EXPERIMENT bool b1 = plane.distance(p1) <= contactDistance; if(b0 || b1) #else if(plane.signedDistanceHessianNormalForm(p0) <= contactDistance || plane.signedDistanceHessianNormalForm(p1) <= contactDistance) #endif { if(PxcSegmentAABBIntersect(p0, p1, aabb.minimum, aabb.maximum, m0to1)) { // Create current edge. We're only interested in different edge directions so we normalize. const PxVec3 currentEdge = world0.rotate(p0 - p1).getNormalized(); sa.addAxis(currentEdge); } } #ifdef EXPERIMENT VRef0 = VRef1; p0 = p1; b0 = b1; #endif } } } static bool PxcTestFacesSepAxesBackface(const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m1to0, const PxVec3& delta, PxReal& dmin, PxVec3& sep, PxU32& id, PxU32* PX_RESTRICT indices_, PxU32& numIndices, PxReal contactDistance, float toleranceLength #ifdef TEST_INTERNAL_OBJECTS , const PxVec3& worldDelta #endif ) { PX_UNUSED(toleranceLength); // Only used in Debug id = PX_INVALID_U32; PxU32* indices = indices_; const PxU32 num = polyData0.mNbPolygons; const PxVec3* PX_RESTRICT vertices = polyData0.mVerts; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; //transform delta from hull0 shape into vertex space: const PxVec3 vertSpaceDelta = scaling0 % delta; // PT: prefetch polygon data { const PxU32 dataSize = num*sizeof(HullPolygonData); for(PxU32 offset=0; offset < dataSize; offset+=128) PxPrefetchLine(polygons, offset); } for(PxU32 i=0; i < num; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; // Do backface-culling if(PL.n.dot(vertSpaceDelta) < 0.0f) continue; //normals transform by inverse transpose: (and transpose(skew) == skew as its symmetric) PxVec3 shapeSpaceNormal = scaling0 % PL.n; //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); // PT: We need to find a way to skip this normalize #ifdef TEST_INTERNAL_OBJECTS /* const PxVec3 worldNormal_ = world0.rotate(shapeSpaceNormal); PxReal d0; bool test0 = PxcTestSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, worldNormal_, d0, contactDistance); PxReal d1; const float invMagnitude0 = 1.0f / magnitude; bool test1 = PxcTestNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude0, P.getMax() * invMagnitude0, polyData1, m1to0, scaling1, d1, contactDistance); PxReal d2; testInternalObjects_(worldDelta, worldNormal_, polyData0, polyData1, world0, world1, d2, contactDistance); */ const PxVec3 worldNormal = world0.rotate(shapeSpaceNormal); if(!testInternalObjects(worldDelta, worldNormal, polyData0, polyData1, world0, world1, dmin)) { #if PX_DEBUG PxReal d; const float invMagnitude = 1.0f / magnitude; if(testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. { PX_ASSERT(d + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif *indices++ = i; //////////////////// /* //gotta transform minimum and maximum from vertex to shape space! //I think they transform like the 'd' of the plane, basically by magnitude division! //unfortunately I am not certain of that, so let's convert them to a point in vertex space, transform that, and then convert back to a plane d. //let's start by transforming the plane's d: //a point on the plane: PxVec3 vertSpaceDPoint = PL.normal * -PL.d; //make sure this is on the plane: PxReal distZero = PL.signedDistanceHessianNormalForm(vertSpaceDPoint); //should be zero //transform: PxVec3 shapeSpaceDPoint = cache.mVertex2ShapeSkew[skewIndex] * vertSpaceDPoint; //make into a d offset again by projecting along the plane: PxcPlane shapeSpacePlane(shapeSpaceNormal, shapeSpaceDPoint); //see what D is!! //NOTE: for boxes scale[0] is always id so this is all redundant. Hopefully for convex convex it will become useful! */ //////////////////// PxReal d; const float invMagnitude = 1.0f / magnitude; if(!testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. return false; if(d < dmin) { #ifdef TEST_INTERNAL_OBJECTS sep = worldNormal; #else sep = world0.rotate(shapeSpaceNormal); #endif dmin = d; id = i; } } numIndices = PxU32(indices - indices_); PX_ASSERT(id!=PX_INVALID_U32); //Should never happen with this version return true; } // PT: isolating this piece of code allows us to better see what happens in PIX. For some reason it looks // like isolating it creates *less* LHS than before, but I don't understand why. There's still a lot of // bad stuff there anyway //PX_FORCE_INLINE static void prepareData(PxPlane& witnessPlane0, PxPlane& witnessPlane1, PxBounds3& aabb0, PxBounds3& aabb1, const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PxPlane& vertSpacePlane0, const PxPlane& vertSpacePlane1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m0to1, const PxMat34& m1to0, PxReal contactDistance ) { scaling0.transformPlaneToShapeSpace(vertSpacePlane0.n, vertSpacePlane0.d, witnessPlane0.n, witnessPlane0.d); scaling1.transformPlaneToShapeSpace(vertSpacePlane1.n, vertSpacePlane1.d, witnessPlane1.n, witnessPlane1.d); //witnessPlane0 = witnessPlane0.getTransformed(m0to1); //witnessPlane1 = witnessPlane1.getTransformed(m1to0); const PxVec3 newN0 = m0to1.rotate(witnessPlane0.n); witnessPlane0 = PxPlane(newN0, witnessPlane0.d - m0to1.p.dot(newN0)); const PxVec3 newN1 = m1to0.rotate(witnessPlane1.n); witnessPlane1 = PxPlane(newN1, witnessPlane1.d - m1to0.p.dot(newN1)); aabb0 = hullBounds0; aabb1 = hullBounds1; //gotta inflate // PT: perfect LHS recipe here.... const PxVec3 inflate(contactDistance); aabb0.minimum -= inflate; aabb1.minimum -= inflate; aabb0.maximum += inflate; aabb1.maximum += inflate; } static bool PxcBruteForceOverlapBackface( const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m0to1, const PxMat34& m1to0, const PxVec3& delta, PxU32& id0, PxU32& id1, PxReal& depth, PxVec3& sep, PxcSepAxisType& code, PxReal contactDistance, float toleranceLength) { const PxVec3 localDelta0 = world0.rotateTranspose(delta); PxU32* PX_RESTRICT indices0 = reinterpret_cast<PxU32*>(PxAlloca(polyData0.mNbPolygons*sizeof(PxU32))); PxU32 numIndices0; PxReal dmin0 = PX_MAX_REAL; PxVec3 vec0; if(!PxcTestFacesSepAxesBackface(polyData0, polyData1, world0, world1, scaling0, scaling1, m1to0, localDelta0, dmin0, vec0, id0, indices0, numIndices0, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , -delta #endif )) return false; const PxVec3 localDelta1 = world1.rotateTranspose(delta); PxU32* PX_RESTRICT indices1 = reinterpret_cast<PxU32*>(PxAlloca(polyData1.mNbPolygons*sizeof(PxU32))); PxU32 numIndices1; PxReal dmin1 = PX_MAX_REAL; PxVec3 vec1; if(!PxcTestFacesSepAxesBackface(polyData1, polyData0, world1, world0, scaling1, scaling0, m0to1, -localDelta1, dmin1, vec1, id1, indices1, numIndices1, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , delta #endif )) return false; PxReal dmin = dmin0; PxVec3 vec = vec0; code = SA_NORMAL0; if(dmin1 < dmin) { dmin = dmin1; vec = vec1; code = SA_NORMAL1; } PX_ASSERT(id0!=PX_INVALID_U32); PX_ASSERT(id1!=PX_INVALID_U32); // Brute-force find a separating axis SeparatingAxes mSA0; SeparatingAxes mSA1; mSA0.reset(); mSA1.reset(); PxPlane witnessPlane0; PxPlane witnessPlane1; PxBounds3 aabb0, aabb1; prepareData(witnessPlane0, witnessPlane1, aabb0, aabb1, hullBounds0, hullBounds1, polyData0.mPolygons[id0].mPlane, polyData1.mPolygons[id1].mPlane, scaling0, scaling1, m0to1, m1to0, contactDistance); // Find possibly separating axes PxcFindSeparatingAxes(mSA0, indices0, numIndices0, polyData0, world0, witnessPlane1, m0to1, aabb1, contactDistance, scaling0); PxcFindSeparatingAxes(mSA1, indices1, numIndices1, polyData1, world1, witnessPlane0, m1to0, aabb0, contactDistance, scaling1); // PxcFindSeparatingAxes(context.mSA0, &id0, 1, hull0, world0, witnessPlane1, m0to1, aabbMin1, aabbMax1); // PxcFindSeparatingAxes(context.mSA1, &id1, 1, hull1, world1, witnessPlane0, m1to0, aabbMin0, aabbMax0); const PxU32 numEdges0 = mSA0.getNumAxes(); const PxVec3* PX_RESTRICT edges0 = mSA0.getAxes(); const PxU32 numEdges1 = mSA1.getNumAxes(); const PxVec3* PX_RESTRICT edges1 = mSA1.getAxes(); // Worst case = convex test 02 with big meshes: 23 & 23 edges => 23*23 = 529 tests! // printf("%d - %d\n", NbEdges0, NbEdges1); // maximum = ~20 in test scenes. for(PxU32 i=0; i < numEdges0; i++) { const PxVec3& edge0 = edges0[i]; for(PxU32 j=0; j < numEdges1; j++) { const PxVec3& edge1 = edges1[j]; PxVec3 sepAxis = edge0.cross(edge1); if(!isAlmostZero(sepAxis)) { sepAxis = sepAxis.getNormalized(); #ifdef TEST_INTERNAL_OBJECTS if(!testInternalObjects(-delta, sepAxis, polyData0, polyData1, world0, world1, dmin)) { #if PX_DEBUG PxReal d; if(testSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, sepAxis, d, contactDistance)) { PX_ASSERT(d + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif PxReal d; if(!testSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, sepAxis, d, contactDistance)) return false; if(d<dmin) { dmin = d; vec = sepAxis; code = SA_EE; } } } } depth = dmin; sep = vec; return true; } static bool GuTestFacesSepAxesBackfaceRoughPass( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m1to0, const PxVec3& /*witness*/, const PxVec3& delta, PxReal& dmin, PxVec3& sep, PxU32& id, PxReal contactDistance, float toleranceLength #ifdef TEST_INTERNAL_OBJECTS , const PxVec3& worldDelta #endif ) { PX_UNUSED(toleranceLength); // Only used in Debug id = PX_INVALID_U32; const PxU32 num = polyData0.mNbPolygons; const HullPolygonData* PX_RESTRICT polygons = polyData0.mPolygons; const PxVec3* PX_RESTRICT vertices = polyData0.mVerts; //transform delta from hull0 shape into vertex space: const PxVec3 vertSpaceDelta = scaling0 % delta; for(PxU32 i=0; i < num; i++) { const HullPolygonData& P = polygons[i]; const PxPlane& PL = P.mPlane; if(PL.n.dot(vertSpaceDelta) < 0.0f) continue; //backface-cull PxVec3 shapeSpaceNormal = scaling0 % PL.n; //normals transform with inverse transpose //renormalize: (Arr!) const PxReal magnitude = shapeSpaceNormal.normalize(); // PT: We need to find a way to skip this normalize #ifdef TEST_INTERNAL_OBJECTS const PxVec3 worldNormal = world0.rotate(shapeSpaceNormal); if(!testInternalObjects(worldDelta, worldNormal, polyData0, polyData1, world0, world1, dmin)) { #if PX_DEBUG PxReal d; const float invMagnitude = 1.0f / magnitude; if(testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, /*hull1,*/ polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. { PX_ASSERT(d + testInternalObjectsEpsilon*toleranceLength >= dmin); } #endif continue; } #endif PxReal d; const float invMagnitude = 1.0f / magnitude; if(!testNormal(shapeSpaceNormal, P.getMin(vertices) * invMagnitude, P.getMax() * invMagnitude, /*hull1,*/ polyData1, m1to0, scaling1, d, contactDistance)) //note how we scale scalars by skew magnitude change as we do plane d-s. return false; if(d < dmin) { #ifdef TEST_INTERNAL_OBJECTS sep = worldNormal; #else sep = world0.rotate(shapeSpaceNormal); #endif dmin = d; id = i; } } PX_ASSERT(id!=PX_INVALID_U32); //Should never happen with this version return true; } static bool GuBruteForceOverlapBackfaceRoughPass( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxMat34& world0, const PxMat34& world1, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, const PxMat34& m0to1, const PxMat34& m1to0, const PxVec3& delta, PxU32& id0, PxU32& id1, PxReal& depth, PxVec3& sep, PxcSepAxisType& code, PxReal contactDistance, PxReal toleranceLength) { PxReal dmin0 = PX_MAX_REAL; PxReal dmin1 = PX_MAX_REAL; PxVec3 vec0, vec1; const PxVec3 localDelta0 = world0.rotateTranspose(delta); const PxVec3 localCenter1in0 = m1to0.transform(polyData1.mCenter); if(!GuTestFacesSepAxesBackfaceRoughPass(polyData0, polyData1, world0, world1, scaling0, scaling1, m1to0, localCenter1in0, localDelta0, dmin0, vec0, id0, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , -delta #endif )) return false; const PxVec3 localDelta1 = world1.rotateTranspose(delta); const PxVec3 localCenter0in1 = m0to1.transform(polyData0.mCenter); if(!GuTestFacesSepAxesBackfaceRoughPass(polyData1, polyData0, world1, world0, scaling1, scaling0, m0to1, localCenter0in1, -localDelta1, dmin1, vec1, id1, contactDistance, toleranceLength #ifdef TEST_INTERNAL_OBJECTS , delta #endif )) return false; PxReal dmin = dmin0; PxVec3 vec = vec0; code = SA_NORMAL0; if(dmin1 < dmin) { dmin = dmin1; vec = vec1; code = SA_NORMAL1; } PX_ASSERT(id0!=PX_INVALID_U32); PX_ASSERT(id1!=PX_INVALID_U32); depth = dmin; sep = vec; return true; } static bool GuContactHullHull( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, bool idtScale0, bool idtScale1); // Box-convex contact generation // this can no longer share code with convex-convex because that case needs scaling for both shapes, while this only needs it for one, which may be significant perf wise. // // PT: duplicating the full convex-vs-convex codepath is a lot worse. Look at it this way: if scaling is really "significant perf wise" then we made the whole convex-convex // codepath significantly slower, and this is a lot more important than just box-vs-convex. The proper approach is to share the code and make sure scaling is NOT a perf hit. // PT: please leave this function in the same translation unit as PxcContactHullHull. bool Gu::contactBoxConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape0); const PxConvexMeshGeometry& shapeConvex = checkedCast<PxConvexMeshGeometry>(shape1); FastVertex2ShapeScaling idtScaling; const PxBounds3 boxBounds(-shapeBox.halfExtents, shapeBox.halfExtents); PolygonalData polyData0; PolygonalBox polyBox(shapeBox.halfExtents); polyBox.getPolygonalData(&polyData0); /////// FastVertex2ShapeScaling convexScaling; PxBounds3 convexBounds; PolygonalData polyData1; const bool idtScale = getConvexData(shapeConvex, convexScaling, convexBounds, polyData1); return GuContactHullHull( polyData0, polyData1, boxBounds, convexBounds, transform0, transform1, params, contactBuffer, idtScaling, convexScaling, true, idtScale); } // PT: please leave this function in the same translation unit as PxcContactHullHull. bool Gu::contactConvexConvex(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(cache); PX_UNUSED(renderOutput); const PxConvexMeshGeometry& shapeConvex0 = checkedCast<PxConvexMeshGeometry>(shape0); const PxConvexMeshGeometry& shapeConvex1 = checkedCast<PxConvexMeshGeometry>(shape1); FastVertex2ShapeScaling scaling0, scaling1; PxBounds3 convexBounds0, convexBounds1; PolygonalData polyData0, polyData1; const bool idtScale0 = getConvexData(shapeConvex0, scaling0, convexBounds0, polyData0); const bool idtScale1 = getConvexData(shapeConvex1, scaling1, convexBounds1, polyData1); return GuContactHullHull( polyData0, polyData1, convexBounds0, convexBounds1, transform0, transform1, params, contactBuffer, scaling0, scaling1, idtScale0, idtScale1); } static bool GuContactHullHull( const PolygonalData& polyData0, const PolygonalData& polyData1, const PxBounds3& hullBounds0, const PxBounds3& hullBounds1, const PxTransform& transform0, const PxTransform& transform1, const NarrowPhaseParams& params, PxContactBuffer& contactBuffer, const FastVertex2ShapeScaling& scaling0, const FastVertex2ShapeScaling& scaling1, bool idtScale0, bool idtScale1) { // Compute matrices const Matrix34FromTransform world0(transform0); const Matrix34FromTransform world1(transform1); const PxVec3 worldCenter0 = world0.transform(polyData0.mCenter); const PxVec3 worldCenter1 = world1.transform(polyData1.mCenter); const PxVec3 deltaC = worldCenter1 - worldCenter0; PxReal depth; /////////////////////////////////////////////////////////////////////////// // Early-exit test: quickly discard obviously non-colliding cases. // PT: we used to skip this when objects were touching, which provided a small speedup (saving 2 full hull projections). // We may want to add this back at some point in the future, if possible. if(true) //AM: now we definitely want to test the cached axis to get the depth value for the cached axis, even if we had a contact before. { if(!testSeparatingAxis(polyData0, polyData1, world0, world1, scaling0, scaling1, deltaC, depth, params.mContactDistance)) //there was no contact previously and we reject using the same prev. axis. return false; } /////////////////////////////////////////////////////////////////////////// // Compute relative transforms PxTransform t0to1 = transform1.transformInv(transform0); PxTransform t1to0 = transform0.transformInv(transform1); PxU32 c0(0x7FFF); PxU32 c1(0x7FFF); PxVec3 worldNormal; const Matrix34FromTransform m0to1(t0to1); const Matrix34FromTransform m1to0(t1to0); #ifdef CONVEX_CONVEX_ROUGH_FIRST_PASS // PT: it is a bad idea to skip the rough pass, for two reasons: // 1) performance. The rough pass is obviously a lot faster. // 2) stability. The "skipIt" optimization relies on the rough pass being present to catch the cases where it fails. If you disable the rough pass // "skipIt" can skip the whole work, contacts get lost, and we never "try again" ==> explosions // bool TryRoughPass = (contactDistance == 0.0f); //Rough first pass doesn't work with dist based for some reason. for(int TryRoughPass = 1 /*gEnableOptims*/; 0 <= TryRoughPass; --TryRoughPass) { #endif { PxcSepAxisType code; PxU32 id0, id1; //PxReal depth; #ifdef CONVEX_CONVEX_ROUGH_FIRST_PASS bool Status; if(TryRoughPass) { Status = GuBruteForceOverlapBackfaceRoughPass(polyData0, polyData1, world0, world1, scaling0, scaling1, m0to1, m1to0, deltaC, id0, id1, depth, worldNormal, code, params.mContactDistance, params.mToleranceLength); } else { Status = PxcBruteForceOverlapBackface( // hull0, hull1, hullBounds0, hullBounds1, polyData0, polyData1, world0, world1, scaling0, scaling1, m0to1, m1to0, deltaC, id0, id1, depth, worldNormal, code, params.mContactDistance, params.mToleranceLength); } if(!Status) #else if(!PxcBruteForceOverlapBackface( // hull0, hull1, hullBounds0, hullBounds1, polyData0, polyData1, world0, world1, scaling0, scaling1, m0to1, m1to0, deltaC, id0, id1, depth, worldNormal, code, contactDistance)) #endif return false; if(deltaC.dot(worldNormal) < 0.0f) worldNormal = -worldNormal; /* worldNormal = -partialSep; depth = -partialDepth; code = SA_EE; */ if(code==SA_NORMAL0) { c0 = id0; c1 = (polyData1.mSelectClosestEdgeCB)(polyData1, scaling1, world1.rotateTranspose(-worldNormal)); } else if(code==SA_NORMAL1) { c0 = (polyData0.mSelectClosestEdgeCB)(polyData0, scaling0, world0.rotateTranspose(worldNormal)); c1 = id1; } else if(code==SA_EE) { c0 = (polyData0.mSelectClosestEdgeCB)(polyData0, scaling0, world0.rotateTranspose(worldNormal)); c1 = (polyData1.mSelectClosestEdgeCB)(polyData1, scaling1, world1.rotateTranspose(-worldNormal)); } } const HullPolygonData& HP0 = polyData0.mPolygons[c0]; const HullPolygonData& HP1 = polyData1.mPolygons[c1]; // PT: prefetching those guys saves ~600.000 cycles in convex-convex benchmark PxPrefetchLine(&HP0.mPlane); PxPrefetchLine(&HP1.mPlane); //ok, we have a new depth value. convert to real distance. // PxReal separation = -depth; //depth was either computed in initial cached-axis check, or better, when skipIt was false, in sep axis search. // if (separation < 0.0f) // separation = 0.0f; //we don't want to store penetration values. const PxReal separation = fsel(depth, 0.0f, -depth); PxVec3 worldNormal0; PX_ALIGN(16, PxPlane) shapeSpacePlane0; if(idtScale0) { V4StoreA(V4LoadU(&HP0.mPlane.n.x), &shapeSpacePlane0.n.x); worldNormal0 = world0.rotate(HP0.mPlane.n); } else { scaling0.transformPlaneToShapeSpace(HP0.mPlane.n,HP0.mPlane.d,shapeSpacePlane0.n,shapeSpacePlane0.d); worldNormal0 = world0.rotate(shapeSpacePlane0.n); } PxVec3 worldNormal1; PX_ALIGN(16, PxPlane) shapeSpacePlane1; if(idtScale1) { V4StoreA(V4LoadU(&HP1.mPlane.n.x), &shapeSpacePlane1.n.x); worldNormal1 = world1.rotate(HP1.mPlane.n); } else { scaling1.transformPlaneToShapeSpace(HP1.mPlane.n,HP1.mPlane.d,shapeSpacePlane1.n,shapeSpacePlane1.d); worldNormal1 = world1.rotate(shapeSpacePlane1.n); } PxIntBool flag; { const PxReal d0 = PxAbs(worldNormal0.dot(worldNormal)); const PxReal d1 = PxAbs(worldNormal1.dot(worldNormal)); bool f = d0>d1; //which face normal is the separating axis closest to. flag = f; } ////////////////////NEW DIST HANDLING////////////////////// PX_ASSERT(separation >= 0.0f); //be sure this got fetched somewhere in the chaos above. const PxReal cCCDEpsilon = params.mMeshContactMargin; const PxReal contactGenPositionShift = separation + cCCDEpsilon; //if we're at a distance, shift so we're in penetration. const PxVec3 contactGenPositionShiftVec = worldNormal * -contactGenPositionShift; //shift one of the bodies this distance toward the other just for Pierre's contact generation. Then the bodies should be penetrating exactly by MIN_SEPARATION_FOR_PENALTY - ideal conditions for this contact generator. //note: for some reason this has to change sign! //this will make contact gen always generate contacts at about MSP. Shift them back to the true real distance, and then to a solver compliant distance given that //the solver converges to MSP penetration, while we want it to converge to 0 penetration. //to real distance: //The system: We always shift convex 0 (arbitrary). If the contact is attached to convex 0 then we will need to shift the contact point, otherwise not. const PxVec3 newp = world0.p - contactGenPositionShiftVec; const PxMat34 world0_Tweaked(world0.m.column0, world0.m.column1, world0.m.column2, newp); PxTransform shifted0(newp, transform0.q); t0to1 = transform1.transformInv(shifted0); t1to0 = shifted0.transformInv(transform1); const Matrix34FromTransform m0to1_Tweaked(t0to1); const Matrix34FromTransform m1to0_Tweaked(t1to0); ////////////////////////////////////////////////// //pretransform convex polygon if we have scaling! PxVec3* scaledVertices0; PxU8* stackIndices0; GET_SCALEX_CONVEX(scaledVertices0, stackIndices0, idtScale0, HP0.mNbVerts, scaling0, polyData0.mVerts, polyData0.getPolygonVertexRefs(HP0)) //pretransform convex polygon if we have scaling! PxVec3* scaledVertices1; PxU8* stackIndices1; GET_SCALEX_CONVEX(scaledVertices1, stackIndices1, idtScale1, HP1.mNbVerts, scaling1, polyData1.mVerts, polyData1.getPolygonVertexRefs(HP1)) // So we need to switch: // - HP0, HP1 // - scaledVertices0, scaledVertices1 // - stackIndices0, stackIndices1 // - world0, world1 // - shapeSpacePlane0, shapeSpacePlane1 // - worldNormal0, worldNormal1 // - m0to1, m1to0 // - true, false const PxMat33 RotT0 = findRotationMatrixFromZ(shapeSpacePlane0.n); const PxMat33 RotT1 = findRotationMatrixFromZ(shapeSpacePlane1.n); if(flag) { if(contactPolygonPolygonExt(HP0.mNbVerts, scaledVertices0, stackIndices0, world0_Tweaked, shapeSpacePlane0, RotT0, HP1.mNbVerts, scaledVertices1, stackIndices1, world1, shapeSpacePlane1, RotT1, worldNormal0, m0to1_Tweaked, m1to0_Tweaked, PXC_CONTACT_NO_FACE_INDEX, PXC_CONTACT_NO_FACE_INDEX, contactBuffer, true, contactGenPositionShiftVec, contactGenPositionShift)) return true; } else { if(contactPolygonPolygonExt(HP1.mNbVerts, scaledVertices1, stackIndices1, world1, shapeSpacePlane1, RotT1, HP0.mNbVerts, scaledVertices0, stackIndices0, world0_Tweaked, shapeSpacePlane0, RotT0, worldNormal1, m1to0_Tweaked, m0to1_Tweaked, PXC_CONTACT_NO_FACE_INDEX, PXC_CONTACT_NO_FACE_INDEX, contactBuffer, false, contactGenPositionShiftVec, contactGenPositionShift)) return true; } #ifdef CONVEX_CONVEX_ROUGH_FIRST_PASS } #endif return false; }
37,890
C++
35.751697
302
0.725996
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCapsuleBox.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 "geomutils/PxContactBuffer.h" #include "GuIntersectionRayBox.h" #include "GuDistanceSegmentBox.h" #include "GuInternal.h" #include "GuContactMethodImpl.h" #include "GuBoxConversion.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Gu; /*namespace Gu { const PxU8* getBoxEdges(); }*/ ///////// /*#include "common/PxRenderOutput.h" #include "PxsContext.h" static void gVisualizeBox(const Box& box, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat33 rot(box.base.column0, box.base.column1, box.base.column2); PxMat44 m(rot, box.origin); DebugBox db(box.extent); PxRenderOutput& out = context.mRenderOutput; out << color << m; out << db; } static void gVisualizeLine(const PxVec3& a, const PxVec3& b, PxcNpThreadContext& context, PxU32 color=0xffffff) { PxMat44 m = PxMat44::identity(); RenderOutput& out = context.mRenderOutput; out << color << m << RenderOutput::LINES << a << b; }*/ ///////// static const PxReal fatBoxEdgeCoeff = 0.01f; static bool intersectEdgeEdgePreca(const PxVec3& p1, const PxVec3& p2, const PxVec3& v1, const PxPlane& plane, PxU32 i, PxU32 j, float coeff, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip) { // if colliding edge (p3,p4) does not cross plane return no collision // same as if p3 and p4 on same side of plane return 0 // // Derivation: // d3 = d(p3, P) = (p3 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // d4 = d(p4, P) = (p4 | plane.n) - plane.d; Reversed sign compared to Plane::Distance() because plane.d is negated. // if d3 and d4 have the same sign, they're on the same side of the plane => no collision // We test both sides at the same time by only testing Sign(d3 * d4). // ### put that in the Plane class // ### also check that code in the triangle class that might be similar const PxReal d3 = plane.distance(p3); PxReal temp = d3 * plane.distance(p4); if(temp>0.0f) return false; // if colliding edge (p3,p4) and plane are parallel return no collision PxVec3 v2 = p4 - p3; temp = plane.n.dot(v2); if(temp==0.0f) return false; // ### epsilon would be better // compute intersection point of plane and colliding edge (p3,p4) ip = p3-v2*(d3/temp); // compute distance of intersection from line (ip, -dir) to line (p1,p2) dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i]))*coeff; if(dist<0.0f) return false; // compute intersection point on edge (p1,p2) line ip -= dist*dir; // check if intersection point (ip) is between edge (p1,p2) vertices temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z); if(temp<0.0f) return true; // collision found return false; // no collision } static bool GuTestAxis(const PxVec3& axis, const Segment& segment, PxReal radius, const Box& box, PxReal& depth) { // Project capsule PxReal min0 = segment.p0.dot(axis); PxReal max0 = segment.p1.dot(axis); if(min0>max0) PxSwap(min0, max0); min0 -= radius; max0 += radius; // Project box PxReal Min1, Max1; { const PxReal BoxCen = box.center.dot(axis); const PxReal BoxExt = PxAbs(box.rot.column0.dot(axis)) * box.extents.x + PxAbs(box.rot.column1.dot(axis)) * box.extents.y + PxAbs(box.rot.column2.dot(axis)) * box.extents.z; Min1 = BoxCen - BoxExt; Max1 = BoxCen + BoxExt; } // Test projections if(max0<Min1 || Max1<min0) return false; const PxReal d0 = max0 - Min1; PX_ASSERT(d0>=0.0f); const PxReal d1 = Max1 - min0; PX_ASSERT(d1>=0.0f); depth = physx::intrinsics::selectMin(d0, d1); return true; } static bool GuCapsuleOBBOverlap3(const Segment& segment, PxReal radius, const Box& box, PxReal* t=NULL, PxVec3* pp=NULL) { PxVec3 Sep(PxReal(0)); PxReal PenDepth = PX_MAX_REAL; // Test normals for(PxU32 i=0;i<3;i++) { PxReal d; if(!GuTestAxis(box.rot[i], segment, radius, box, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = box.rot[i]; } } // Test edges PxVec3 CapsuleAxis(segment.p1 - segment.p0); CapsuleAxis = CapsuleAxis.getNormalized(); for(PxU32 i=0;i<3;i++) { PxVec3 Cross = CapsuleAxis.cross(box.rot[i]); if(!isAlmostZero(Cross)) { Cross = Cross.getNormalized(); PxReal d; if(!GuTestAxis(Cross, segment, radius, box, d)) return false; if(d<PenDepth) { PenDepth = d; Sep = Cross; } } } const PxVec3 Witness = segment.computeCenter() - box.center; if(Sep.dot(Witness) < 0.0f) Sep = -Sep; if(t) *t = PenDepth; if(pp) *pp = Sep; return true; } static void GuGenerateVFContacts( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const Box& worldBox, // const PxVec3& normal, const PxReal contactDistance) { const PxVec3 Max = worldBox.extents; const PxVec3 Min = -worldBox.extents; const PxVec3 tmp2 = - worldBox.rot.transformTranspose(normal); const PxVec3* PX_RESTRICT Ptr = &segment.p0; for(PxU32 i=0;i<2;i++) { const PxVec3& Pos = Ptr[i]; const PxVec3 tmp = worldBox.rot.transformTranspose(Pos - worldBox.center); PxReal tnear, tfar; int Res = intersectRayAABB(Min, Max, tmp, tmp2, tnear, tfar); if(Res!=-1 && tnear < radius + contactDistance) { contactBuffer.contact(Pos - tnear * normal, normal, tnear - radius); } } } // PT: this looks similar to PxcGenerateEEContacts2 but it is mandatory to properly handle thin capsules. static void GuGenerateEEContacts( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const Box& worldBox, // const PxVec3& normal) { const PxU8* PX_RESTRICT Indices = getBoxEdges(); PxVec3 Pts[8]; worldBox.computeBoxPoints(Pts); PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = v1.cross(normal); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[ii]*normal[jj]-v1[jj]*normal[ii]); for(PxU32 i=0;i<12;i++) { // PxVec3 p1 = Pts[*Indices++]; // PxVec3 p2 = Pts[*Indices++]; // makeFatEdge(p1, p2, fatBoxEdgeCoeff); // PT: TODO: make fat segment instead const PxVec3& p1 = Pts[*Indices++]; const PxVec3& p2 = Pts[*Indices++]; // PT: keep original code in case something goes wrong // PxReal dist; // PxVec3 ip; // if(intersectEdgeEdge(p1, p2, -normal, segment.p0, segment.p1, dist, ip)) // contactBuffer.contact(ip, normal, - (radius + dist)); PxReal dist; PxVec3 ip; if(intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip)) // if(intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, normal, p1, p2, dist, ip)) { contactBuffer.contact(ip-normal*dist, normal, - (radius + dist)); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } } } static void GuGenerateEEContacts2( PxContactBuffer& contactBuffer, // const Segment& segment, const PxReal radius, // const Box& worldBox, // const PxVec3& normal, const PxReal contactDistance) { const PxU8* PX_RESTRICT Indices = getBoxEdges(); PxVec3 Pts[8]; worldBox.computeBoxPoints(Pts); PxVec3 s0 = segment.p0; PxVec3 s1 = segment.p1; makeFatEdge(s0, s1, fatBoxEdgeCoeff); // PT: precomputed part of edge-edge intersection test // const PxVec3 v1 = segment.p1 - segment.p0; const PxVec3 v1 = s1 - s0; PxPlane plane; plane.n = -(v1.cross(normal)); // plane.d = -(plane.normal|segment.p0); plane.d = -(plane.n.dot(s0)); PxU32 ii,jj; closestAxis(plane.n, ii, jj); const float coeff = 1.0f /(v1[jj]*normal[ii]-v1[ii]*normal[jj]); for(PxU32 i=0;i<12;i++) { // PxVec3 p1 = Pts[*Indices++]; // PxVec3 p2 = Pts[*Indices++]; // makeFatEdge(p1, p2, fatBoxEdgeCoeff); // PT: TODO: make fat segment instead const PxVec3& p1 = Pts[*Indices++]; const PxVec3& p2 = Pts[*Indices++]; // PT: keep original code in case something goes wrong // PxReal dist; // PxVec3 ip; // bool contact = intersectEdgeEdge(p1, p2, normal, segment.p0, segment.p1, dist, ip); // if(contact && dist < radius + contactDistance) // contactBuffer.contact(ip, normal, dist - radius); PxReal dist; PxVec3 ip; // bool contact = intersectEdgeEdgePreca(segment.p0, segment.p1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip); bool contact = intersectEdgeEdgePreca(s0, s1, v1, plane, ii, jj, coeff, -normal, p1, p2, dist, ip); if(contact && dist < radius + contactDistance) { contactBuffer.contact(ip-normal*dist, normal, dist - radius); // if(contactBuffer.count==2) // PT: we only need 2 contacts to be stable // return; } } } bool Gu::contactCapsuleBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); // Get actual shape data const PxCapsuleGeometry& shapeCapsule = checkedCast<PxCapsuleGeometry>(shape0); const PxBoxGeometry& shapeBox = checkedCast<PxBoxGeometry>(shape1); // PT: TODO: move computations to local space // Capsule data Segment worldSegment; getCapsuleSegment(transform0, shapeCapsule, worldSegment); const PxReal inflatedRadius = shapeCapsule.radius + params.mContactDistance; // Box data Box worldBox; buildFrom(worldBox, transform1.p, shapeBox.halfExtents, transform1.q); // Collision detection PxReal t; PxVec3 onBox; const PxReal squareDist = distanceSegmentBoxSquared(worldSegment.p0, worldSegment.p1, worldBox.center, worldBox.extents, worldBox.rot, &t, &onBox); if(squareDist >= inflatedRadius*inflatedRadius) return false; PX_ASSERT(contactBuffer.count==0); if(squareDist != 0.0f) { // PT: the capsule segment doesn't intersect the box => distance-based version const PxVec3 onSegment = worldSegment.getPointAt(t); onBox = worldBox.center + worldBox.rot.transform(onBox); PxVec3 normal = onSegment - onBox; PxReal normalLen = normal.magnitude(); if(normalLen > 0.0f) { normal *= 1.0f/normalLen; // PT: generate VF contacts for segment's vertices vs box GuGenerateVFContacts(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, normal, params.mContactDistance); // PT: early exit if we already have 2 stable contacts if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts GuGenerateEEContacts2(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, normal, params.mContactDistance); // PT: run VF case for box-vertex-vs-capsule only if we don't have any contact yet if(!contactBuffer.count) contactBuffer.contact(onBox, normal, sqrtf(squareDist) - shapeCapsule.radius); } else { // On linux we encountered the following: // For a case where a segment endpoint lies on the surface of a box, the squared distance between segment and box was tiny but still larger than 0. // However, the computation of the normal length was exactly 0. In that case we should have switched to the penetration based version so we do it now // instead. goto PenetrationBasedCode; } } else { PenetrationBasedCode: // PT: the capsule segment intersects the box => penetration-based version // PT: compute penetration vector (MTD) PxVec3 sepAxis; PxReal depth; if(!GuCapsuleOBBOverlap3(worldSegment, shapeCapsule.radius, worldBox, &depth, &sepAxis)) return false; // PT: generate VF contacts for segment's vertices vs box GuGenerateVFContacts(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, sepAxis, params.mContactDistance); // PT: early exit if we already have 2 stable contacts if(contactBuffer.count==2) return true; // PT: else generate slower EE contacts GuGenerateEEContacts(contactBuffer, worldSegment, shapeCapsule.radius, worldBox, sepAxis); if(!contactBuffer.count) { contactBuffer.contact(worldSegment.computeCenter(), sepAxis, -(shapeCapsule.radius + depth)); return true; } } return true; }
13,856
C++
30.27991
222
0.694284
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactBoxBox.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 "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" #include "CmMatrix34.h" #include "foundation/PxUtilities.h" using namespace physx; using namespace Gu; using namespace Cm; #define MAX_NB_CTCS 8 + 12*5 + 6*4 #define ABS_GREATER(x, y) (PxAbs(x) > (y)) #define ABS_SMALLER_EQUAL(x, y) (PxAbs(x) <= (y)) //#define AIR(x) ((PxU32&)(x)&SIGN_BITMASK) //#define ABS_GREATER(x, y) (AIR(x) > IR(y)) //#define ABS_SMALLER_EQUAL(x, y) (AIR(x) <= IR(y)) #if PX_X86 && !PX_OSX // Some float optimizations ported over from novodex. //returns non zero if the value is negative. #define PXC_IS_NEGATIVE(x) (((PxU32&)(x)) & 0x80000000) #else //On most platforms using the integer rep is worse(produces LHSs) since the CPU has more registers. //returns non zero if the value is negative. #define PXC_IS_NEGATIVE(x) ((x) < 0.0f) #endif enum { AXIS_A0, AXIS_A1, AXIS_A2, AXIS_B0, AXIS_B1, AXIS_B2 }; struct VertexInfo { PxVec3 pos; bool penetrate; bool area; }; /*static PxI32 doBoxBoxContactGeneration(PxVec3 ctcPts[MAX_NB_CTCS], PxReal depths[MAX_NB_CTCS], PxVec3* ctcNrm, const PxVec3& extents0, const PxVec3& extents1, PxU32& collisionData, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance);*/ static PxI32 doBoxBoxContactGeneration(PxContactBuffer& contactBuffer, const PxVec3& extents0, const PxVec3& extents1, PxU32& collisionData, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance); bool Gu::contactBoxBox(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); // Get actual shape data const PxBoxGeometry& shapeBox0 = checkedCast<PxBoxGeometry>(shape0); const PxBoxGeometry& shapeBox1 = checkedCast<PxBoxGeometry>(shape1); PxU32 pd = PxU32(cache.mPairData); PxI32 Nb = doBoxBoxContactGeneration(contactBuffer, shapeBox0.halfExtents, shapeBox1.halfExtents, pd, Matrix34FromTransform(transform0), Matrix34FromTransform(transform1), params.mContactDistance); cache.mPairData = PxTo8(pd); if(!Nb) { cache.mPairData = 0; // Mark as separated for temporal coherence return false; // WARNING: the contact stream code below used to output stuff even for 0 contacts (!). Now we just return here. } return true; } // face => 4 vertices of a face of the cube (i.e. a quad) static PX_FORCE_INLINE PxReal IsInYZ(const PxReal y, const PxReal z, const VertexInfo** PX_RESTRICT face) { // Warning, indices have been remapped. We're now actually like this: // // 3+------+2 // | | | // | *--| // | (y,z)| // 0+------+1 PxReal PreviousY = face[3]->pos.y; PxReal PreviousZ = face[3]->pos.z; // Loop through quad vertices for(PxI32 i=0; i<4; i++) { const PxReal CurrentY = face[i]->pos.y; const PxReal CurrentZ = face[i]->pos.z; // |CurrentY - PreviousY y - PreviousY| // |CurrentZ - PreviousZ z - PreviousZ| // => similar to backface culling, check each one of the 4 triangles are consistent, in which case // the point is within the parallelogram. if((CurrentY - PreviousY)*(z - PreviousZ) - (CurrentZ - PreviousZ)*(y - PreviousY) >= 0.0f) return -1.0f; PreviousY = CurrentY; PreviousZ = CurrentZ; } PxReal x = face[0]->pos.x; { const PxReal ay = y - face[0]->pos.y; const PxReal az = z - face[0]->pos.z; PxVec3 b = face[1]->pos - face[0]->pos; // ### could be precomputed ? x += b.x * (ay*b.y + az*b.z) / b.magnitudeSquared(); // ### could be precomputed ? b = face[3]->pos - face[0]->pos; // ### could be precomputed ? x += b.x * (ay*b.y + az*b.z) / b.magnitudeSquared(); // ### could be precomputed ? } return x; } // Test with respect to the quad defined by (0,-y1,-z1) and (0,y1,z1) // +------+ y1 y // | | | // | * | | // | | | // +------+ -y1 *-----z static PxI32 generateContacts(//PxVec3 ctcPts[], PxReal depths[], PxContactBuffer& contactBuffer, const PxVec3& contactNormal, PxReal y1, PxReal z1, const PxVec3& box2, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance) { // PxI32 NbContacts=0; contactBuffer.reset(); y1 += contactDistance; z1 += contactDistance; const PxMat34 trans1to0 = transform0.getInverseRT() * transform1; VertexInfo vtx[8]; // The 8 cube vertices // PxI32 i; // 6+------+7 // /| /| // / | / | // / 4+---/--+5 // 2+------+3 / y z // | / | / | / // |/ |/ |/ // 0+------+1 *---x { const PxVec3 ex = trans1to0.m.column0 * box2.x; const PxVec3 ey = trans1to0.m.column1 * box2.y; const PxVec3 ez = trans1to0.m.column2 * box2.z; /* vtx[0].pos = mat.pos - ex - ey - ez; vtx[1].pos = mat.pos + ex - ey - ez; vtx[2].pos = mat.pos - ex + ey - ez; vtx[3].pos = mat.pos + ex + ey - ez; vtx[4].pos = mat.pos - ex - ey + ez; vtx[5].pos = mat.pos + ex - ey + ez; vtx[6].pos = mat.pos - ex + ey + ez; vtx[7].pos = mat.pos + ex + ey + ez; */ // 12 vector ops = 12*3 = 36 FPU ops vtx[0].pos = vtx[2].pos = vtx[4].pos = vtx[6].pos = trans1to0.p - ex; vtx[1].pos = vtx[3].pos = vtx[5].pos = vtx[7].pos = trans1to0.p + ex; PxVec3 e = ey+ez; vtx[0].pos -= e; vtx[1].pos -= e; vtx[6].pos += e; vtx[7].pos += e; e = ey-ez; vtx[2].pos += e; vtx[3].pos += e; vtx[4].pos -= e; vtx[5].pos -= e; } // Create vertex info for 8 vertices for(PxU32 i=0; i<8; i++) { // Vertex suivant VertexInfo& p = vtx[i]; // test the point with respect to the x = 0 plane // if(p.pos.x < 0) if(p.pos.x < -contactDistance) //if(PXC_IS_NEGATIVE(p.pos.x)) { p.area = false; p.penetrate = false; continue; } { // we penetrated the quad plane p.penetrate = true; // test to see if we are in the quad // PxAbs => thus we test Y with respect to -Y1 and +Y1 (same for Z) // if(PxAbs(p->pos.y) <= y1 && PxAbs(p->pos.z) <= z1) if(ABS_SMALLER_EQUAL(p.pos.y, y1) && ABS_SMALLER_EQUAL(p.pos.z, z1)) { // the point is inside the quad p.area=true; // Since we are testing with respect to x = 0, the penetration is directly the x coordinate. // depths[NbContacts] = p.pos.x; // We take the vertex as the impact point // ctcPts[NbContacts++] = p.pos; contactBuffer.contact(p.pos, contactNormal, -p.pos.x); } else { p.area=false; } } } // Teste 12 edges on the quad static const PxI32 indices[]={ 0,1, 1,3, 3,2, 2,0, 4,5, 5,7, 7,6, 6,4, 0,4, 1,5, 2,6, 3,7, }; const PxI32* runningLine = indices; const PxI32* endLine = runningLine+24; while(runningLine!=endLine) { // The two vertices of the current edge const VertexInfo* p1 = &vtx[*runningLine++]; const VertexInfo* p2 = &vtx[*runningLine++]; // Penetrate|Area|Penetrate|Area => 16 cases // We only take the edges that at least penetrated the quad's plane into account. if(p1->penetrate || p2->penetrate) // if(p1->penetrate + p2->penetrate) // One branch only { // If at least one of the two vertices is not in the quad... if(!p1->area || !p2->area) // if(!p1->area + !p2->area) // One branch only { // Test y if(p1->pos.y > p2->pos.y) { const VertexInfo* tmp=p1; p1=p2; p2=tmp; } // Impact on the +Y1 edge of the quad if(p1->pos.y < +y1 && p2->pos.y >= +y1) // => a point under Y1, the other above { // Case 1 PxReal a = (+y1 - p1->pos.y)/(p2->pos.y - p1->pos.y); PxReal z = p1->pos.z + (p2->pos.z - p1->pos.z)*a; if(PxAbs(z) <= z1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, y1, z); contactBuffer.contact(PxVec3(x, y1, z), contactNormal, -x); } } } // Impact on the edge -Y1 of the quad if(p1->pos.y < -y1 && p2->pos.y >= -y1) { // Case 2 PxReal a = (-y1 - p1->pos.y)/(p2->pos.y - p1->pos.y); PxReal z = p1->pos.z + (p2->pos.z - p1->pos.z)*a; if(PxAbs(z) <= z1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, -y1, z); contactBuffer.contact(PxVec3(x, -y1, z), contactNormal, -x); } } } // Test z if(p1->pos.z > p2->pos.z) { const VertexInfo* tmp=p1; p1=p2; p2=tmp; } // Impact on the edge +Z1 of the quad if(p1->pos.z < +z1 && p2->pos.z >= +z1) { // Case 3 PxReal a = (+z1 - p1->pos.z)/(p2->pos.z - p1->pos.z); PxReal y = p1->pos.y + (p2->pos.y - p1->pos.y)*a; if(PxAbs(y) <= y1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, y, z1); contactBuffer.contact(PxVec3(x, y, z1), contactNormal, -x); } } } // Impact on the edge -Z1 of the quad if(p1->pos.z < -z1 && p2->pos.z >= -z1) { // Case 4 PxReal a = (-z1 - p1->pos.z)/(p2->pos.z - p1->pos.z); PxReal y = p1->pos.y + (p2->pos.y - p1->pos.y)*a; if(PxAbs(y) <= y1) { PxReal x = p1->pos.x + (p2->pos.x - p1->pos.x)*a; if(x+contactDistance>=0.0f) { // depths[NbContacts] = x; // ctcPts[NbContacts++] = PxVec3(x, y, -z1); contactBuffer.contact(PxVec3(x, y, -z1), contactNormal, -x); } } } } // The case where one point penetrates the plane, and the other is not in the quad. if((!p1->penetrate && !p2->area) || (!p2->penetrate && !p1->area)) { // Case 5 PxReal a = (-p1->pos.x)/(p2->pos.x - p1->pos.x); PxReal y = p1->pos.y + (p2->pos.y - p1->pos.y)*a; if(PxAbs(y) <= y1) { PxReal z = p1->pos.z + (p2->pos.z - p1->pos.z)*a; if(PxAbs(z) <= z1) { // depths[NbContacts] = 0; // ctcPts[NbContacts++] = PxVec3(0, y, z); contactBuffer.contact(PxVec3(0, y, z), contactNormal, 0); } } } } } { // 6 quads => 6 faces of the cube static const PxI32 face[][4]={ {0,1,3,2}, {1,5,7,3}, {5,4,6,7}, {4,0,2,6}, {2,3,7,6}, {0,4,5,1} }; PxI32 addflg=0; for(PxU32 i=0; i<6 && addflg!=0x0f; i++) { const PxI32* p = face[i]; const VertexInfo* q[4]; if((q[0]=&vtx[p[0]])->penetrate && (q[1]=&vtx[p[1]])->penetrate && (q[2]=&vtx[p[2]])->penetrate && (q[3]=&vtx[p[3]])->penetrate) { if(!q[0]->area || !q[1]->area || !q[2]->area || !q[3]->area) { if(!(addflg&1)) { PxReal x = IsInYZ(-y1, -z1, q); if(x>=0.0f) { addflg|=1; contactBuffer.contact(PxVec3(x, -y1, -z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, -y1, -z1);*/ } } if(!(addflg&2)) { PxReal x = IsInYZ(+y1, -z1, q); if(x>=0.0f) { addflg|=2; contactBuffer.contact(PxVec3(x, +y1, -z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, +y1, -z1);*/ } } if(!(addflg&4)) { PxReal x = IsInYZ(-y1, +z1, q); if(x>=0.0f) { addflg|=4; contactBuffer.contact(PxVec3(x, -y1, +z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, -y1, +z1);*/ } } if(!(addflg&8)) { PxReal x = IsInYZ(+y1, +z1, q); if(x>=0.0f) { addflg|=8; contactBuffer.contact(PxVec3(x, +y1, +z1), contactNormal, -x); /*depths[NbContacts]=x; ctcPts[NbContacts++] = PxVec3(x, +y1, +z1);*/ } } } } } } // for(i=0; i<NbContacts; i++) for(PxU32 i=0; i<contactBuffer.count; i++) // ctcPts[i] = transform0.transform(ctcPts[i]); // local to world contactBuffer.contacts[i].point = transform0.transform(contactBuffer.contacts[i].point); // local to world //PX_ASSERT(NbContacts); //if this did not make contacts then something went wrong in theory, but even the old code without distances had this flaw! // return NbContacts; return PxI32(contactBuffer.count); } //static PxI32 doBoxBoxContactGeneration(PxVec3 ctcPts[MAX_NB_CTCS], PxReal depths[MAX_NB_CTCS], PxVec3* ctcNrm, static PxI32 doBoxBoxContactGeneration(PxContactBuffer& contactBuffer, const PxVec3& extents0, const PxVec3& extents1, PxU32& collisionData, const PxMat34& transform0, const PxMat34& transform1, PxReal contactDistance) { PxReal aafC[3][3]; // matrix C = A^T B, c_{ij} = Dot(A_i,B_j) PxReal aafAbsC[3][3]; // |c_{ij}| PxReal afAD[3]; // Dot(A_i,D) PxReal d1[6]; PxReal overlap[6]; PxVec3 kD = transform1.p - transform0.p; const PxVec3& axis00 = transform0.m.column0; const PxVec3& axis01 = transform0.m.column1; const PxVec3& axis02 = transform0.m.column2; const PxVec3& axis10 = transform1.m.column0; const PxVec3& axis11 = transform1.m.column1; const PxVec3& axis12 = transform1.m.column2; // Perform Class I tests aafC[0][0] = axis00.dot(axis10); aafC[0][1] = axis00.dot(axis11); aafC[0][2] = axis00.dot(axis12); afAD[0] = axis00.dot(kD); aafAbsC[0][0] = 1e-6f + PxAbs(aafC[0][0]); aafAbsC[0][1] = 1e-6f + PxAbs(aafC[0][1]); aafAbsC[0][2] = 1e-6f + PxAbs(aafC[0][2]); d1[AXIS_A0] = afAD[0]; PxReal d0 = extents0.x + extents1.x*aafAbsC[0][0] + extents1.y*aafAbsC[0][1] + extents1.z*aafAbsC[0][2]; overlap[AXIS_A0] = d0 - PxAbs(d1[AXIS_A0]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_A0])) return 0; aafC[1][0] = axis01.dot(axis10); aafC[1][1] = axis01.dot(axis11); aafC[1][2] = axis01.dot(axis12); afAD[1] = axis01.dot(kD); aafAbsC[1][0] = 1e-6f + PxAbs(aafC[1][0]); aafAbsC[1][1] = 1e-6f + PxAbs(aafC[1][1]); aafAbsC[1][2] = 1e-6f + PxAbs(aafC[1][2]); d1[AXIS_A1] = afAD[1]; d0 = extents0.y + extents1.x*aafAbsC[1][0] + extents1.y*aafAbsC[1][1] + extents1.z*aafAbsC[1][2]; overlap[AXIS_A1] = d0 - PxAbs(d1[AXIS_A1]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_A1])) return 0; aafC[2][0] = axis02.dot(axis10); aafC[2][1] = axis02.dot(axis11); aafC[2][2] = axis02.dot(axis12); afAD[2] = axis02.dot(kD); aafAbsC[2][0] = 1e-6f + PxAbs(aafC[2][0]); aafAbsC[2][1] = 1e-6f + PxAbs(aafC[2][1]); aafAbsC[2][2] = 1e-6f + PxAbs(aafC[2][2]); d1[AXIS_A2] = afAD[2]; d0 = extents0.z + extents1.x*aafAbsC[2][0] + extents1.y*aafAbsC[2][1] + extents1.z*aafAbsC[2][2]; overlap[AXIS_A2] = d0 - PxAbs(d1[AXIS_A2]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_A2])) return 0; // Perform Class II tests d1[AXIS_B0] = axis10.dot(kD); d0 = extents1.x + extents0.x*aafAbsC[0][0] + extents0.y*aafAbsC[1][0] + extents0.z*aafAbsC[2][0]; overlap[AXIS_B0] = d0 - PxAbs(d1[AXIS_B0]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_B0])) return 0; d1[AXIS_B1] = axis11.dot(kD); d0 = extents1.y + extents0.x*aafAbsC[0][1] + extents0.y*aafAbsC[1][1] + extents0.z*aafAbsC[2][1]; overlap[AXIS_B1] = d0 - PxAbs(d1[AXIS_B1]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_B1])) return 0; d1[AXIS_B2] = axis12.dot(kD); d0 = extents1.z + extents0.x*aafAbsC[0][2] + extents0.y*aafAbsC[1][2] + extents0.z*aafAbsC[2][2]; overlap[AXIS_B2] = d0 - PxAbs(d1[AXIS_B2]) + contactDistance; if(PXC_IS_NEGATIVE(overlap[AXIS_B2])) return 0; // Perform Class III tests - we don't need to store distances for those ones. // We only test those axes when objects are likely to be separated, i.e. when they where previously non-colliding. For stacks, we'll have // to do full contact generation anyway, and those tests are useless - so we skip them. This is similar to what I did in Opcode. if(!collisionData) // separated or first run { PxReal d = afAD[2]*aafC[1][0] - afAD[1]*aafC[2][0]; d0 = contactDistance + extents0.y*aafAbsC[2][0] + extents0.z*aafAbsC[1][0] + extents1.y*aafAbsC[0][2] + extents1.z*aafAbsC[0][1]; if(ABS_GREATER(d, d0)) return 0; d = afAD[2]*aafC[1][1] - afAD[1]*aafC[2][1]; d0 = contactDistance + extents0.y*aafAbsC[2][1] + extents0.z*aafAbsC[1][1] + extents1.x*aafAbsC[0][2] + extents1.z*aafAbsC[0][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[2]*aafC[1][2] - afAD[1]*aafC[2][2]; d0 = contactDistance + extents0.y*aafAbsC[2][2] + extents0.z*aafAbsC[1][2] + extents1.x*aafAbsC[0][1] + extents1.y*aafAbsC[0][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[0]*aafC[2][0] - afAD[2]*aafC[0][0]; d0 = contactDistance + extents0.x*aafAbsC[2][0] + extents0.z*aafAbsC[0][0] + extents1.y*aafAbsC[1][2] + extents1.z*aafAbsC[1][1]; if(ABS_GREATER(d, d0)) return 0; d = afAD[0]*aafC[2][1] - afAD[2]*aafC[0][1]; d0 = contactDistance + extents0.x*aafAbsC[2][1] + extents0.z*aafAbsC[0][1] + extents1.x*aafAbsC[1][2] + extents1.z*aafAbsC[1][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[0]*aafC[2][2] - afAD[2]*aafC[0][2]; d0 = contactDistance + extents0.x*aafAbsC[2][2] + extents0.z*aafAbsC[0][2] + extents1.x*aafAbsC[1][1] + extents1.y*aafAbsC[1][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[1]*aafC[0][0] - afAD[0]*aafC[1][0]; d0 = contactDistance + extents0.x*aafAbsC[1][0] + extents0.y*aafAbsC[0][0] + extents1.y*aafAbsC[2][2] + extents1.z*aafAbsC[2][1]; if(ABS_GREATER(d, d0)) return 0; d = afAD[1]*aafC[0][1] - afAD[0]*aafC[1][1]; d0 = contactDistance + extents0.x*aafAbsC[1][1] + extents0.y*aafAbsC[0][1] + extents1.x*aafAbsC[2][2] + extents1.z*aafAbsC[2][0]; if(ABS_GREATER(d, d0)) return 0; d = afAD[1]*aafC[0][2] - afAD[0]*aafC[1][2]; d0 = contactDistance + extents0.x*aafAbsC[1][2] + extents0.y*aafAbsC[0][2] + extents1.x*aafAbsC[2][1] + extents1.y*aafAbsC[2][0]; if(ABS_GREATER(d, d0)) return 0; } /* djs - tempUserData can be zero when it gets here - maybe if there was no previous axis? - which causes stack corruption, and thence a crash, in .NET PT: right! At first tempUserData wasn't ever supposed to be zero, but then I used that value to mark separation of boxes, and forgot to update the code below. Now I think the test is redundant with the one performed above, and the line could eventually be merged in the previous block. I'll do that later when removing all the #defines. */ // NB: the "16" here has nothing to do with MAX_NB_CTCS. Don't touch. if(collisionData) // if initialized & not previously separated overlap[collisionData-1] *= 0.999f; // Favorise previous axis .999 is too little. PxReal minimum = PX_MAX_REAL; PxI32 minIndex = 0; for(PxU32 i=AXIS_A0; i<6; i++) { PxReal d = overlap[i]; if(d>=0.0f && d<minimum) { minimum=d; minIndex=PxI32(i); } // >=0 !! otherwise bug at sep = 0 } collisionData = PxU32(minIndex + 1); // Leave "0" for separation #if PX_X86 const PxU32 sign = PXC_IS_NEGATIVE(d1[minIndex]); #else const PxU32 sign = PxU32(PXC_IS_NEGATIVE(d1[minIndex])); #endif PxMat34 trs; PxVec3 ctcNrm; switch(minIndex) { default: return 0; case AXIS_A0: // *ctcNrm = axis00; if(sign) { ctcNrm = axis00; trs.m = transform0.m; trs.p = transform0.p - extents0.x*axis00; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis00; trs.m.column0 = -axis00; trs.m.column1 = -axis01; trs.m.column2 = axis02; trs.p = transform0.p + extents0.x*axis00; } // return generateContacts(ctcPts, depths, extents0.y, extents0.z, extents1, trs, transform1, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents0.y, extents0.z, extents1, trs, transform1, contactDistance); case AXIS_A1: // *ctcNrm = axis01; trs.m.column2 = axis00; // Factored out if(sign) { ctcNrm = axis01; trs.m.column0 = axis01; trs.m.column1 = axis02; trs.p = transform0.p - extents0.y*axis01; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis01; trs.m.column0 = -axis01; trs.m.column1 = -axis02; trs.p = transform0.p + extents0.y*axis01; } // return generateContacts(ctcPts, depths, extents0.z, extents0.x, extents1, trs, transform1, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents0.z, extents0.x, extents1, trs, transform1, contactDistance); case AXIS_A2: // *ctcNrm = axis02; trs.m.column2 = axis01; // Factored out if(sign) { ctcNrm = axis02; trs.m.column0 = axis02; trs.m.column1 = axis00; trs.p = transform0.p - extents0.z*axis02; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis02; trs.m.column0 = -axis02; trs.m.column1 = -axis00; trs.p = transform0.p + extents0.z*axis02; } // return generateContacts(ctcPts, depths, extents0.x, extents0.y, extents1, trs, transform1, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents0.x, extents0.y, extents1, trs, transform1, contactDistance); case AXIS_B0: // *ctcNrm = axis10; if(sign) { ctcNrm = axis10; trs.m.column0 = -axis10; trs.m.column1 = -axis11; trs.m.column2 = axis12; trs.p = transform1.p + extents1.x*axis10; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis10; trs.m = transform1.m; trs.p = transform1.p - extents1.x*axis10; } // return generateContacts(ctcPts, depths, extents1.y, extents1.z, extents0, trs, transform0, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents1.y, extents1.z, extents0, trs, transform0, contactDistance); case AXIS_B1: // *ctcNrm = axis11; trs.m.column2 = axis10; // Factored out if(sign) { ctcNrm = axis11; trs.m.column0 = -axis11; trs.m.column1 = -axis12; trs.p = transform1.p + extents1.y*axis11; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis11; trs.m.column0 = axis11; trs.m.column1 = axis12; trs.m.column2 = axis10; trs.p = transform1.p - extents1.y*axis11; } // return generateContacts(ctcPts, depths, extents1.z, extents1.x, extents0, trs, transform0, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents1.z, extents1.x, extents0, trs, transform0, contactDistance); case AXIS_B2: // *ctcNrm = axis12; trs.m.column2 = axis11; // Factored out if(sign) { ctcNrm = axis12; trs.m.column0 = -axis12; trs.m.column1 = -axis10; trs.p = transform1.p + extents1.z*axis12; } else { // *ctcNrm = -*ctcNrm; ctcNrm = -axis12; trs.m.column0 = axis12; trs.m.column1 = axis10; trs.p = transform1.p - extents1.z*axis12; } // return generateContacts(ctcPts, depths, extents1.x, extents1.y, extents0, trs, transform0, contactDistance); return generateContacts(contactBuffer, ctcNrm, extents1.x, extents1.y, extents0, trs, transform0, contactDistance); } }
23,913
C++
33.359195
216
0.626145
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactCustomGeometry.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 "geomutils/PxContactBuffer.h" #include "GuContactMethodImpl.h" using namespace physx; bool Gu::contactCustomGeometryGeometry(GU_CONTACT_METHOD_ARGS) { PX_UNUSED(renderOutput); PX_UNUSED(cache); const PxCustomGeometry& customGeom = checkedCast<PxCustomGeometry>(shape0); const PxGeometry& otherGeom = shape1; customGeom.callbacks->generateContacts(customGeom, otherGeom, transform0, transform1, params.mContactDistance, params.mMeshContactMargin, params.mToleranceLength, contactBuffer); return true; } bool Gu::contactGeometryCustomGeometry(GU_CONTACT_METHOD_ARGS) { bool res = contactCustomGeometryGeometry(shape1, shape0, transform1, transform0, params, cache, contactBuffer, renderOutput); for (PxU32 i = 0; i < contactBuffer.count; ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; return res; }
2,572
C++
44.14035
126
0.769051
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/contact/GuContactPolygonPolygon.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 "geomutils/PxContactBuffer.h" #include "GuContactPolygonPolygon.h" #include "GuShapeConvex.h" #include "GuInternal.h" #include "foundation/PxAlloca.h" #include "foundation/PxFPU.h" using namespace physx; using namespace Gu; #define CONTACT_REDUCTION /* void gVisualizeLocalLine(const PxVec3& a, const PxVec3& b, const PxMat34& m, PxsContactManager& manager) //temp debug { RenderOutput out = manager.getContext()->getRenderOutput(); out << 0xffffff << m << RenderOutput::LINES << a << b; } */ #ifdef CONTACT_REDUCTION static PX_FORCE_INLINE PxReal dot2D(const PxVec3& v0, const PxVec3& v1) { return v0.x * v1.x + v0.y * v1.y; } static void ContactReductionAllIn( PxContactBuffer& contactBuffer, PxU32 nbExistingContacts, PxU32 numIn, const PxMat33& rotT, const PxVec3* PX_RESTRICT vertices, const PxU8* PX_RESTRICT indices) { // Number of contacts created by current call const PxU32 nbNewContacts = contactBuffer.count - nbExistingContacts; if(nbNewContacts<=4) return; // no reduction for less than 4 verts // We have 3 different numbers here: // - numVerts = number of vertices in the convex polygon we're dealing with // - numIn = number of those that were "inside" the other convex polygon (should be <= numVerts) // - contactBuffer.count = total number of contacts *from both polygons* (that's the catch here) // The fast path can only be chosen when the contact buffer contains all the verts from current polygon, // i.e. when contactBuffer.count == numIn == numVerts PxContactPoint* PX_RESTRICT ctcs = contactBuffer.contacts + nbExistingContacts; if(numIn == nbNewContacts) { // Codepath 1: all vertices generated a contact PxReal deepestSeparation = ctcs[0].separation; PxU32 deepestIndex = 0; for(PxU32 i=1; i<nbNewContacts; ++i) { if(deepestSeparation > ctcs[i].separation) { deepestSeparation = ctcs[i].separation; deepestIndex = i; } } PxU32 index = 0; const PxU32 step = (numIn<<16)>>2; // Fixed point math, don't use floats here please bool needsExtraPoint = true; for(PxU32 i=0;i<4;i++) { const PxU32 contactIndex = index>>16; ctcs[i] = ctcs[contactIndex]; if(contactIndex==deepestIndex) needsExtraPoint = false; index += step; } if(needsExtraPoint) { ctcs[4] = ctcs[deepestIndex]; contactBuffer.count = nbExistingContacts + 5; } else { contactBuffer.count = nbExistingContacts + 4; } /* PT: TODO: investigate why this one does not work PxU32 index = deepestIndex<<16; const PxU32 step = (numIn<<16)>>2; // Fixed point math, don't use floats here please for(PxU32 i=0;i<4;i++) { PxU32 contactIndex = index>>16; if(contactIndex>=numIn) contactIndex -= numIn; ctcs[i] = ctcs[contactIndex]; index += step; } contactBuffer.count = nbExistingContacts + 4;*/ } else { // Codepath 2: all vertices are "in" but only some of them generated a contact // WARNING: this path doesn't work when the buffer contains vertices from both polys. // TODO: precompute those axes const PxU32 nbAxes = 8; PxVec3 dirs[nbAxes]; float angle = 0.0f; const float angleStep = PxDegToRad(180.0f/float(nbAxes)); for(PxU32 i=0;i<nbAxes;i++) { dirs[i] = PxVec3(cosf(angle), sinf(angle), 0.0f); angle += angleStep; } float dpmin[nbAxes]; float dpmax[nbAxes]; for(PxU32 i=0;i<nbAxes;i++) { dpmin[i] = PX_MAX_F32; dpmax[i] = -PX_MAX_F32; } for(PxU32 i=0;i<nbNewContacts;i++) { const PxVec3& p = vertices[indices[i]]; // Transform to 2D const PxVec3 p2d = rotT.transform(p); for(PxU32 j=0;j<nbAxes;j++) { const float dp = dot2D(dirs[j], p2d); dpmin[j] = physx::intrinsics::selectMin(dpmin[j], dp); dpmax[j] = physx::intrinsics::selectMax(dpmax[j], dp); } } PxU32 bestAxis = 0; float maxVariance = dpmax[0] - dpmin[0]; for(PxU32 i=1;i<nbAxes;i++) { const float variance = dpmax[i] - dpmin[i]; if(variance>maxVariance) { maxVariance = variance; bestAxis = i; } } const PxVec3 u = dirs[bestAxis]; const PxVec3 v = PxVec3(-u.y, u.x, 0.0f); // PxVec3(1.0f, 0.0f, 0.0f) => PxVec3(0.0f, 1.0f, 0.0f) // PxVec3(0.0f, 1.0f, 0.0f) => PxVec3(-1.0f, 0.0f, 0.0f) // PxVec3(-1.0f, 1.0f, 0.0f) => PxVec3(-1.0f, -1.0f, 0.0f) // PxVec3(1.0f, 1.0f, 0.0f) => PxVec3(-1.0f, 1.0f, 0.0f) float dpminu = PX_MAX_F32; float dpmaxu = -PX_MAX_F32; float dpminv = PX_MAX_F32; float dpmaxv = -PX_MAX_F32; PxU32 indexMinU = 0; PxU32 indexMaxU = 0; PxU32 indexMinV = 0; PxU32 indexMaxV = 0; for(PxU32 i=0;i<nbNewContacts;i++) { const PxVec3& p = vertices[indices[i]]; // Transform to 2D const PxVec3 p2d = rotT.transform(p); const float dpu = dot2D(u, p2d); const float dpv = dot2D(v, p2d); if(dpu<dpminu) { dpminu=dpu; indexMinU = i; } if(dpu>dpmaxu) { dpmaxu=dpu; indexMaxU = i; } if(dpv<dpminv) { dpminv=dpv; indexMinV = i; } if(dpv>dpmaxv) { dpmaxv=dpv; indexMaxV = i; } } if(indexMaxU == indexMinU) indexMaxU = 0xffffffff; if(indexMinV == indexMinU || indexMinV == indexMaxU) indexMinV = 0xffffffff; if(indexMaxV == indexMinU || indexMaxV == indexMaxU || indexMaxV == indexMinV) indexMaxV = 0xffffffff; PxU32 newCount = 0; for(PxU32 i=0;i<nbNewContacts;i++) { if( i==indexMinU || i==indexMaxU || i==indexMinV || i==indexMaxV) { ctcs[newCount++] = ctcs[i]; } } contactBuffer.count = nbExistingContacts + newCount; } } #endif // PT: please leave that function in the same translation unit as the calling code /*static*/ PxMat33 Gu::findRotationMatrixFromZ(const PxVec3& to) { PxMat33 result; const PxReal e = to.z; const PxReal f = PxAbs(e); if(f <= 0.9999f) { // PT: please keep the normal case first for PS3 branch prediction // Normal case, to and from are not parallel or anti-parallel const PxVec3 v = cross001(to); const PxReal h = 1.0f/(1.0f + e); /* optimization by Gottfried Chen */ const PxReal hvx = h * v.x; const PxReal hvz = h * v.z; const PxReal hvxy = hvx * v.y; const PxReal hvxz = hvx * v.z; const PxReal hvyz = hvz * v.y; result(0,0) = e + hvx*v.x; result(0,1) = hvxy - v.z; result(0,2) = hvxz + v.y; result(1,0) = hvxy + v.z; result(1,1) = e + h*v.y*v.y; result(1,2) = hvyz - v.x; result(2,0) = hvxz - v.y; result(2,1) = hvyz + v.x; result(2,2) = e + hvz*v.z; } else { //Vectors almost parallel // PT: TODO: simplify code below PxVec3 from(0.0f, 0.0f, 1.0f); PxVec3 absFrom(0.0f, 0.0f, 1.0f); if(absFrom.x < absFrom.y) { if(absFrom.x < absFrom.z) absFrom = PxVec3(1.0f, 0.0f, 0.0f); else absFrom = PxVec3(0.0f, 0.0f, 1.0f); } else { if(absFrom.y < absFrom.z) absFrom = PxVec3(0.0f, 1.0f, 0.0f); else absFrom = PxVec3(0.0f, 0.0f, 1.0f); } PxVec3 u, v; u.x = absFrom.x - from.x; u.y = absFrom.y - from.y; u.z = absFrom.z - from.z; v.x = absFrom.x - to.x; v.y = absFrom.y - to.y; v.z = absFrom.z - to.z; const PxReal c1 = 2.0f / u.dot(u); const PxReal c2 = 2.0f / v.dot(v); const PxReal c3 = c1 * c2 * u.dot(v); for(unsigned int i = 0; i < 3; i++) { for(unsigned int j = 0; j < 3; j++) { result(i,j) = - c1*u[i]*u[j] - c2*v[i]*v[j] + c3*v[i]*u[j]; } result(i,i) += 1.0f; } } return result; } // PT: using this specialized version avoids doing an explicit transpose, which reduces LHS PX_FORCE_INLINE PxMat34 transformTranspose(const PxMat33& a, const PxMat34& b) { return PxMat34(a.transformTranspose(b.m.column0), a.transformTranspose(b.m.column1), a.transformTranspose(b.m.column2), a.transformTranspose(b.p)); } // Helper function to transform x/y coordinate of point. PX_FORCE_INLINE void transform2D(float& x, float& y, const PxVec3& src, const PxMat34& mat) { x = src.x * mat.m.column0.x + src.y * mat.m.column1.x + src.z * mat.m.column2.x + mat.p.x; y = src.x * mat.m.column0.y + src.y * mat.m.column1.y + src.z * mat.m.column2.y + mat.p.y; } // Helper function to transform x/y coordinate of point. Use transposed matrix PX_FORCE_INLINE void transform2DT(float& x, float& y, const PxVec3& src, const PxMat33& mat) { x = mat.column0.dot(src); y = mat.column1.dot(src); } // Helper function to transform z coordinate of point. PX_FORCE_INLINE PxReal transformZ(const PxVec3& src, const PxMat34& mat) { return src.x * mat.m.column0.z + src.y * mat.m.column1.z + src.z * mat.m.column2.z + mat.p.z; } static void transformVertices( float& minX, float& minY, float& maxX, float& maxY, float* PX_RESTRICT verts2D, PxU32 nb, const PxVec3* PX_RESTRICT vertices, const PxU8* PX_RESTRICT indices, const PxMat33& RotT) { // PT: using local variables is important to reduce LHS. float lminX = FLT_MAX; float lminY = FLT_MAX; float lmaxX = -FLT_MAX; float lmaxY = -FLT_MAX; // PT: project points, compute min & max at the same time for(PxU32 i=0; i<nb; i++) { float x,y; transform2DT(x, y, vertices[indices[i]], RotT); lminX = physx::intrinsics::selectMin(lminX, x); lminY = physx::intrinsics::selectMin(lminY, y); lmaxX = physx::intrinsics::selectMax(lmaxX, x); lmaxY = physx::intrinsics::selectMax(lmaxY, y); verts2D[i*2+0] = x; verts2D[i*2+1] = y; } // DE702 // Compute center of polygon const float cx = (lminX + lmaxX)*0.5f; const float cy = (lminY + lmaxY)*0.5f; // We'll scale the polygon by epsilon const float epsilon = 1.e-6f; // Adjust bounds to take care of scaling lminX -= epsilon; lminY -= epsilon; lmaxX += epsilon; lmaxY += epsilon; //~DE702 // PT: relocate polygon to positive quadrant for(PxU32 i=0; i<nb; i++) { const float x = verts2D[i*2+0]; const float y = verts2D[i*2+1]; // PT: original code suffering from DE702 (relocation) // verts2D[i*2+0] = x - lminX; // verts2D[i*2+1] = y - lminY; // PT: theoretically proper DE702 fix (relocation + scaling) const float dx = x - cx; const float dy = y - cy; // const float coeff = epsilon * physx::intrinsics::recipSqrt(dx*dx+dy*dy); // verts2D[i*2+0] = x - lminX + dx * coeff; // verts2D[i*2+1] = y - lminY + dy * coeff; // PT: approximate but faster DE702 fix. We multiply by epsilon so this is good enough. verts2D[i*2+0] = x - lminX + physx::intrinsics::fsel(dx, epsilon, -epsilon); verts2D[i*2+1] = y - lminY + physx::intrinsics::fsel(dy, epsilon, -epsilon); } lmaxX -= lminX; lmaxY -= lminY; minX = lminX; minY = lminY; maxX = lmaxX; maxY = lmaxY; } //! Dedicated triangle version PX_FORCE_INLINE bool pointInTriangle2D( float px, float pz, float p0x, float p0z, float e10x, float e10z, float e20x, float e20z) { const float a = e10x*e10x + e10z*e10z; const float b = e10x*e20x + e10z*e20z; const float c = e20x*e20x + e20z*e20z; const float ac_bb = (a*c)-(b*b); const float vpx = px - p0x; const float vpz = pz - p0z; const float d = vpx*e10x + vpz*e10z; const float e = vpx*e20x + vpz*e20z; const float x = (d*c) - (e*b); const float y = (e*a) - (d*b); const float z = x + y - ac_bb; // Same as: if(x>0.0f && y>0.0f && z<0.0f) return TRUE; // else return FALSE; // return (( IR(z) & ~(IR(x)|IR(y)) ) & SIGN_BITMASK) != 0; if(x>0.0f && y>0.0f && z<0.0f) return true; else return false; } enum OutCode { OUT_XP = (1<<0), OUT_XN = (1<<1), OUT_YP = (1<<2), OUT_YN = (1<<3) }; static //PX_FORCE_INLINE bool PointInConvexPolygon2D_OutCodes(const float* PX_RESTRICT pgon2D, PxU32 numVerts, const PxReal tx, const PxReal ty, const PxReal maxX, const PxReal maxY, PxU8& outCodes) { PxU32 out = 0; if(tx<0.0f) out |= OUT_XN; if(ty<0.0f) out |= OUT_YN; if(tx>maxX) out |= OUT_XP; if(ty>maxY) out |= OUT_YP; outCodes = PxU8(out); if(out) return false; if(numVerts==3) return pointInTriangle2D( tx, ty, pgon2D[0], pgon2D[1], pgon2D[2] - pgon2D[0], pgon2D[3] - pgon2D[1], pgon2D[4] - pgon2D[0], pgon2D[5] - pgon2D[1]); #define X 0 #define Y 1 const PxReal* PX_RESTRICT vtx0_ = pgon2D + (numVerts-1)*2; const PxReal* PX_RESTRICT vtx1_ = pgon2D; const int* PX_RESTRICT ivtx0 = reinterpret_cast<const int*>(vtx0_); const int* PX_RESTRICT ivtx1 = reinterpret_cast<const int*>(vtx1_); //const int itx = (int&)tx; //const int ity = (int&)ty; // const int ity = PX_SIR(ty); const int* tmp = reinterpret_cast<const int*>(&ty); const int ity = *tmp; // get test bit for above/below X axis int yflag0 = ivtx0[Y] >= ity; int InsideFlag = 0; while(numVerts--) { const int yflag1 = ivtx1[Y] >= ity; if(yflag0 != yflag1) { const PxReal* PX_RESTRICT vtx0 = reinterpret_cast<const PxReal*>(ivtx0); const PxReal* PX_RESTRICT vtx1 = reinterpret_cast<const PxReal*>(ivtx1); if( ((vtx1[Y]-ty) * (vtx0[X]-vtx1[X]) > (vtx1[X]-tx) * (vtx0[Y]-vtx1[Y])) == yflag1 ) { if(InsideFlag == 1) return false; InsideFlag++; } } yflag0 = yflag1; ivtx0 = ivtx1; ivtx1 += 2; } #undef X #undef Y return InsideFlag & 1; } // Helper function to detect contact between two edges PX_FORCE_INLINE bool EdgeEdgeContactSpecial(const PxVec3& v1, const PxPlane& plane, const PxVec3& p1, const PxVec3& p2, const PxVec3& dir, const PxVec3& p3, const PxVec3& p4, PxReal& dist, PxVec3& ip, unsigned int i, unsigned int j, float coeff) { const PxReal d3 = plane.distance(p3); PxReal temp = d3 * plane.distance(p4); if(temp > 0.0f) return false; // if colliding edge (p3,p4) and plane are parallel return no collision const PxVec3 v2 = (p4-p3); temp = plane.n.dot(v2); if(temp == 0.0f) // ### epsilon would be better return false; // compute intersection point of plane and colliding edge (p3,p4) ip = p3-v2*(d3/temp); // compute distance of intersection from line (ip, -dir) to line (p1,p2) dist = (v1[i]*(ip[j]-p1[j])-v1[j]*(ip[i]-p1[i])) * coeff; if(dist < 0.0f) return false; // compute intersection point on edge (p1,p2) line ip -= dist*dir; // check if intersection point (ip) is between edge (p1,p2) vertices temp = (p1.x-ip.x)*(p2.x-ip.x)+(p1.y-ip.y)*(p2.y-ip.y)+(p1.z-ip.z)*(p2.z-ip.z); if(temp<0.0f) return true; // collision found return false; //no collision } //This one can also handle 2 vertex 'polygons' (useful for capsule surface segments) and can shift the results before contact generation. bool Gu::contactPolygonPolygonExt( PxU32 numVerts0, const PxVec3* vertices0, const PxU8* indices0, //polygon 0 const PxMat34& world0, const PxPlane& localPlane0, //xform of polygon 0, plane of polygon const PxMat33& rotT0, // PxU32 numVerts1, const PxVec3* PX_RESTRICT vertices1, const PxU8* PX_RESTRICT indices1, //polygon 1 const PxMat34& world1, const PxPlane& localPlane1, //xform of polygon 1, plane of polygon const PxMat33& rotT1, // const PxVec3& worldSepAxis, //world normal of separating plane - this is the world space normal of polygon0!! const PxMat34& transform0to1, const PxMat34& transform1to0, //transforms between polygons PxU32 /*polyIndex0*/, PxU32 polyIndex1, //feature indices for contact callback PxContactBuffer& contactBuffer, bool flipNormal, const PxVec3& posShift, PxReal sepShift) // shape order, result shift { const PxVec3 n = flipNormal ? -worldSepAxis : worldSepAxis; PX_ASSERT(indices0 != NULL && indices1 != NULL); // - optimize "from to" computation // - do the raycast case && EE tests in same space as 2D case... // - project all edges at the same time ? PxU32 NumIn = 0; bool status = false; void* PX_RESTRICT stackMemory; { const PxU32 maxNumVert = PxMax(numVerts0, numVerts1); stackMemory = PxAlloca(maxNumVert * sizeof(PxVec3)); } const PxU32 size0 = numVerts0 * sizeof(bool); bool* PX_RESTRICT flags0 = reinterpret_cast<bool*>(PxAlloca(size0)); PxU8* PX_RESTRICT outCodes0 = reinterpret_cast<PxU8*>(PxAlloca(size0)); // PxMemZero(flags0, size0); // PxMemZero(outCodes0, size0); const PxU32 size1 = numVerts1 * sizeof(bool); bool* PX_RESTRICT flags1 = reinterpret_cast<bool*>(PxAlloca(size1)); PxU8* PX_RESTRICT outCodes1 = reinterpret_cast<PxU8*>(PxAlloca(size1)); // PxMemZero(flags1, size1); // PxMemZero(outCodes1, size1); #ifdef CONTACT_REDUCTION // We want to do contact reduction on newly created contacts, not on all the already existing ones... PxU32 nbExistingContacts = contactBuffer.count; PxU32 nbCurrentContacts=0; PxU8 indices[PxContactBuffer::MAX_CONTACTS]; #endif { //polygon 1 float* PX_RESTRICT verts2D = NULL; float minX=0, minY=0; float maxX=0, maxY=0; const PxVec3 localDir = -world1.rotateTranspose(worldSepAxis); //contactNormal in hull1 space //that's redundant, its equal to -localPlane1.d const PxMat34 t0to2D = transformTranspose(rotT1, transform0to1); //transform from hull0 to RotT PxReal dn = localDir.dot(localPlane1.n); //if the contactNormal == +-(normal of poly0) is NOT orthogonal to poly1 ...this is just to protect the division below. // PT: TODO: if "numVerts1>2" we may skip more if (numVerts1 > 2 //no need to test whether we're 'inside' ignore capsule segments and points // if(!(-1E-7 < dn && dn < 1E-7)) && dn >= 1E-7f) // PT: it should never be negative so this unique test is enough { dn = 1.0f / dn; const float ld1 = -localPlane1.d; // PT: unavoidable "int-to-float" LHS here, so we only want to read it once! // Lazy-transform vertices if(!verts2D) { verts2D = reinterpret_cast<float*>(stackMemory); //Project points transformVertices( minX, minY, maxX, maxY, verts2D, numVerts1, vertices1, indices1, rotT1); } for(PxU32 i=0; i < numVerts0; i++) //for all vertices of poly0 { const PxVec3& p = vertices0[indices0[i]]; const float p0_z = transformZ(p, t0to2D); //transform ith vertex of poly0 to RotT const PxVec3 pIn1 = transform0to1.transform(p); //transform vertex to hull1 space, in which we have the poly1 vertices. const PxReal dd = (p0_z - ld1) * dn; //(p0_z + localPlane1.d) is the depth of the vertex behind the triangle measured along the triangle's normal. //we convert this to being measured along the 'contact normal' using the division. // if(dd < 0.0f) //if the penetrating vertex will have a penetration along the contact normal: // PX_ASSERT(dd <= 0.0f); // PT: dn is always positive, so dd is always negative { float px, py; transform2DT(px, py, pIn1 - dd*localDir, rotT1); //project vertex into poly1 plane along CONTACT NORMAL - not the polygon's normal. const bool res = PointInConvexPolygon2D_OutCodes(verts2D, numVerts1, px-minX, py-minY, maxX, maxY, outCodes0[i]); flags0[i] = res; if(res) { NumIn++; if(p0_z < ld1) { status = true; // PT: keep this first to avoid an LHS when leaving the function PxContactPoint* PX_RESTRICT ctc = contactBuffer.contact(); if(ctc) { #ifdef CONTACT_REDUCTION indices[nbCurrentContacts++] = indices0[i]; #endif ctc->normal = n; ctc->point = world0.transform(p) + (flipNormal ? posShift : PxVec3(0.0f)); ctc->separation = dd + sepShift; ctc->internalFaceIndex1 = polyIndex1; } } } } } } else { PxMemZero(flags0, size0); PxMemZero(outCodes0, size0); } if(NumIn == numVerts0) { //All vertices0 are inside polygon 1 #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT0, vertices0, indices); #endif return status; } #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT0, vertices0, indices); #endif #ifdef CONTACT_REDUCTION nbExistingContacts = contactBuffer.count; nbCurrentContacts = 0; #endif NumIn = 0; verts2D = NULL; //Polygon 0 const PxMat34 t1to2D = transformTranspose(rotT0, transform1to0); if (numVerts0 > 2) //no need to test whether we're 'inside' ignore capsule segments and points { const float ld0 = -localPlane0.d; // PT: unavoidable "int-to-float" LHS here, so we only want to read it once! // Lazy-transform vertices if(!verts2D) { verts2D = reinterpret_cast<float*>(stackMemory); //Project vertices transformVertices( minX, minY, maxX, maxY, verts2D, numVerts0, vertices0, indices0, rotT0); } for(PxU32 i=0; i < numVerts1; i++) { const PxVec3& p = vertices1[indices1[i]]; float px, py; transform2D(px, py, p, t1to2D); const bool res = PointInConvexPolygon2D_OutCodes(verts2D, numVerts0, px-minX, py-minY, maxX, maxY, outCodes1[i]); flags1[i] = res; if(res) { NumIn++; const float pz = transformZ(p, t1to2D); if(pz < ld0) { status = true; // PT: keep this first to avoid an LHS when leaving the function // PT: in theory, with this contact point we should use "worldSepAxis" as a contact normal. // However we want to output the same normal for all contact points not to break friction // patches!!! In theory again, it should be exactly the same since the contact point at // time of impact is supposed to be the same on both bodies. In practice however, and with // a depth-based engine, this is not the case. So the contact point here is not exactly // right, but preserving the friction patch seems more important. PxContactPoint* PX_RESTRICT ctc = contactBuffer.contact(); if(ctc) { #ifdef CONTACT_REDUCTION indices[nbCurrentContacts++] = indices1[i]; #endif ctc->normal = n; ctc->point = world1.transform(p) + (flipNormal ? PxVec3(0.0f) : posShift); ctc->separation = (pz - ld0) + sepShift; ctc->internalFaceIndex1 = polyIndex1; } } } } if(NumIn == numVerts1) { //all vertices 1 are inside polygon 0 #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT1, vertices1, indices); #endif return status; } #ifdef CONTACT_REDUCTION ContactReductionAllIn(contactBuffer, nbExistingContacts, NumIn, rotT1, vertices1, indices); #endif } else { PxMemZero(flags1, size1); PxMemZero(outCodes1, size1); } } //Edge/edge case //Calculation done in space 0 PxVec3* PX_RESTRICT verts1in0 = reinterpret_cast<PxVec3*>(stackMemory); for(PxU32 i=0; i<numVerts1; i++) { verts1in0[i] = transform1to0.transform(vertices1[indices1[i]]); } if (numVerts0 >= 2 && numVerts1 >= 2)//useless if one of them is degenerate. for(PxU32 j=0; j<numVerts1; j++) { PxU32 j1 = j+1; if(j1 >= numVerts1) j1 = 0; // if(!(flags1[j] ^ flags1[j1])) // continue; if(flags1[j] && flags1[j1]) continue; if(outCodes1[j]&outCodes1[j1]) continue; const PxVec3& p0 = verts1in0[j]; const PxVec3& p1 = verts1in0[j1]; // gVisualizeLocalLine(vertices1[indices1[j]], vertices1[indices1[j1]], world1, callback.getManager()); const PxVec3 v1 = p1-p0; const PxVec3 planeNormal = v1.cross(localPlane0.n); const PxPlane plane(planeNormal, -(planeNormal.dot(p0))); // find largest 2D plane projection PxU32 _i, _j; closestAxis(planeNormal, _i, _j); const PxReal coeff = 1.0f / (v1[_i]*localPlane0.n[_j]-v1[_j]*localPlane0.n[_i]); for(PxU32 i=0; i<numVerts0; i++) { PxU32 i1 = i+1; if(i1 >= numVerts0) i1 = 0; // if(!(flags0[i] ^ flags0[i1])) // continue; if(flags0[i] && flags0[i1]) continue; if(outCodes0[i]&outCodes0[i1]) continue; const PxVec3& p0b = vertices0[indices0[i]]; const PxVec3& p1b = vertices0[indices0[i1]]; // gVisualizeLocalLine(p0b, p1b, world0, callback.getManager()); PxReal dist; PxVec3 p; if(EdgeEdgeContactSpecial(v1, plane, p0, p1, localPlane0.n, p0b, p1b, dist, p, _i, _j, coeff)) { status = true; // PT: keep this first to avoid an LHS when leaving the function /* p = world0.transform(p); //contacts are generated on the edges of polygon 1 //we only have to shift the position of polygon 1 if flipNormal is false, because //in this case convex 0 gets passed as polygon 1, and it is convex 0 that was shifted. if (!flipNormal) p += posShift; contactBuffer.contact(p, n, -dist + sepShift, polyIndex0, polyIndex1, convexID);*/ PxContactPoint* PX_RESTRICT ctc = contactBuffer.contact(); if(ctc) { ctc->normal = n; ctc->point = world0.transform(p) + (flipNormal ? PxVec3(0.0f) : posShift); ctc->separation = -dist + sepShift; ctc->internalFaceIndex1 = polyIndex1; } } } } return status; }
26,369
C++
29.591647
173
0.65888
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuQuantizer.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 "GuQuantizer.h" #include "foundation/PxVec3.h" #include "foundation/PxBounds3.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxAllocator.h" #include "foundation/PxArray.h" using namespace physx; using namespace Gu; PxU32 kmeans_cluster3d(const PxVec3* input, // an array of input 3d data points. PxU32 inputSize, // the number of input data points. PxU32 clumpCount, // the number of clumps you wish to product. PxVec3* outputClusters, // The output array of clumps 3d vectors, should be at least 'clumpCount' in size. PxU32* outputIndices, // A set of indices which remaps the input vertices to clumps; should be at least 'inputSize' float errorThreshold=0.01f, // The error threshold to converge towards before giving up. float collapseDistance=0.01f); // distance so small it is not worth bothering to create a new clump. template <class Vec,class Type > PxU32 kmeans_cluster(const Vec* input, PxU32 inputCount, PxU32 clumpCount, Vec* clusters, PxU32* outputIndices, Type threshold, // controls how long it works to converge towards a least errors solution. Type collapseDistance) // distance between clumps to consider them to be essentially equal. { PxU32 convergeCount = 64; // maximum number of iterations attempting to converge to a solution.. PxU32* counts = PX_ALLOCATE(PxU32, clumpCount, "PxU32"); Type error=0; if ( inputCount <= clumpCount ) // if the number of input points is less than our clumping size, just return the input points. { clumpCount = inputCount; for (PxU32 i=0; i<inputCount; i++) { if ( outputIndices ) { outputIndices[i] = i; } clusters[i] = input[i]; counts[i] = 1; } } else { PxVec3* centroids = PX_ALLOCATE(PxVec3, clumpCount, "PxVec3"); // Take a sampling of the input points as initial centroid estimates. for (PxU32 i=0; i<clumpCount; i++) { PxU32 index = (i*inputCount)/clumpCount; PX_ASSERT( index < inputCount ); clusters[i] = input[index]; } // Here is the main convergence loop Type old_error = FLT_MAX; // old and initial error estimates are max Type error = FLT_MAX; do { old_error = error; // preserve the old error // reset the counts and centroids to current cluster location for (PxU32 i=0; i<clumpCount; i++) { counts[i] = 0; centroids[i] = PxVec3(PxZero); } error = 0; // For each input data point, figure out which cluster it is closest too and add it to that cluster. for (PxU32 i=0; i<inputCount; i++) { Type min_distance = FLT_MAX; // find the nearest clump to this point. for (PxU32 j=0; j<clumpCount; j++) { const Type distance = (input[i] - clusters[j]).magnitudeSquared(); if ( distance < min_distance ) { min_distance = distance; outputIndices[i] = j; // save which clump this point indexes } } const PxU32 index = outputIndices[i]; // which clump was nearest to this point. centroids[index]+=input[i]; counts[index]++; // increment the counter indicating how many points are in this clump. error+=min_distance; // save the error accumulation } // Now, for each clump, compute the mean and store the result. for (PxU32 i=0; i<clumpCount; i++) { if ( counts[i] ) // if this clump got any points added to it... { const Type recip = 1.0f / Type(counts[i]); // compute the average (center of those points) centroids[i]*=recip; // compute the average center of the points in this clump. clusters[i] = centroids[i]; // store it as the new cluster. } } // decrement the convergence counter and bail if it is taking too long to converge to a solution. convergeCount--; if (convergeCount == 0 ) { break; } if ( error < threshold ) // early exit if our first guess is already good enough (if all input points are the same) break; } while ( PxAbs(error - old_error) > threshold ); // keep going until the error is reduced by this threshold amount. PX_FREE(centroids); } // ok..now we prune the clumps if necessary. // The rules are; first, if a clump has no 'counts' then we prune it as it's unused. // The second, is if the centroid of this clump is essentially the same (based on the distance tolerance) // as an existing clump, then it is pruned and all indices which used to point to it, now point to the one // it is closest too. PxU32 outCount = 0; // number of clumps output after pruning performed. Type d2 = collapseDistance*collapseDistance; // squared collapse distance. for (PxU32 i=0; i<clumpCount; i++) { if ( counts[i] == 0 ) // if no points ended up in this clump, eliminate it. continue; // see if this clump is too close to any already accepted clump. bool add = true; PxU32 remapIndex = outCount; // by default this clump will be remapped to its current index. for (PxU32 j=0; j<outCount; j++) { Type distance = (clusters[i] - clusters[j]).magnitudeSquared(); if ( distance < d2 ) { remapIndex = j; add = false; // we do not add this clump break; } } // If we have fewer output clumps than input clumps so far, then we need to remap the old indices to the new ones. if ( outputIndices ) { if ( outCount != i || !add ) // we need to remap indices! everything that was index 'i' now needs to be remapped to 'outCount' { for (PxU32 j=0; j<inputCount; j++) { if ( outputIndices[j] == i ) { outputIndices[j] = remapIndex; // } } } } if ( add ) { clusters[outCount] = clusters[i]; outCount++; } } PX_FREE(counts); clumpCount = outCount; return clumpCount; } PxU32 kmeans_cluster3d( const PxVec3* input, // an array of input 3d data points. PxU32 inputSize, // the number of input data points. PxU32 clumpCount, // the number of clumps you wish to produce PxVec3* outputClusters, // The output array of clumps 3d vectors, should be at least 'clumpCount' in size. PxU32* outputIndices, // A set of indices which remaps the input vertices to clumps; should be at least 'inputSize' float errorThreshold, // The error threshold to converge towards before giving up. float collapseDistance) // distance so small it is not worth bothering to create a new clump. { return kmeans_cluster< PxVec3, float >(input, inputSize, clumpCount, outputClusters, outputIndices, errorThreshold, collapseDistance); } class QuantizerImpl : public Quantizer, public PxUserAllocated { public: QuantizerImpl(void) { mScale = PxVec3(1.0f, 1.0f, 1.0f); mCenter = PxVec3(0.0f, 0.0f, 0.0f); } // Use the k-means quantizer, similar results, but much slower. virtual const PxVec3* kmeansQuantize3D(PxU32 vcount, const PxVec3* vertices, PxU32 stride, bool denormalizeResults, PxU32 maxVertices, PxU32& outVertsCount) { const PxVec3* ret = NULL; outVertsCount = 0; mNormalizedInput.clear(); mQuantizedOutput.clear(); if ( vcount > 0 ) { normalizeInput(vcount,vertices, stride); PxVec3* quantizedOutput = PX_ALLOCATE(PxVec3, vcount, "PxVec3"); PxU32* quantizedIndices = PX_ALLOCATE(PxU32, vcount, "PxU32"); outVertsCount = kmeans_cluster3d(&mNormalizedInput[0], vcount, maxVertices, quantizedOutput, quantizedIndices, 0.01f, 0.0001f ); if ( outVertsCount > 0 ) { if ( denormalizeResults ) { for (PxU32 i=0; i<outVertsCount; i++) { PxVec3 v( quantizedOutput[i] ); v = v.multiply(mScale) + mCenter; mQuantizedOutput.pushBack(v); } } else { for (PxU32 i=0; i<outVertsCount; i++) { const PxVec3& v( quantizedOutput[i] ); mQuantizedOutput.pushBack(v); } } ret = &mQuantizedOutput[0]; } PX_FREE(quantizedOutput); PX_FREE(quantizedIndices); } return ret; } virtual void release(void) { PX_DELETE_THIS; } virtual const PxVec3& getDenormalizeScale(void) const { return mScale; } virtual const PxVec3& getDenormalizeCenter(void) const { return mCenter; } private: void normalizeInput(PxU32 vcount, const PxVec3* vertices, PxU32 stride) { const char* vtx = reinterpret_cast<const char *> (vertices); mNormalizedInput.clear(); mQuantizedOutput.clear(); PxBounds3 bounds; bounds.setEmpty(); for (PxU32 i=0; i<vcount; i++) { const PxVec3& v = *reinterpret_cast<const PxVec3 *> (vtx); vtx += stride; bounds.include(v); } mCenter = bounds.getCenter(); PxVec3 dim = bounds.getDimensions(); dim *= 1.001f; mScale = dim*0.5f; for (PxU32 i = 0; i < 3; i++) { if(dim[i] == 0) mScale[i] = 1.0f; } PxVec3 recip; recip.x = 1.0f / mScale.x; recip.y = 1.0f / mScale.y; recip.z = 1.0f / mScale.z; vtx = reinterpret_cast<const char *> (vertices); for (PxU32 i=0; i<vcount; i++) { PxVec3 v = *reinterpret_cast<const PxVec3 *> (vtx); vtx += stride; v = (v - mCenter).multiply(recip); mNormalizedInput.pushBack(v); } } virtual ~QuantizerImpl() { } private: PxVec3 mScale; PxVec3 mCenter; PxArray<PxVec3> mNormalizedInput; PxArray<PxVec3> mQuantizedOutput; }; Quantizer* physx::Gu::createQuantizer() { return PX_NEW(QuantizerImpl); }
10,947
C++
31.876877
135
0.6811
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuVertexReducer.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 "GuVertexReducer.h" #include "foundation/PxAllocator.h" #include "CmRadixSort.h" using namespace physx; using namespace Gu; using namespace Cm; // PT: code archeology: this initially came from ICE (IceVertexCloud.h/cpp). Consider dropping it. ReducedVertexCloud::ReducedVertexCloud(const PxVec3* verts, PxU32 nb_verts) : mNbRVerts(0), mRVerts(NULL), mXRef(NULL) { mVerts = verts; mNbVerts = nb_verts; } ReducedVertexCloud::~ReducedVertexCloud() { clean(); } ReducedVertexCloud& ReducedVertexCloud::clean() { PX_FREE(mXRef); PX_FREE(mRVerts); return *this; } /** * Reduction method. Use this to create a minimal vertex cloud. * \param rc [out] result structure * \return true if success * \warning This is not about welding nearby vertices, here we look for real redundant ones. */ bool ReducedVertexCloud::reduce(REDUCEDCLOUD* rc) { clean(); mXRef = PX_ALLOCATE(PxU32, mNbVerts, "mXRef"); float* f = PX_ALLOCATE(float, mNbVerts, "tmp"); for(PxU32 i=0;i<mNbVerts;i++) f[i] = mVerts[i].x; RadixSortBuffered Radix; Radix.Sort(reinterpret_cast<const PxU32*>(f), mNbVerts, RADIX_UNSIGNED); for(PxU32 i=0;i<mNbVerts;i++) f[i] = mVerts[i].y; Radix.Sort(reinterpret_cast<const PxU32*>(f), mNbVerts, RADIX_UNSIGNED); for(PxU32 i=0;i<mNbVerts;i++) f[i] = mVerts[i].z; const PxU32* Sorted = Radix.Sort(reinterpret_cast<const PxU32*>(f), mNbVerts, RADIX_UNSIGNED).GetRanks(); PX_FREE(f); mNbRVerts = 0; const PxU32 Junk[] = {PX_INVALID_U32, PX_INVALID_U32, PX_INVALID_U32}; const PxU32* Previous = Junk; mRVerts = PX_ALLOCATE(PxVec3, mNbVerts, "PxVec3"); PxU32 Nb = mNbVerts; while(Nb--) { const PxU32 Vertex = *Sorted++; // Vertex number const PxU32* current = reinterpret_cast<const PxU32*>(&mVerts[Vertex]); if(current[0]!=Previous[0] || current[1]!=Previous[1] || current[2]!=Previous[2]) mRVerts[mNbRVerts++] = mVerts[Vertex]; Previous = current; mXRef[Vertex] = mNbRVerts-1; } if(rc) { rc->CrossRef = mXRef; rc->NbRVerts = mNbRVerts; rc->RVerts = mRVerts; } return true; }
3,751
C++
32.20354
118
0.728339
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuBarycentricCoordinates.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 "GuBarycentricCoordinates.h" using namespace physx; using namespace aos; void Gu::barycentricCoordinates(const Vec3VArg p, const Vec3VArg a, const Vec3VArg b, FloatV& v) { const Vec3V v0 = V3Sub(a, p); const Vec3V v1 = V3Sub(b, p); const Vec3V d = V3Sub(v1, v0); const FloatV denominator = V3Dot(d, d); const FloatV numerator = V3Dot(V3Neg(v0), d); const FloatV zero = FZero(); const FloatV denom = FSel(FIsGrtr(denominator, zero), FRecip(denominator), zero); v = FMul(numerator, denom); } void Gu::barycentricCoordinates(const aos::Vec3VArg p, const aos::Vec3VArg a, const aos::Vec3VArg b, const aos::Vec3VArg c, aos::FloatV& v, aos::FloatV& w) { const Vec3V ab = V3Sub(b, a); const Vec3V ac = V3Sub(c, a); const Vec3V n = V3Cross(ab, ac); const VecCrossV crossA = V3PrepareCross(V3Sub(a, p)); const VecCrossV crossB = V3PrepareCross(V3Sub(b, p)); const VecCrossV crossC = V3PrepareCross(V3Sub(c, p)); const Vec3V bCrossC = V3Cross(crossB, crossC); const Vec3V cCrossA = V3Cross(crossC, crossA); const Vec3V aCrossB = V3Cross(crossA, crossB); const FloatV va = V3Dot(n, bCrossC);//edge region of BC, signed area rbc, u = S(rbc)/S(abc) for a const FloatV vb = V3Dot(n, cCrossA);//edge region of AC, signed area rac, v = S(rca)/S(abc) for b const FloatV vc = V3Dot(n, aCrossB);//edge region of AB, signed area rab, w = S(rab)/S(abc) for c const FloatV totalArea =FAdd(va, FAdd(vb, vc)); const FloatV zero = FZero(); const FloatV denom = FSel(FIsEq(totalArea, zero), zero, FRecip(totalArea)); v = FMul(vb, denom); w = FMul(vc, denom); } // v0 = b - a; // v1 = c - a; // v2 = p - a; void Gu::barycentricCoordinates(const Vec3VArg v0, const Vec3VArg v1, const Vec3VArg v2, FloatV& v, FloatV& w) { const FloatV d00 = V3Dot(v0, v0); const FloatV d01 = V3Dot(v0, v1); const FloatV d11 = V3Dot(v1, v1); const FloatV d20 = V3Dot(v2, v0); const FloatV d21 = V3Dot(v2, v1); const FloatV denom = FRecip(FSub(FMul(d00,d11), FMul(d01, d01))); v = FMul(FSub(FMul(d11, d20), FMul(d01, d21)), denom); w = FMul(FSub(FMul(d00, d21), FMul(d01, d20)), denom); }
3,790
C++
43.599999
155
0.7219
NVIDIA-Omniverse/PhysX/physx/source/geomutils/src/common/GuAdjacencies.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 "GuEdgeList.h" #include "GuAdjacencies.h" #include "CmSerialize.h" #include "CmRadixSort.h" // PT: code archeology: this initially came from ICE (IceAdjacencies.h/cpp). Consider putting it back the way it was initially. using namespace physx; using namespace Gu; using namespace Cm; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// /** * Flips the winding. */ void AdjTriangle::Flip() { #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY // Call the Triangle method IndexedTriangle::Flip(); #endif // Flip links. We flipped vertex references 1 & 2, i.e. links 0 & 1. physx::PxSwap(mATri[0], mATri[1]); } /** * Computes the number of boundary edges in a triangle. * \return the number of boundary edges. (0 => 3) */ PxU32 AdjTriangle::ComputeNbBoundaryEdges() const { // Look for boundary edges PxU32 Nb = 0; if(IS_BOUNDARY(mATri[0])) Nb++; if(IS_BOUNDARY(mATri[1])) Nb++; if(IS_BOUNDARY(mATri[2])) Nb++; return Nb; } /** * Computes the number of valid neighbors. * \return the number of neighbors. (0 => 3) */ PxU32 AdjTriangle::ComputeNbNeighbors() const { PxU32 Nb = 0; if(!IS_BOUNDARY(mATri[0])) Nb++; if(!IS_BOUNDARY(mATri[1])) Nb++; if(!IS_BOUNDARY(mATri[2])) Nb++; return Nb; } /** * Checks whether the triangle has a particular neighbor or not. * \param tref [in] the triangle reference to look for * \param index [out] the corresponding index in the triangle (NULL if not needed) * \return true if the triangle has the given neighbor */ bool AdjTriangle::HasNeighbor(PxU32 tref, PxU32* index) const { // ### could be optimized if(!IS_BOUNDARY(mATri[0]) && MAKE_ADJ_TRI(mATri[0])==tref) { if(index) *index = 0; return true; } if(!IS_BOUNDARY(mATri[1]) && MAKE_ADJ_TRI(mATri[1])==tref) { if(index) *index = 1; return true; } if(!IS_BOUNDARY(mATri[2]) && MAKE_ADJ_TRI(mATri[2])==tref) { if(index) *index = 2; return true; } return false; } Adjacencies::Adjacencies() : mNbFaces(0), mFaces(NULL) { } Adjacencies::~Adjacencies() { PX_DELETE_ARRAY(mFaces); } /** * Computes the number of boundary edges. * \return the number of boundary edges. */ PxU32 Adjacencies::ComputeNbBoundaryEdges() const { if(!mFaces) return 0; // Look for boundary edges PxU32 Nb = 0; for(PxU32 i=0;i<mNbFaces;i++) { AdjTriangle* CurTri = &mFaces[i]; Nb+=CurTri->ComputeNbBoundaryEdges(); } return Nb; } /** * Computes the boundary vertices. A boundary vertex is defined as a vertex shared by at least one boundary edge. * \param nb_verts [in] the number of vertices * \param bound_status [out] a user-provided array of bool * \return true if success. The user-array is filled with true or false (boundary vertex / not boundary vertex) */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool Adjacencies::GetBoundaryVertices(PxU32 nb_verts, bool* bound_status) const #else bool Adjacencies::GetBoundaryVertices(PxU32 nb_verts, bool* bound_status, const IndexedTriangle32* faces) const #endif { // We need the adjacencies if(!mFaces || !bound_status || !nb_verts) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::GetBoundaryVertices: NULL parameter!"); #ifndef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(!faces) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::GetBoundaryVertices: NULL parameter!"); #endif // Init PxMemZero(bound_status, nb_verts*sizeof(bool)); // Loop through faces for(PxU32 i=0;i<mNbFaces;i++) { AdjTriangle* CurTri = &mFaces[i]; if(IS_BOUNDARY(CurTri->mATri[0])) { // Two boundary vertices: 0 - 1 #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 VRef0 = CurTri->v[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = CurTri->v[1]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #else PxU32 VRef0 = faces[i].mRef[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = faces[i].mRef[1]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #endif } if(IS_BOUNDARY(CurTri->mATri[1])) { // Two boundary vertices: 0 - 2 #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 VRef0 = CurTri->v[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = CurTri->v[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #else PxU32 VRef0 = faces[i].mRef[0]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = faces[i].mRef[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #endif } if(IS_BOUNDARY(CurTri->mATri[2])) { // Two boundary vertices: 1 - 2 #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 VRef0 = CurTri->v[1]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = CurTri->v[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #else PxU32 VRef0 = faces[i].mRef[1]; if(VRef0>=nb_verts) return false; bound_status[VRef0] = true; PxU32 VRef1 = faces[i].mRef[2]; if(VRef1>=nb_verts) return false; bound_status[VRef1] = true; #endif } } return true; } /** * Assigns a new edge code to the counterpart link of a given link. * \param link [in] the link to modify - shouldn't be a boundary link * \param edge_nb [in] the new edge number */ void Adjacencies::AssignNewEdgeCode(PxU32 link, PxU8 edge_nb) { if(!IS_BOUNDARY(link)) { PxU32 Id = MAKE_ADJ_TRI(link); // Triangle ID PxU32 Edge = GET_EDGE_NB(link); // Counterpart edge ID AdjTriangle* Tri = &mFaces[Id]; // Adjacent triangle // Get link whose edge code is invalid PxU32 AdjLink = Tri->mATri[Edge]; // Link to ourself (i.e. to 'link') SET_EDGE_NB(AdjLink, edge_nb); // Assign new edge code Tri->mATri[Edge] = AdjLink; // Put link back } } /** * Modifies the existing database so that reference 'vref' of triangle 'curtri' becomes the last one. * Provided reference must already exist in provided triangle. * \param cur_tri [in] the triangle * \param vref [in] the reference * \return true if success. */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool Adjacencies::MakeLastRef(AdjTriangle& cur_tri, PxU32 vref) #else bool Adjacencies::MakeLastRef(AdjTriangle& cur_tri, PxU32 vref, IndexedTriangle32* cur_topo) #endif { #ifndef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(!cur_topo) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::MakeLastRef: NULL parameter!"); #endif // We want pattern (x y vref) // Edge 0-1 is (x y) // Edge 0-2 is (x vref) // Edge 1-2 is (y vref) // First thing is to scroll the existing references in order for vref to become the last one. Scrolling assures winding order is conserved. // Edge code need fixing as well: // The two MSB for each link encode the counterpart edge in adjacent triangle. We swap the link positions, but adjacent triangles remain the // same. In other words, edge codes are still valid for current triangle since counterpart edges have not been swapped. *BUT* edge codes of // the three possible adjacent triangles *are* now invalid. We need to fix edge codes, but for adjacent triangles... #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(cur_tri.v[0]==vref) #else if(cur_topo->mRef[0]==vref) #endif { // Pattern is (vref x y) // Edge 0-1 is (vref x) // Edge 0-2 is (vref y) // Edge 1-2 is (x y) // Catch original data #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 Ref0 = cur_tri.v[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_tri.v[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_tri.v[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_tri.v[0] = Ref1; cur_tri.v[1] = Ref2; cur_tri.v[2] = Ref0; #else PxU32 Ref0 = cur_topo->mRef[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_topo->mRef[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_topo->mRef[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_topo->mRef[0] = Ref1; cur_topo->mRef[1] = Ref2; cur_topo->mRef[2] = Ref0; #endif cur_tri.mATri[0] = Link12; // Edge 0-1 now encodes Ref1-Ref2, i.e. previous Link12 cur_tri.mATri[1] = Link01; // Edge 0-2 now encodes Ref1-Ref0, i.e. previous Link01 cur_tri.mATri[2] = Link02; // Edge 1-2 now encodes Ref2-Ref0, i.e. previous Link02 // Fix edge codes AssignNewEdgeCode(Link01, 1); AssignNewEdgeCode(Link02, 2); AssignNewEdgeCode(Link12, 0); return true; } #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY else if(cur_tri.v[1]==vref) #else else if(cur_topo->mRef[1]==vref) #endif { // Pattern is (x vref y) // Edge 0-1 is (x vref) // Edge 0-2 is (x y) // Edge 1-2 is (vref y) // Catch original data #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY PxU32 Ref0 = cur_tri.v[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_tri.v[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_tri.v[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_tri.v[0] = Ref2; cur_tri.v[1] = Ref0; cur_tri.v[2] = Ref1; #else PxU32 Ref0 = cur_topo->mRef[0]; PxU32 Link01 = cur_tri.mATri[0]; PxU32 Ref1 = cur_topo->mRef[1]; PxU32 Link02 = cur_tri.mATri[1]; PxU32 Ref2 = cur_topo->mRef[2]; PxU32 Link12 = cur_tri.mATri[2]; // Swap cur_topo->mRef[0] = Ref2; cur_topo->mRef[1] = Ref0; cur_topo->mRef[2] = Ref1; #endif cur_tri.mATri[0] = Link02; // Edge 0-1 now encodes Ref2-Ref0, i.e. previous Link02 cur_tri.mATri[1] = Link12; // Edge 0-2 now encodes Ref2-Ref1, i.e. previous Link12 cur_tri.mATri[2] = Link01; // Edge 1-2 now encodes Ref0-Ref1, i.e. previous Link01 // Fix edge codes AssignNewEdgeCode(Link01, 2); AssignNewEdgeCode(Link02, 0); AssignNewEdgeCode(Link12, 1); return true; } #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY else if(cur_tri.v[2]==vref) #else else if(cur_topo->mRef[2]==vref) #endif { // Nothing to do, provided reference already is the last one return true; } // Here the provided reference doesn't belong to the provided triangle. return false; } bool Adjacencies::Load(PxInputStream& stream) { // Import header PxU32 Version; bool Mismatch; if(!ReadHeader('A', 'D', 'J', 'A', Version, Mismatch, stream)) return false; // Import adjacencies mNbFaces = readDword(Mismatch, stream); mFaces = PX_NEW(AdjTriangle)[mNbFaces]; stream.read(mFaces, sizeof(AdjTriangle)*mNbFaces); return true; } //#ifdef PX_COOKING //! An edge class used to compute the adjacency structures. class AdjEdge : public EdgeData, public PxUserAllocated { public: PX_INLINE AdjEdge() {} PX_INLINE ~AdjEdge() {} PxU32 mFaceNb; //!< Owner face }; /** * Adds a new edge to the database. * \param ref0 [in] vertex reference for the new edge * \param ref1 [in] vertex reference for the new edge * \param face [in] owner face */ static void AddEdge(PxU32 ref0, PxU32 ref1, PxU32 face, PxU32& nb_edges, AdjEdge* edges) { // Store edge data edges[nb_edges].Ref0 = ref0; edges[nb_edges].Ref1 = ref1; edges[nb_edges].mFaceNb = face; nb_edges++; } /** * Adds a new triangle to the database. * \param ref0 [in] vertex reference for the new triangle * \param ref1 [in] vertex reference for the new triangle * \param ref2 [in] vertex reference for the new triangle * \param id [in] triangle index */ static void AddTriangle(PxU32 ref0, PxU32 ref1, PxU32 ref2, PxU32 id, AdjTriangle* faces, PxU32& nb_edges, AdjEdge* edges) { #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY // Store vertex-references faces[id].v[0] = ref0; faces[id].v[1] = ref1; faces[id].v[2] = ref2; #endif // Reset links faces[id].mATri[0] = PX_INVALID_U32; faces[id].mATri[1] = PX_INVALID_U32; faces[id].mATri[2] = PX_INVALID_U32; // Add edge 01 to database if(ref0<ref1) AddEdge(ref0, ref1, id, nb_edges, edges); else AddEdge(ref1, ref0, id, nb_edges, edges); // Add edge 02 to database if(ref0<ref2) AddEdge(ref0, ref2, id, nb_edges, edges); else AddEdge(ref2, ref0, id, nb_edges, edges); // Add edge 12 to database if(ref1<ref2) AddEdge(ref1, ref2, id, nb_edges, edges); else AddEdge(ref2, ref1, id, nb_edges, edges); } /** * Updates the links in two adjacent triangles. * \param first_tri [in] index of the first triangle * \param second_tri [in] index of the second triangle * \param ref0 [in] the common edge's first vertex reference * \param ref1 [in] the common edge's second vertex reference * \return true if success. */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY static bool UpdateLink(PxU32 first_tri, PxU32 second_tri, PxU32 ref0, PxU32 ref1, AdjTriangle* faces) #else static bool UpdateLink(PxU32 first_tri, PxU32 second_tri, PxU32 ref0, PxU32 ref1, AdjTriangle* faces, const ADJACENCIESCREATE& create) #endif { #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY AdjTriangle& Tri0 = faces[first_tri]; // Catch the first triangle AdjTriangle& Tri1 = faces[second_tri]; // Catch the second triangle // Get the edge IDs. 0xff means input references are wrong. PxU8 EdgeNb0 = Tri0.FindEdge(ref0, ref1); if(EdgeNb0==0xff) return SetIceError("Adjacencies::UpdateLink: invalid edge reference in first triangle"); PxU8 EdgeNb1 = Tri1.FindEdge(ref0, ref1); if(EdgeNb1==0xff) return SetIceError("Adjacencies::UpdateLink: invalid edge reference in second triangle"); // Update links. The two most significant bits contain the counterpart edge's ID. Tri0.mATri[EdgeNb0] = second_tri |(PxU32(EdgeNb1)<<30); Tri1.mATri[EdgeNb1] = first_tri |(PxU32(EdgeNb0)<<30); #else IndexedTriangle32 FirstTri, SecondTri; if(create.DFaces) { FirstTri.mRef[0] = create.DFaces[first_tri*3+0]; FirstTri.mRef[1] = create.DFaces[first_tri*3+1]; FirstTri.mRef[2] = create.DFaces[first_tri*3+2]; SecondTri.mRef[0] = create.DFaces[second_tri*3+0]; SecondTri.mRef[1] = create.DFaces[second_tri*3+1]; SecondTri.mRef[2] = create.DFaces[second_tri*3+2]; } if(create.WFaces) { FirstTri.mRef[0] = create.WFaces[first_tri*3+0]; FirstTri.mRef[1] = create.WFaces[first_tri*3+1]; FirstTri.mRef[2] = create.WFaces[first_tri*3+2]; SecondTri.mRef[0] = create.WFaces[second_tri*3+0]; SecondTri.mRef[1] = create.WFaces[second_tri*3+1]; SecondTri.mRef[2] = create.WFaces[second_tri*3+2]; } // Get the edge IDs. 0xff means input references are wrong. const PxU8 EdgeNb0 = FirstTri.findEdge(ref0, ref1); const PxU8 EdgeNb1 = SecondTri.findEdge(ref0, ref1); if(EdgeNb0==0xff || EdgeNb1==0xff) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::UpdateLink: invalid edge reference"); // Update links. The two most significant bits contain the counterpart edge's ID. faces[first_tri].mATri[EdgeNb0] = second_tri |(PxU32(EdgeNb1)<<30); faces[second_tri].mATri[EdgeNb1] = first_tri |(PxU32(EdgeNb0)<<30); #endif return true; } /** * Creates the adjacency structures. * \return true if success. */ #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY static bool CreateDatabase(AdjTriangle* faces, PxU32 nb_edges, const AdjEdge* edges) #else static bool CreateDatabase(AdjTriangle* faces, PxU32 nb_edges, const AdjEdge* edges, const ADJACENCIESCREATE& create) #endif { RadixSortBuffered Core; { // Multiple sorts - this rewritten version uses less ram // PT: TTP 2994: the mesh has 343000+ edges, so yeah, sure, allocating more than 1mb on the stack causes overflow... PxU32* VRefs = PX_ALLOCATE(PxU32, nb_edges, "tmp"); // Sort according to mRef0, then mRef1 PxU32 i; for(i=0;i<nb_edges;i++) VRefs[i] = edges[i].Ref0; Core.Sort(VRefs, nb_edges); for(i=0;i<nb_edges;i++) VRefs[i] = edges[i].Ref1; Core.Sort(VRefs, nb_edges); PX_FREE(VRefs); } const PxU32* Sorted = Core.GetRanks(); // Read the list in sorted order, look for similar edges PxU32 LastRef0 = edges[Sorted[0]].Ref0; PxU32 LastRef1 = edges[Sorted[0]].Ref1; PxU32 Count = 0; PxU32 TmpBuffer[3]; while(nb_edges--) { PxU32 SortedIndex = *Sorted++; PxU32 Face = edges[SortedIndex].mFaceNb; // Owner face PxU32 Ref0 = edges[SortedIndex].Ref0; // Vertex ref #1 PxU32 Ref1 = edges[SortedIndex].Ref1; // Vertex ref #2 if(Ref0==LastRef0 && Ref1==LastRef1) { // Current edge is the same as last one TmpBuffer[Count++] = Face; // Store face number // Only works with manifold meshes (i.e. an edge is not shared by more than 2 triangles) if(Count==3) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "Adjacencies::CreateDatabase: can't work on non-manifold meshes."); } else { // Here we have a new edge (LastRef0, LastRef1) shared by Count triangles stored in TmpBuffer if(Count==2) { // if Count==1 => edge is a boundary edge: it belongs to a single triangle. // Hence there's no need to update a link to an adjacent triangle. #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(!UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces)) return false; #else if(!UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces, create)) return false; #endif } // Reset for next edge Count = 0; TmpBuffer[Count++] = Face; LastRef0 = Ref0; LastRef1 = Ref1; } } bool Status = true; #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY if(Count==2) Status = UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces); #else if(Count==2) Status = UpdateLink(TmpBuffer[0], TmpBuffer[1], LastRef0, LastRef1, faces, create); #endif return Status; } AdjacenciesBuilder::AdjacenciesBuilder() { } AdjacenciesBuilder::~AdjacenciesBuilder() { } /** * Initializes the component. * \param create [in] the creation structure * \return true if success. */ bool AdjacenciesBuilder::Init(const ADJACENCIESCREATE& create) { if(!create.NbFaces) return false; // Get some bytes mNbFaces = create.NbFaces; mFaces = PX_NEW(AdjTriangle)[mNbFaces]; AdjEdge* Edges = PX_NEW(AdjEdge)[mNbFaces*3]; PxU32 NbEdges=0; // Feed me with triangles..... for(PxU32 i=0;i<mNbFaces;i++) { // Get correct vertex references const PxU32 Ref0 = create.DFaces ? create.DFaces[i*3+0] : create.WFaces ? create.WFaces[i*3+0] : 0; const PxU32 Ref1 = create.DFaces ? create.DFaces[i*3+1] : create.WFaces ? create.WFaces[i*3+1] : 1; const PxU32 Ref2 = create.DFaces ? create.DFaces[i*3+2] : create.WFaces ? create.WFaces[i*3+2] : 2; // Add a triangle to the database AddTriangle(Ref0, Ref1, Ref2, i, mFaces, NbEdges, Edges); } // At this point of the process we have mFaces & Edges filled with input data. That is: // - a list of triangles with 3 NULL links (i.e. PX_INVALID_U32) // - a list of mNbFaces*3 edges, each edge having 2 vertex references and an owner face. // Here NbEdges should be equal to mNbFaces*3. PX_ASSERT(NbEdges==mNbFaces*3); #ifdef MSH_ADJACENCIES_INCLUDE_TOPOLOGY bool Status = CreateDatabase(mFaces, NbEdges, Edges); #else bool Status = CreateDatabase(mFaces, NbEdges, Edges, create); #endif // We don't need the edges anymore PX_DELETE_ARRAY(Edges); #ifdef MSH_ADJACENCIES_INCLUDE_CONVEX_BITS // Now create convex information. This creates coupling between adjacencies & edge-list but in this case it's actually the goal: // mixing the two structures to save memory. if(Status && create.Verts) { EDGELISTCREATE ELC; ELC.NbFaces = create.NbFaces; ELC.DFaces = create.DFaces; // That's where I like having a unified way to do things... We ELC.WFaces = create.WFaces; // can just directly copy the same pointers. ELC.FacesToEdges = true; ELC.Verts = create.Verts; ELC.Epsilon = create.Epsilon; EdgeList EL; if(EL.init(ELC)) { for(PxU32 i=0;i<mNbFaces;i++) { const EdgeTriangleData& ET = EL.getEdgeTriangle(i); if(EdgeTriangleAC::HasActiveEdge01(ET)) mFaces[i].mATri[EDGE01] |= 0x20000000; else mFaces[i].mATri[EDGE01] &= ~0x20000000; if(EdgeTriangleAC::HasActiveEdge20(ET)) mFaces[i].mATri[EDGE02] |= 0x20000000; else mFaces[i].mATri[EDGE02] &= ~0x20000000; if(EdgeTriangleAC::HasActiveEdge12(ET)) mFaces[i].mATri[EDGE12] |= 0x20000000; else mFaces[i].mATri[EDGE12] &= ~0x20000000; PX_ASSERT((EdgeTriangleAC::HasActiveEdge01(ET) && mFaces[i].HasActiveEdge01()) || (!EdgeTriangleAC::HasActiveEdge01(ET) && !mFaces[i].HasActiveEdge01())); PX_ASSERT((EdgeTriangleAC::HasActiveEdge20(ET) && mFaces[i].HasActiveEdge20()) || (!EdgeTriangleAC::HasActiveEdge20(ET) && !mFaces[i].HasActiveEdge20())); PX_ASSERT((EdgeTriangleAC::HasActiveEdge12(ET) && mFaces[i].HasActiveEdge12()) || (!EdgeTriangleAC::HasActiveEdge12(ET) && !mFaces[i].HasActiveEdge12())); } } } #endif return Status; } /* bool AdjacenciesBuilder::Save(Stream& stream) const { bool PlatformMismatch = PxPlatformMismatch(); // Export header if(!WriteHeader('A', 'D', 'J', 'A', gVersion, PlatformMismatch, stream)) return false; // Export adjacencies // stream.StoreDword(mNbFaces); WriteDword(mNbFaces, PlatformMismatch, stream); // stream.StoreBuffer(mFaces, sizeof(AdjTriangle)*mNbFaces); WriteDwordBuffer((const PxU32*)mFaces, mNbFaces*3, PlatformMismatch, stream); return true; }*/ //#endif
22,841
C++
33.452489
158
0.690381