file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlMemoryPool.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_MEMORY_POOL_H #define SN_XML_MEMORY_POOL_H #include "foundation/PxAssert.h" #include "foundation/PxArray.h" #include "PxProfileAllocatorWrapper.h" namespace physx { using namespace physx::profile; /** * Linked list used to store next node ptr. */ struct SMemPoolNode { SMemPoolNode* mNextNode; }; /** * Template arguments are powers of two. * A very fast memory pool that is not memory efficient. It contains a vector of pointers * to blocks of memory along with a linked list of free sections. All sections are * of the same size so allocating memory is very fast, there isn't a linear search * through blocks of indeterminate size. It also means there is memory wasted * when objects aren't sized to powers of two. */ template<PxU8 TItemSize , PxU8 TItemCount > class CMemoryPool { typedef PxProfileArray<PxU8*> TPxU8PtrList; PxProfileAllocatorWrapper& mWrapper; TPxU8PtrList mAllMemory; SMemPoolNode* mFirstFreeNode; public: CMemoryPool(PxProfileAllocatorWrapper& inWrapper) : mWrapper( inWrapper ) , mAllMemory( inWrapper ) , mFirstFreeNode( NULL ) {} ~CMemoryPool() { TPxU8PtrList::ConstIterator theEnd = mAllMemory.end(); for ( TPxU8PtrList::ConstIterator theIter = mAllMemory.begin(); theIter != theEnd; ++theIter ) { PxU8* thePtr = *theIter; mWrapper.getAllocator().deallocate( thePtr ); } mAllMemory.clear(); mFirstFreeNode = NULL; } //Using deallocated memory to hold the pointers to the next amount of memory. PxU8* allocate() { if ( mFirstFreeNode ) { PxU8* retval = reinterpret_cast<PxU8*>(mFirstFreeNode); mFirstFreeNode = mFirstFreeNode->mNextNode; return retval; } PxU32 itemSize = GetItemSize(); PxU32 itemCount = 1 << TItemCount; //No free nodes, make some more. PxU8* retval = reinterpret_cast<PxU8*>(mWrapper.getAllocator().allocate( itemCount * itemSize, "RepX fixed-size memory pool", PX_FL)); PxU8* dataPtr = retval + itemSize; //Free extra chunks for( PxU32 idx = 1; idx < itemCount; ++idx, dataPtr += itemSize ) deallocate( dataPtr ); mAllMemory.pushBack(retval); return retval; } void deallocate( PxU8* inData ) { SMemPoolNode* nodePtr = reinterpret_cast<SMemPoolNode*>(inData); nodePtr->mNextNode = mFirstFreeNode; mFirstFreeNode = nodePtr; } //We have to have at least a pointer's worth of memory inline PxU32 GetItemSize() { return sizeof(SMemPoolNode) << TItemSize; } }; typedef PxU32 TMemAllocSizeType; struct SVariableMemPoolNode : SMemPoolNode { TMemAllocSizeType mSize; SVariableMemPoolNode* NextNode() { return static_cast< SVariableMemPoolNode* >( mNextNode ); } }; /** * Manages variable sized allocations. * Keeps track of freed allocations in a insertion sorted * list. Allocating new memory traverses the list linearly. * This object will split nodes if the node is more than * twice as large as the request memory allocation. */ class CVariableMemoryPool { typedef PxProfileHashMap<TMemAllocSizeType, SVariableMemPoolNode*> TFreeNodeMap; typedef PxProfileArray<PxU8*> TPxU8PtrList; PxProfileAllocatorWrapper& mWrapper; TPxU8PtrList mAllMemory; TFreeNodeMap mFreeNodeMap; PxU32 mMinAllocationSize; CVariableMemoryPool &operator=(const CVariableMemoryPool &); public: CVariableMemoryPool(PxProfileAllocatorWrapper& inWrapper, PxU32 inMinAllocationSize = 0x20 ) : mWrapper( inWrapper ) , mAllMemory( inWrapper ) , mFreeNodeMap( inWrapper) , mMinAllocationSize( inMinAllocationSize ) {} ~CVariableMemoryPool() { TPxU8PtrList::ConstIterator theEnd = mAllMemory.end(); for ( TPxU8PtrList::ConstIterator theIter = mAllMemory.begin(); theIter != theEnd; ++theIter ) { PxU8* thePtr = *theIter; mWrapper.getAllocator().deallocate( thePtr ); } mAllMemory.clear(); mFreeNodeMap.clear(); } PxU8* MarkMem( PxU8* inMem, TMemAllocSizeType inSize ) { PX_ASSERT( inSize >= sizeof( SVariableMemPoolNode ) ); SVariableMemPoolNode* theMem = reinterpret_cast<SVariableMemPoolNode*>( inMem ); theMem->mSize = inSize; return reinterpret_cast< PxU8* >( theMem + 1 ); } //Using deallocated memory to hold the pointers to the next amount of memory. PxU8* allocate( PxU32 size ) { //Ensure we can place the size of the memory at the start //of the memory block. //Kai: to reduce the size of hash map, the requested size is aligned to 128 bytes PxU32 theRequestedSize = (size + sizeof(SVariableMemPoolNode) + 127) & ~127; TFreeNodeMap::Entry* entry = const_cast<TFreeNodeMap::Entry*>( mFreeNodeMap.find( theRequestedSize ) ); if ( NULL != entry ) { SVariableMemPoolNode* theNode = entry->second; PX_ASSERT( NULL != theNode ); PX_ASSERT( theNode->mSize == theRequestedSize ); entry->second = theNode->NextNode(); if (entry->second == NULL) mFreeNodeMap.erase( theRequestedSize ); return reinterpret_cast< PxU8* >( theNode + 1 ); } if ( theRequestedSize < mMinAllocationSize ) theRequestedSize = mMinAllocationSize; //No large enough free nodes, make some more. PxU8* retval = reinterpret_cast<PxU8*>(mWrapper.getAllocator().allocate( size_t(theRequestedSize), "RepX variable sized memory pool", PX_FL)); //If we allocated it, we free it. mAllMemory.pushBack( retval ); return MarkMem( retval, theRequestedSize ); } //The size is stored at the beginning of the memory block. void deallocate( PxU8* inData ) { SVariableMemPoolNode* theData = reinterpret_cast< SVariableMemPoolNode* >( inData ) - 1; TMemAllocSizeType theSize = theData->mSize; AddFreeMem( reinterpret_cast< PxU8* >( theData ), theSize ); } void CheckFreeListInvariant( SVariableMemPoolNode* inNode ) { if ( inNode && inNode->mNextNode ) { PX_ASSERT( inNode->mSize <= inNode->NextNode()->mSize ); } } void AddFreeMem( PxU8* inMemory, TMemAllocSizeType inSize ) { PX_ASSERT( inSize >= sizeof( SVariableMemPoolNode ) ); SVariableMemPoolNode* theNewNode = reinterpret_cast< SVariableMemPoolNode* >( inMemory ); theNewNode->mNextNode = NULL; theNewNode->mSize = inSize; TFreeNodeMap::Entry* entry = const_cast<TFreeNodeMap::Entry*>( mFreeNodeMap.find( inSize ) ); if (NULL != entry) { theNewNode->mNextNode = entry->second; entry->second = theNewNode; } else { mFreeNodeMap.insert( inSize, theNewNode ); } } }; /** * The manager keeps a list of memory pools for different sizes of allocations. * Anything too large simply gets allocated using the new operator. * This doesn't mark the memory with the size of the allocated memory thus * allowing much more efficient allocation of small items. For large enough * allocations, it does mark the size. * * When using as a general memory manager, you need to wrap this class with * something that actually does mark the returned allocation with the size * of the allocation. */ class CMemoryPoolManager { CMemoryPoolManager &operator=(const CMemoryPoolManager &); public: PxProfileAllocatorWrapper mWrapper; //CMemoryPool<0,8> m0ItemPool; //CMemoryPool<1,8> m1ItemPool; //CMemoryPool<2,8> m2ItemPool; //CMemoryPool<3,8> m3ItemPool; //CMemoryPool<4,8> m4ItemPool; //CMemoryPool<5,8> m5ItemPool; //CMemoryPool<6,8> m6ItemPool; //CMemoryPool<7,8> m7ItemPool; //CMemoryPool<8,8> m8ItemPool; CVariableMemoryPool mVariablePool; CMemoryPoolManager( PxAllocatorCallback& inAllocator ) : mWrapper( inAllocator ) //, m0ItemPool( mWrapper ) //, m1ItemPool( mWrapper ) //, m2ItemPool( mWrapper ) //, m3ItemPool( mWrapper ) //, m4ItemPool( mWrapper ) //, m5ItemPool( mWrapper ) //, m6ItemPool( mWrapper ) //, m7ItemPool( mWrapper ) //, m8ItemPool( mWrapper ) , mVariablePool( mWrapper ) { } PxProfileAllocatorWrapper& getWrapper() { return mWrapper; } inline PxU8* allocate( PxU32 inSize ) { /* if ( inSize <= m0ItemPool.GetItemSize() ) return m0ItemPool.allocate(); if ( inSize <= m1ItemPool.GetItemSize() ) return m1ItemPool.allocate(); if ( inSize <= m2ItemPool.GetItemSize() ) return m2ItemPool.allocate(); if ( inSize <= m3ItemPool.GetItemSize() ) return m3ItemPool.allocate(); if ( inSize <= m4ItemPool.GetItemSize() ) return m4ItemPool.allocate(); if ( inSize <= m5ItemPool.GetItemSize() ) return m5ItemPool.allocate(); if ( inSize <= m6ItemPool.GetItemSize() ) return m6ItemPool.allocate(); if ( inSize <= m7ItemPool.GetItemSize() ) return m7ItemPool.allocate(); if ( inSize <= m8ItemPool.GetItemSize() ) return m8ItemPool.allocate(); */ return mVariablePool.allocate( inSize ); } inline void deallocate( PxU8* inMemory ) { if ( inMemory == NULL ) return; /* if ( inSize <= m0ItemPool.GetItemSize() ) m0ItemPool.deallocate(inMemory); else if ( inSize <= m1ItemPool.GetItemSize() ) m1ItemPool.deallocate(inMemory); else if ( inSize <= m2ItemPool.GetItemSize() ) m2ItemPool.deallocate(inMemory); else if ( inSize <= m3ItemPool.GetItemSize() ) m3ItemPool.deallocate(inMemory); else if ( inSize <= m4ItemPool.GetItemSize() ) m4ItemPool.deallocate(inMemory); else if ( inSize <= m5ItemPool.GetItemSize() ) m5ItemPool.deallocate(inMemory); else if ( inSize <= m6ItemPool.GetItemSize() ) m6ItemPool.deallocate(inMemory); else if ( inSize <= m7ItemPool.GetItemSize() ) m7ItemPool.deallocate(inMemory); else if ( inSize <= m8ItemPool.GetItemSize() ) m8ItemPool.deallocate(inMemory); else */ mVariablePool.deallocate(inMemory); } /** * allocate an object. Calls constructor on the new memory. */ template<typename TObjectType> inline TObjectType* allocate() { TObjectType* retval = reinterpret_cast<TObjectType*>( allocate( sizeof(TObjectType) ) ); new (retval)TObjectType(); return retval; } /** * deallocate an object calling the destructor on the object. * This *must* be the concrete type, it cannot be a generic type. */ template<typename TObjectType> inline void deallocate( TObjectType* inObject ) { inObject->~TObjectType(); deallocate( reinterpret_cast<PxU8*>(inObject) ); } /** * allocate an object. Calls constructor on the new memory. */ template<typename TObjectType> inline TObjectType* BatchAllocate(PxU32 inCount ) { TObjectType* retval = reinterpret_cast<TObjectType*>( allocate( sizeof(TObjectType) * inCount ) ); return retval; } /** * deallocate an object calling the destructor on the object. * This *must* be the concrete type, it cannot be a generic type. */ template<typename TObjectType> inline void BatchDeallocate( TObjectType* inObject, PxU32 inCount ) { PX_UNUSED(inCount); deallocate( reinterpret_cast<PxU8*>(inObject) ); } }; } #endif
12,640
C
32.799465
145
0.707437
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlSerializer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_SERIALIZER_H #define SN_XML_SERIALIZER_H #include "PxExtensionMetaDataObjects.h" #include "SnXmlVisitorWriter.h" namespace physx { namespace Sn { void writeHeightFieldSample( PxOutputStream& inStream, const PxHeightFieldSample& inSample ) { PxU32 retval = 0; PxU8* writePtr( reinterpret_cast< PxU8*>( &retval ) ); const PxU8* inPtr( reinterpret_cast<const PxU8*>( &inSample ) ); if ( isBigEndian() ) { //Height field samples are a //16 bit integer followed by two bytes. //right now, data is 2 1 3 4 //We need a 32 bit integer that //when read in by a LE system is 4 3 2 1. //Thus, we need a BE integer that looks like: //4 3 2 1 writePtr[0] = inPtr[3]; writePtr[1] = inPtr[2]; writePtr[2] = inPtr[0]; writePtr[3] = inPtr[1]; } else { writePtr[0] = inPtr[0]; writePtr[1] = inPtr[1]; writePtr[2] = inPtr[2]; writePtr[3] = inPtr[3]; } inStream << retval; } template<typename TDataType, typename TWriteOperator> inline void writeStridedBufferProperty( XmlWriter& writer, MemoryBuffer& tempBuffer, const char* inPropName, const void* inData, PxU32 inStride, PxU32 inCount, PxU32 inItemsPerLine, TWriteOperator inOperator ) { PX_ASSERT( inStride == 0 || inStride == sizeof( TDataType ) ); PX_UNUSED( inStride ); writeBuffer( writer, tempBuffer , inItemsPerLine, reinterpret_cast<const TDataType*>( inData ) , inCount, inPropName, inOperator ); } template<typename TDataType, typename TWriteOperator> inline void writeStridedBufferProperty( XmlWriter& writer, MemoryBuffer& tempBuffer, const char* inPropName, const PxStridedData& inData, PxU32 inCount, PxU32 inItemsPerLine, TWriteOperator inOperator ) { writeStridedBufferProperty<TDataType>( writer, tempBuffer, inPropName, inData.data, inData.stride, inCount, inItemsPerLine, inOperator ); } template<typename TDataType, typename TWriteOperator> inline void writeStridedBufferProperty( XmlWriter& writer, MemoryBuffer& tempBuffer, const char* inPropName, const PxTypedStridedData<TDataType>& inData, PxU32 inCount, PxU32 inItemsPerLine, TWriteOperator inOperator ) { writeStridedBufferProperty<TDataType>( writer, tempBuffer, inPropName, inData.data, inData.stride, inCount, inItemsPerLine, inOperator ); } template<typename TDataType, typename TWriteOperator> inline void writeStridedBufferProperty( XmlWriter& writer, MemoryBuffer& tempBuffer, const char* inPropName, const PxBoundedData& inData, PxU32 inItemsPerLine, TWriteOperator inWriteOperator ) { writeStridedBufferProperty<TDataType>( writer, tempBuffer, inPropName, inData, inData.count, inItemsPerLine, inWriteOperator ); } template<typename TDataType, typename TWriteOperator> inline void writeStridedBufferProperty( XmlWriter& writer, MemoryBuffer& tempBuffer, const char* inPropName, PxStrideIterator<const TDataType>& inData, PxU32 inCount, PxU32 inItemsPerLine, TWriteOperator inWriteOperator ) { writeStrideBuffer<TDataType>(writer, tempBuffer , inItemsPerLine, inData, PtrAccess<TDataType> , inCount, inPropName, inData.stride(), inWriteOperator ); } template<typename TDataType> inline void writeStridedFlagsProperty( XmlWriter& writer, MemoryBuffer& tempBuffer, const char* inPropName, PxStrideIterator<const TDataType>& inData, PxU32 inCount, PxU32 inItemsPerLine, const PxU32ToName* inTable ) { writeStrideFlags<TDataType>(writer, tempBuffer , inItemsPerLine, inData, PtrAccess<TDataType> , inCount, inPropName, inTable ); } } } #endif
5,229
C
43.322034
222
0.757889
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepXCollection.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_REPX_COLLECTION_H #define SN_REPX_COLLECTION_H #include "common/PxTolerancesScale.h" #include "extensions/PxRepXSerializer.h" namespace physx { namespace Sn { struct XmlNode; struct RepXCollectionItem { PxRepXObject liveObject; XmlNode* descriptor; RepXCollectionItem( PxRepXObject inItem = PxRepXObject(), XmlNode* inDescriptor = NULL ) : liveObject( inItem ) , descriptor( inDescriptor ) { } }; struct RepXDefaultEntry { const char* name; const char* value; RepXDefaultEntry( const char* pn, const char* val ) : name( pn ), value( val ){} }; /** * The result of adding an object to the collection. */ struct RepXAddToCollectionResult { enum Enum { Success, SerializerNotFound, InvalidParameters, //Null data passed in. AlreadyInCollection }; PxSerialObjectId collectionId; Enum result; RepXAddToCollectionResult( Enum inResult = Success, const PxSerialObjectId inId = 0 ) : collectionId( inId ) , result( inResult ) { } bool isValid() { return result == Success && collectionId != 0; } }; /** * A RepX collection contains a set of static data objects that can be transformed * into live objects. It uses RepX serializer to do two transformations: * live object <-> collection object (descriptor) * collection object <-> file system. * * A live object is considered to be something live in the physics * world such as a material or a rigidstatic. * * A collection object is a piece of data from which a live object * of identical characteristics can be created. * * Clients need to pass PxCollection so that objects can resolve * references. In addition, objects must be added in an order such that * references can be resolved in the first place. So objects must be added * to the collection *after* objects they are dependent upon. * * When deserializing from a file, the collection will allocate char*'s that will * not be freed when the collection itself is freed. The user must be responsible * for these character allocations. */ class RepXCollection { protected: virtual ~RepXCollection(){} public: virtual void destroy() = 0; /** * Set the scale on this collection. The scale is saved with the collection. * * If the scale wasn't set, it will be invalid. */ virtual void setTolerancesScale( const PxTolerancesScale& inScale ) = 0; /** * Get the scale that was set at collection creation time or at load time. * If this is a loaded file and the source data does not contain a scale * this value will be invalid (PxTolerancesScale::isValid()). */ virtual PxTolerancesScale getTolerancesScale() const = 0; /** * Set the up vector on this collection. The up vector is saved with the collection. * * If the up vector wasn't set, it will be (0,0,0). */ virtual void setUpVector( const PxVec3& inUpVector ) = 0; /** * If the up vector wasn't set, it will be (0,0,0). Else this will be the up vector * optionally set when the collection was created. */ virtual PxVec3 getUpVector() const = 0; virtual const char* getVersion() = 0; static const char* getLatestVersion(); //Necessary accessor functions for translation/upgrading. virtual const RepXCollectionItem* begin() const = 0; virtual const RepXCollectionItem* end() const = 0; //Performs a deep copy of the repx node. virtual XmlNode* copyRepXNode( const XmlNode* srcNode ) = 0; virtual void addCollectionItem( RepXCollectionItem inItem ) = 0; //Create a new repx node with this name. Its value is unset. virtual XmlNode& createRepXNode( const char* name ) = 0; virtual RepXCollection& createCollection( const char* inVersionStr ) = 0; //Release this when finished. virtual XmlReaderWriter& createNodeEditor() = 0; virtual PxAllocatorCallback& getAllocator() = 0; virtual bool instantiateCollection( PxRepXInstantiationArgs& inArgs, PxCollection& inPxCollection ) = 0; virtual RepXAddToCollectionResult addRepXObjectToCollection( const PxRepXObject& inObject, PxCollection* inCollection, PxRepXInstantiationArgs& inArgs ) = 0; /** * Save this collection out to a file stream. Uses the RepX serialize to perform * collection object->file conversions. * * /param[in] inStream Write-only stream to save collection out to. */ virtual void save( PxOutputStream& inStream ) = 0; }; } } #endif
6,101
C
34.068965
159
0.731519
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnPxStreamOperators.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_PX_STREAM_OPERATORS_H #define SN_PX_STREAM_OPERATORS_H #include "foundation/PxVec3.h" #include "foundation/PxTransform.h" #include "foundation/PxBounds3.h" #include "foundation/PxString.h" #include "PxFiltering.h" namespace physx { static inline PxU32 strLenght( const char* inStr ) { return inStr ? PxU32(strlen(inStr)) : 0; } } namespace physx // ADL requires we put the operators in the same namespace as the underlying type of PxOutputStream { inline PxOutputStream& operator << ( PxOutputStream& ioStream, const char* inString ) { if ( inString && *inString ) { ioStream.write( inString, PxU32(strlen(inString)) ); } return ioStream; } template<typename TDataType> inline PxOutputStream& toStream( PxOutputStream& ioStream, const char* inFormat, const TDataType inData ) { char buffer[128] = { 0 }; Pxsnprintf( buffer, 128, inFormat, inData ); ioStream << buffer; return ioStream; } struct endl_obj {}; //static endl_obj endl; inline PxOutputStream& operator << ( PxOutputStream& ioStream, bool inData ) { ioStream << (inData ? "true" : "false"); return ioStream; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxI32 inData ) { return toStream( ioStream, "%d", inData ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxU16 inData ) { return toStream( ioStream, "%u", PxU32(inData) ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxU8 inData ) { return toStream( ioStream, "%u", PxU32(inData) ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, char inData ) { return toStream( ioStream, "%c", inData ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxU32 inData ) { return toStream( ioStream, "%u", inData ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxU64 inData ) { return toStream( ioStream, "%" PX_PRIu64, inData ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, const void* inData ) { return ioStream << static_cast<uint64_t>(size_t(inData)); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxF32 inData ) { return toStream( ioStream, "%g", PxF64(inData) ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, PxF64 inData ) { return toStream( ioStream, "%g", inData ); } inline PxOutputStream& operator << ( PxOutputStream& ioStream, endl_obj) { return ioStream << "\n"; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, const PxVec3& inData ) { ioStream << inData[0]; ioStream << " "; ioStream << inData[1]; ioStream << " "; ioStream << inData[2]; return ioStream; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, const PxQuat& inData ) { ioStream << inData.x; ioStream << " "; ioStream << inData.y; ioStream << " "; ioStream << inData.z; ioStream << " "; ioStream << inData.w; return ioStream; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, const PxTransform& inData ) { ioStream << inData.q; ioStream << " "; ioStream << inData.p; return ioStream; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, const PxBounds3& inData ) { ioStream << inData.minimum; ioStream << " "; ioStream << inData.maximum; return ioStream; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, const PxFilterData& inData ) { ioStream << inData.word0 << " " << inData.word1 << " " << inData.word2 << " " << inData.word3; return ioStream; } inline PxOutputStream& operator << ( PxOutputStream& ioStream, struct PxMetaDataPlane& inData ) { ioStream << inData.normal; ioStream << " "; ioStream << inData.distance; return ioStream; } } #endif
5,411
C
39.088889
146
0.716503
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnJointRepXSerializer.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 "PxMetaDataObjects.h" #include "PxExtensionMetaDataObjects.h" #include "ExtJointMetaDataExtensions.h" #include "SnJointRepXSerializer.h" namespace physx { template<typename TJointType> inline TJointType* createJoint( PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1 ) { PX_UNUSED(physics); PX_UNUSED(actor0); PX_UNUSED(actor1); PX_UNUSED(localFrame0); PX_UNUSED(localFrame1); return NULL; } template<> inline PxD6Joint* createJoint<PxD6Joint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxD6JointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<> inline PxDistanceJoint* createJoint<PxDistanceJoint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxDistanceJointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<> inline PxContactJoint* createJoint<PxContactJoint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxContactJointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<> inline PxFixedJoint* createJoint<PxFixedJoint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxFixedJointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<> inline PxPrismaticJoint* createJoint<PxPrismaticJoint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxPrismaticJointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<> inline PxRevoluteJoint* createJoint<PxRevoluteJoint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxRevoluteJointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<> inline PxSphericalJoint* createJoint<PxSphericalJoint>(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { return PxSphericalJointCreate( physics, actor0, localFrame0, actor1, localFrame1 ); } template<typename TJointType> PxRepXObject PxJointRepXSerializer<TJointType>::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) { PxRigidActor* actor0 = NULL; PxRigidActor* actor1 = NULL; PxTransform localPose0 = PxTransform(PxIdentity); PxTransform localPose1 = PxTransform(PxIdentity); bool ok = true; if ( inReader.gotoChild( "Actors" ) ) { ok = readReference<PxRigidActor>( inReader, *inCollection, "actor0", actor0 ); ok &= readReference<PxRigidActor>( inReader, *inCollection, "actor1", actor1 ); inReader.leaveChild(); } TJointType* theJoint = !ok ? NULL : createJoint<TJointType>( inArgs.physics, actor0, localPose0, actor1, localPose1 ); if ( theJoint ) { PxConstraint* constraint = theJoint->getConstraint(); PX_ASSERT( constraint ); inCollection->add( *constraint ); this->fileToObjectImpl( theJoint, inReader, inAllocator, inArgs, inCollection ); } return PxCreateRepXObject(theJoint); } template<typename TJointType> void PxJointRepXSerializer<TJointType>::objectToFileImpl( const TJointType* inObj, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& ) { writeAllProperties( inObj, inWriter, inTempBuffer, *inCollection ); } // explicit template instantiations template struct PxJointRepXSerializer<PxFixedJoint>; template struct PxJointRepXSerializer<PxDistanceJoint>; template struct PxJointRepXSerializer<PxContactJoint>; template struct PxJointRepXSerializer<PxD6Joint>; template struct PxJointRepXSerializer<PxPrismaticJoint>; template struct PxJointRepXSerializer<PxRevoluteJoint>; template struct PxJointRepXSerializer<PxSphericalJoint>; }
6,185
C++
41.662069
190
0.750202
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnSimpleXmlWriter.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_SIMPLE_XML_WRITER_H #define SN_SIMPLE_XML_WRITER_H #include "foundation/PxArray.h" #include "SnXmlMemoryPoolStreams.h" namespace physx { namespace Sn { class SimpleXmlWriter { public: struct STagWatcher { typedef SimpleXmlWriter TXmlWriterType; TXmlWriterType& mWriter; STagWatcher( const STagWatcher& inOther ); STagWatcher& operator-( const STagWatcher& inOther ); STagWatcher( TXmlWriterType& inWriter, const char* inTagName ) : mWriter( inWriter ) { mWriter.beginTag( inTagName ); } ~STagWatcher() { mWriter.endTag(); } protected: STagWatcher& operator=(const STagWatcher&); }; virtual ~SimpleXmlWriter(){} virtual void beginTag( const char* inTagname ) = 0; virtual void endTag() = 0; virtual void addAttribute( const char* inName, const char* inValue ) = 0; virtual void writeContentTag( const char* inTag, const char* inContent ) = 0; virtual void addContent( const char* inContent ) = 0; virtual PxU32 tabCount() = 0; private: SimpleXmlWriter& operator=(const SimpleXmlWriter&); }; template<typename TStreamType> class SimpleXmlWriterImpl : public SimpleXmlWriter { PxProfileAllocatorWrapper mWrapper; TStreamType& mStream; SimpleXmlWriterImpl( const SimpleXmlWriterImpl& inOther ); SimpleXmlWriterImpl& operator=( const SimpleXmlWriterImpl& inOther ); PxProfileArray<const char*> mTags; bool mTagOpen; PxU32 mInitialTagDepth; public: SimpleXmlWriterImpl( TStreamType& inStream, PxAllocatorCallback& inAllocator, PxU32 inInitialTagDepth = 0 ) : mWrapper( inAllocator ) , mStream( inStream ) , mTags( mWrapper ) , mTagOpen( false ) , mInitialTagDepth( inInitialTagDepth ) { } virtual ~SimpleXmlWriterImpl() { while( mTags.size() ) endTag(); } PxU32 tabCount() { return mTags.size() + mInitialTagDepth; } void writeTabs( PxU32 inSize ) { inSize += mInitialTagDepth; for ( PxU32 idx =0; idx < inSize; ++idx ) mStream << "\t"; } void beginTag( const char* inTagname ) { closeTag(); writeTabs(mTags.size()); mTags.pushBack( inTagname ); mStream << "<" << inTagname; mTagOpen = true; } void addAttribute( const char* inName, const char* inValue ) { PX_ASSERT( mTagOpen ); mStream << " " << inName << "=" << "\"" << inValue << "\""; } void closeTag(bool useNewline = true) { if ( mTagOpen ) { mStream << " " << ">"; if (useNewline ) mStream << "\n"; } mTagOpen = false; } void doEndOpenTag() { mStream << "</" << mTags.back() << ">" << "\n"; } void endTag() { PX_ASSERT( mTags.size() ); if ( mTagOpen ) mStream << " " << "/>" << "\n"; else { writeTabs(mTags.size()-1); doEndOpenTag(); } mTagOpen = false; mTags.popBack(); } static bool IsNormalizableWhitespace(char c) { return c == 0x9 || c == 0xA || c == 0xD; } static bool IsValidXmlCharacter(char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } void addContent( const char* inContent ) { closeTag(false); //escape xml for( ; *inContent; inContent++ ) { switch (*inContent) { case '<': mStream << "&lt;"; break; case '>': mStream << "&gt;"; break; case '&': mStream << "&amp;"; break; case '\'': mStream << "&apos;"; break; case '"': mStream << "&quot;"; break; default: if (IsValidXmlCharacter(*inContent)) { if (IsNormalizableWhitespace(*inContent)) { char s[32]; Pxsnprintf(s, 32, "&#x%02X;", unsigned(*inContent)); mStream << s; } else mStream << *inContent; } break; } } } void writeContentTag( const char* inTag, const char* inContent ) { beginTag( inTag ); addContent( inContent ); doEndOpenTag(); mTags.popBack(); } void insertXml( const char* inXml ) { closeTag(); mStream << inXml; } }; struct BeginTag { const char* mTagName; BeginTag( const char* inTagName ) : mTagName( inTagName ) { } }; struct EndTag { EndTag() {} }; struct Att { const char* mAttName; const char* mAttValue; Att( const char* inAttName, const char* inAttValue ) : mAttName( inAttName ) , mAttValue( inAttValue ) { } }; struct Content { const char* mContent; Content( const char* inContent ) : mContent( inContent ) { } }; struct ContentTag { const char* mTagName; const char* mContent; ContentTag( const char* inTagName, const char* inContent ) : mTagName( inTagName ) , mContent( inContent ) { } }; inline SimpleXmlWriter& operator<<( SimpleXmlWriter& inWriter, const BeginTag& inTag ) { inWriter.beginTag( inTag.mTagName ); return inWriter; } inline SimpleXmlWriter& operator<<( SimpleXmlWriter& inWriter, const EndTag& inTag ) { PX_UNUSED(inTag); inWriter.endTag(); return inWriter; } inline SimpleXmlWriter& operator<<( SimpleXmlWriter& inWriter, const Att& inTag ) { inWriter.addAttribute(inTag.mAttName, inTag.mAttValue); return inWriter; } inline SimpleXmlWriter& operator<<( SimpleXmlWriter& inWriter, const Content& inTag ) { inWriter.addContent(inTag.mContent); return inWriter; } inline SimpleXmlWriter& operator<<( SimpleXmlWriter& inWriter, const ContentTag& inTag ) { inWriter.writeContentTag(inTag.mTagName, inTag.mContent); return inWriter; } inline void writeProperty( SimpleXmlWriter& inWriter, MemoryBuffer& tempBuffer, const char* inPropName ) { PxU8 data = 0; tempBuffer.write( &data, sizeof(PxU8) ); inWriter.writeContentTag( inPropName, reinterpret_cast<const char*>( tempBuffer.mBuffer ) ); tempBuffer.clear(); } template<typename TDataType> inline void writeProperty( SimpleXmlWriter& inWriter, MemoryBuffer& tempBuffer, const char* inPropName, TDataType inValue ) { tempBuffer << inValue; writeProperty( inWriter, tempBuffer, inPropName ); } } } #endif
7,602
C
28.583657
168
0.677585
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepXUpgrader.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_REPX_UPGRADER_H #define SN_REPX_UPGRADER_H #include "foundation/PxSimpleTypes.h" namespace physx { namespace Sn { class RepXCollection; class RepXUpgrader { public: //If a new collection is created, the source collection is destroyed. //Thus you only need to release the new collection. //This holds for all of the upgrade functions. //So be aware, that the argument to these functions may not be valid //after they are called, but the return value always will be valid. static RepXCollection& upgradeCollection( RepXCollection& src ); static RepXCollection& upgrade10CollectionTo3_1Collection( RepXCollection& src ); static RepXCollection& upgrade3_1CollectionTo3_2Collection( RepXCollection& src ); static RepXCollection& upgrade3_2CollectionTo3_3Collection( RepXCollection& src ); static RepXCollection& upgrade3_3CollectionTo3_4Collection( RepXCollection& src ); static RepXCollection& upgrade3_4CollectionTo4_0Collection( RepXCollection& src ); }; } } #endif
2,704
C
48.181817
84
0.77145
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlVisitorReader.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_VISITOR_READER_H #define SN_XML_VISITOR_READER_H #include "foundation/PxArray.h" #include "foundation/PxUtilities.h" #include "RepXMetaDataPropertyVisitor.h" #include "SnPxStreamOperators.h" #include "SnXmlMemoryPoolStreams.h" #include "SnXmlReader.h" #include "SnXmlImpl.h" #include "SnXmlMemoryAllocator.h" #include "SnXmlStringToType.h" namespace physx { namespace Sn { inline PxU32 findEnumByName( const char* inName, const PxU32ToName* inTable ) { for ( PxU32 idx = 0; inTable[idx].mName != NULL; ++idx ) { if ( physx::Pxstricmp( inTable[idx].mName, inName ) == 0 ) return inTable[idx].mValue; } return 0; } PX_INLINE void stringToFlagsType( const char* strData, XmlMemoryAllocator& alloc, PxU32& ioType, const PxU32ToName* inTable ) { if ( inTable == NULL ) return; ioType = 0; if ( strData && *strData) { //Destructively parse the string to get out the different flags. char* theValue = const_cast<char*>( copyStr( &alloc, strData ) ); char* theMarker = theValue; char* theNext = theValue; while( theNext && *theNext ) { ++theNext; if( *theNext == '|' ) { *theNext = 0; ++theNext; ioType |= static_cast< PxU32 > ( findEnumByName( theMarker, inTable ) ); theMarker = theNext; } } if ( theMarker && *theMarker ) ioType |= static_cast< PxU32 > ( findEnumByName( theMarker, inTable ) ); alloc.deallocate( reinterpret_cast<PxU8*>( theValue ) ); } } template<typename TDataType> PX_INLINE void stringToEnumType( const char* strData, TDataType& ioType, const PxU32ToName* inTable ) { ioType = static_cast<TDataType>( findEnumByName( strData, inTable ) ); } template<typename TDataType> PX_INLINE bool readProperty( XmlReader& inReader, const char* pname, TDataType& ioType ) { const char* value; if ( inReader.read( pname, value ) ) { stringToType( value, ioType ); return true; } return false; } template<typename TObjType> inline TObjType* findReferencedObject( PxCollection& collection, PxSerialObjectId id) { PX_ASSERT(id > 0); TObjType* outObject = static_cast<TObjType*>(const_cast<PxBase*>(collection.find(id))); if (outObject == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxSerialization::createCollectionFromXml: " "Reference to ID %d cannot be resolved. Make sure externalRefs collection is specified if required and " "check Xml file for completeness.", id); } return outObject; } template<typename TObjType> inline bool readReference( XmlReader& inReader, PxCollection& collection, TObjType*& outObject ) { PxSerialObjectId theId; const char* theValue = inReader.getCurrentItemValue(); strto( theId, theValue ); if( theId == 0) { // the NULL pointer is a valid pointer if the input id is 0 outObject = NULL; return true; } else { outObject = findReferencedObject<TObjType>(collection, theId); return outObject != NULL; } } template<typename TObjType> inline bool readReference( XmlReader& inReader, PxCollection& inCollection, const char* pname, TObjType*& outObject ) { outObject = NULL; PxSerialObjectId theId = 0; if (readProperty ( inReader, pname, theId ) && theId ) { outObject = findReferencedObject<TObjType>(inCollection, theId); } // the NULL pointer is a valid pointer if the input id is 0 return (outObject != NULL) || 0 == theId; } template<typename TEnumType, typename TStorageType> inline bool readFlagsProperty( XmlReader& reader, XmlMemoryAllocator& allocator, const char* pname, const PxU32ToName* inConversions, PxFlags<TEnumType,TStorageType>& outFlags ) { const char* value; if ( reader.read( pname, value ) ) { PxU32 tempValue = 0; stringToFlagsType( value, allocator, tempValue, inConversions ); outFlags = PxFlags<TEnumType,TStorageType>(PxTo16(tempValue) ); return true; } return false; } template<typename TObjType, typename TReaderType, typename TInfoType> inline void readComplexObj( TReaderType& oldVisitor, TObjType* inObj, TInfoType& info); template<typename TObjType, typename TReaderType> inline void readComplexObj( TReaderType& oldVisitor, TObjType* inObj); template<typename TReaderType, typename TGeomType> inline PxGeometry* parseGeometry( TReaderType& reader, TGeomType& /*inGeom*/) { PxAllocatorCallback& inAllocator = reader.mAllocator.getAllocator(); TGeomType* shape = PX_PLACEMENT_NEW((inAllocator.allocate(sizeof(TGeomType), "parseGeometry", PX_FL)), TGeomType); PxClassInfoTraits<TGeomType> info; readComplexObj( reader, shape); return shape; } template<typename TReaderType> inline void parseShape( TReaderType& visitor, PxGeometry*& outResult, PxArray<PxMaterial*>& outMaterials) { XmlReader& theReader( visitor.mReader ); PxCollection& collection = visitor.mCollection; visitor.pushCurrentContext(); if ( visitor.gotoTopName() ) { visitor.pushCurrentContext(); if ( visitor.gotoChild( "Materials" ) ) { for( bool matSuccess = visitor.gotoFirstChild(); matSuccess; matSuccess = visitor.gotoNextSibling() ) { PxMaterial* material = NULL; if(!readReference<PxMaterial>( theReader, collection, material )) visitor.mHadError = true; if ( material ) outMaterials.pushBack( material ); } } visitor.popCurrentContext(); visitor.pushCurrentContext(); PxPlaneGeometry plane; PxHeightFieldGeometry heightField; PxSphereGeometry sphere; PxTriangleMeshGeometry mesh; PxConvexMeshGeometry convex; PxBoxGeometry box; PxCapsuleGeometry capsule; if ( visitor.gotoChild( "Geometry" ) ) { if ( visitor.gotoFirstChild() ) { const char* geomTypeName = visitor.getCurrentItemName(); if ( physx::Pxstricmp( geomTypeName, "PxSphereGeometry" ) == 0 ) outResult = parseGeometry(visitor, sphere); else if ( physx::Pxstricmp( geomTypeName, "PxPlaneGeometry" ) == 0 ) outResult = parseGeometry(visitor, plane); else if ( physx::Pxstricmp( geomTypeName, "PxCapsuleGeometry" ) == 0 ) outResult = parseGeometry(visitor, capsule); else if ( physx::Pxstricmp( geomTypeName, "PxBoxGeometry" ) == 0 ) outResult = parseGeometry(visitor, box); else if ( physx::Pxstricmp( geomTypeName, "PxConvexMeshGeometry" ) == 0 ) outResult = parseGeometry(visitor, convex); else if ( physx::Pxstricmp( geomTypeName, "PxTriangleMeshGeometry" ) == 0 ) outResult = parseGeometry(visitor, mesh); else if ( physx::Pxstricmp( geomTypeName, "PxHeightFieldGeometry" ) == 0 ) outResult = parseGeometry(visitor, heightField); else PX_ASSERT( false ); } } visitor.popCurrentContext(); } visitor.popCurrentContext(); return; } template<typename TReaderType, typename TObjType> inline void readShapesProperty( TReaderType& visitor, TObjType* inObj, const PxRigidActorShapeCollection* inProp = NULL, bool isSharedShape = false ) { PX_UNUSED(isSharedShape); PX_UNUSED(inProp); XmlReader& theReader( visitor.mReader ); PxCollection& collection( visitor.mCollection ); visitor.pushCurrentContext(); if ( visitor.gotoTopName() ) { //uggh working around the shape collection api. //read out materials and geometry for ( bool success = visitor.gotoFirstChild(); success; success = visitor.gotoNextSibling() ) { if( 0 == physx::Pxstricmp( visitor.getCurrentItemName(), "PxShapeRef" ) ) { PxShape* shape = NULL; if(!readReference<PxShape>( theReader, collection, shape )) visitor.mHadError = true; if(shape) inObj->attachShape( *shape ); } else { PxArray<PxMaterial*> materials; PxGeometry* geometry = NULL; parseShape( visitor, geometry, materials); PxShape* theShape = NULL; if ( materials.size() ) { theShape = visitor.mArgs.physics.createShape( *geometry, materials.begin(), PxTo16(materials.size()), true ); if ( theShape ) { readComplexObj( visitor, theShape ); if(theShape) { inObj->attachShape(*theShape); collection.add( *theShape ); } } } switch(geometry->getType()) { case PxGeometryType::eSPHERE : static_cast<PxSphereGeometry*>(geometry)->~PxSphereGeometry(); break; case PxGeometryType::ePLANE : static_cast<PxPlaneGeometry*>(geometry)->~PxPlaneGeometry(); break; case PxGeometryType::eCAPSULE : static_cast<PxCapsuleGeometry*>(geometry)->~PxCapsuleGeometry(); break; case PxGeometryType::eBOX : static_cast<PxBoxGeometry*>(geometry)->~PxBoxGeometry(); break; case PxGeometryType::eCONVEXMESH : static_cast<PxConvexMeshGeometry*>(geometry)->~PxConvexMeshGeometry(); break; case PxGeometryType::eTRIANGLEMESH : static_cast<PxTriangleMeshGeometry*>(geometry)->~PxTriangleMeshGeometry(); break; case PxGeometryType::eHEIGHTFIELD : static_cast<PxHeightFieldGeometry*>(geometry)->~PxHeightFieldGeometry(); break; case PxGeometryType::eTETRAHEDRONMESH : static_cast<PxTetrahedronMeshGeometry*>(geometry)->~PxTetrahedronMeshGeometry(); break; case PxGeometryType::ePARTICLESYSTEM: static_cast<PxParticleSystemGeometry*>(geometry)->~PxParticleSystemGeometry(); break; case PxGeometryType::eHAIRSYSTEM: static_cast<PxHairSystemGeometry*>(geometry)->~PxHairSystemGeometry(); break; case PxGeometryType::eCUSTOM : static_cast<PxCustomGeometry*>(geometry)->~PxCustomGeometry(); break; case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: PX_ASSERT(0); } visitor.mAllocator.getAllocator().deallocate(geometry); } } } visitor.popCurrentContext(); } struct ReaderNameStackEntry : NameStackEntry { bool mValid; ReaderNameStackEntry( const char* nm, bool valid ) : NameStackEntry(nm), mValid(valid) {} }; typedef PxProfileArray<ReaderNameStackEntry> TReaderNameStack; template<typename TObjType> struct RepXVisitorReaderBase { protected: RepXVisitorReaderBase<TObjType>& operator=(const RepXVisitorReaderBase<TObjType>&); public: TReaderNameStack& mNames; PxProfileArray<PxU32>& mContexts; PxRepXInstantiationArgs mArgs; XmlReader& mReader; TObjType* mObj; XmlMemoryAllocator& mAllocator; PxCollection& mCollection; bool mValid; bool& mHadError; RepXVisitorReaderBase( TReaderNameStack& names, PxProfileArray<PxU32>& contexts, const PxRepXInstantiationArgs& args, XmlReader& reader, TObjType* obj , XmlMemoryAllocator& alloc, PxCollection& collection, bool& hadError ) : mNames( names ) , mContexts( contexts ) , mArgs( args ) , mReader( reader ) , mObj( obj ) , mAllocator( alloc ) , mCollection( collection ) , mValid( true ) , mHadError(hadError) { } RepXVisitorReaderBase( const RepXVisitorReaderBase& other ) : mNames( other.mNames ) , mContexts( other.mContexts ) , mArgs( other.mArgs ) , mReader( other.mReader ) , mObj( other.mObj ) , mAllocator( other.mAllocator ) , mCollection( other.mCollection ) , mValid( other.mValid ) , mHadError( other.mHadError ) { } void pushName( const char* name ) { gotoTopName(); mNames.pushBack( ReaderNameStackEntry( name, mValid ) ); } void pushBracketedName( const char* name ) { pushName( name ); } void popName() { if ( mNames.size() ) { if ( mNames.back().mOpen && mNames.back().mValid ) mReader.leaveChild(); mNames.popBack(); } mValid =true; if ( mNames.size() && mNames.back().mValid == false ) mValid = false; } void pushCurrentContext() { mContexts.pushBack( static_cast<PxU32>( mNames.size() ) ); } void popCurrentContext() { if ( mContexts.size() ) { PxU32 depth = mContexts.back(); PX_ASSERT( mNames.size() >= depth ); while( mNames.size() > depth ) popName(); mContexts.popBack(); } } bool updateLastEntryAfterOpen() { mNames.back().mValid = mValid; mNames.back().mOpen = mValid; return mValid; } bool gotoTopName() { if ( mNames.size() && mNames.back().mOpen == false ) { if ( mValid ) mValid = mReader.gotoChild( mNames.back().mName ); updateLastEntryAfterOpen(); } return mValid; } bool isValid() const { return mValid; } bool gotoChild( const char* name ) { pushName( name ); return gotoTopName(); } bool gotoFirstChild() { pushName( "__child" ); if ( mValid ) mValid = mReader.gotoFirstChild(); return updateLastEntryAfterOpen(); } bool gotoNextSibling() { bool retval = mValid; if ( mValid ) retval = mReader.gotoNextSibling(); return retval; } const char* getCurrentItemName() { if (mValid ) return mReader.getCurrentItemName(); return ""; } const char* topName() const { if ( mNames.size() ) return mNames.back().mName; PX_ASSERT( false ); return "bad__repx__name"; } const char* getCurrentValue() { const char* value = NULL; if ( isValid() && mReader.read( topName(), value ) ) return value; return NULL; } template<typename TDataType> bool readProperty(TDataType& outType) { const char* value = getCurrentValue(); if ( value && *value ) { stringToType( value, outType ); return true; } return false; } template<typename TDataType> bool readExtendedIndexProperty(TDataType& outType) { const char* value = mReader.getCurrentItemValue(); if ( value && *value ) { stringToType( value, outType ); return true; } return false; } template<typename TRefType> bool readReference(TRefType*& outRef) { return physx::Sn::readReference<TRefType>( mReader, mCollection, topName(), outRef ); } inline bool readProperty(const char*& outProp ) { outProp = ""; const char* value = getCurrentValue(); if ( value && *value && mArgs.stringTable ) { outProp = mArgs.stringTable->allocateStr( value ); return true; } return false; } inline bool readProperty(PxConvexMesh*& outProp ) { return readReference<PxConvexMesh>( outProp ); } inline bool readProperty(PxTriangleMesh*& outProp ) { return readReference<PxTriangleMesh>( outProp ); } inline bool readProperty(PxBVH33TriangleMesh*& outProp ) { return readReference<PxBVH33TriangleMesh>( outProp ); } inline bool readProperty(PxBVH34TriangleMesh*& outProp ) { return readReference<PxBVH34TriangleMesh>( outProp ); } inline bool readProperty(PxHeightField*& outProp ) { return readReference<PxHeightField>( outProp ); } inline bool readProperty( PxRigidActor *& outProp ) { return readReference<PxRigidActor>( outProp ); } template<typename TAccessorType> void simpleProperty( PxU32 /*key*/, TAccessorType& inProp ) { typedef typename TAccessorType::prop_type TPropertyType; TPropertyType value; if ( readProperty( value ) ) inProp.set( mObj, value ); } template<typename TAccessorType> void enumProperty( PxU32 /*key*/, TAccessorType& inProp, const PxU32ToName* inConversions ) { typedef typename TAccessorType::prop_type TPropertyType; const char* strVal = getCurrentValue(); if ( strVal && *strVal ) { TPropertyType pval; stringToEnumType( strVal, pval, inConversions ); inProp.set( mObj, pval ); } } template<typename TAccessorType> void flagsProperty( PxU32 /*key*/, const TAccessorType& inProp, const PxU32ToName* inConversions ) { typedef typename TAccessorType::prop_type TPropertyType; typedef typename TPropertyType::InternalType TInternalType; const char* strVal = getCurrentValue(); if ( strVal && *strVal ) { PxU32 tempValue = 0; stringToFlagsType( strVal, mAllocator, tempValue, inConversions ); inProp.set( mObj, TPropertyType(TInternalType( tempValue ))); } } template<typename TAccessorType, typename TInfoType> void complexProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo ) { typedef typename TAccessorType::prop_type TPropertyType; if ( gotoTopName() ) { TPropertyType propVal = inProp.get( mObj ); readComplexObj( *this, &propVal, inInfo ); inProp.set( mObj, propVal ); } } template<typename TAccessorType, typename TInfoType> void bufferCollectionProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo ) { typedef typename TAccessorType::prop_type TPropertyType; PxInlineArray<TPropertyType,5> theData; this->pushCurrentContext(); if ( this->gotoTopName() ) { for ( bool success = this->gotoFirstChild(); success; success = this->gotoNextSibling() ) { TPropertyType propVal; readComplexObj( *this, &propVal, inInfo ); theData.pushBack(propVal); } } this->popCurrentContext(); inProp.set( mObj, theData.begin(), theData.size() ); } template<typename TAccessorType, typename TInfoType> void extendedIndexedProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo ) { typedef typename TAccessorType::prop_type TPropertyType; this->pushCurrentContext(); if ( this->gotoTopName() ) { PxU32 index = 0; for ( bool success = this->gotoFirstChild(); success; success = this->gotoNextSibling() ) { TPropertyType propVal; readComplexObj( *this, &propVal, inInfo ); inProp.set(mObj, index, propVal); ++index; } } this->popCurrentContext(); } template<typename TAccessorType, typename TInfoType> void PxFixedSizeLookupTableProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo ) { typedef typename TAccessorType::prop_type TPropertyType; const_cast<TAccessorType&>(inProp).clear( mObj ); this->pushCurrentContext(); if ( this->gotoTopName() ) { for ( bool success = this->gotoFirstChild(); success; success = this->gotoNextSibling() ) { TPropertyType propXVal; readComplexObj( *this, &propXVal, inInfo ); if(this->gotoNextSibling()) { TPropertyType propYVal; readComplexObj( *this, &propYVal, inInfo ); const_cast<TAccessorType&>(inProp).addPair(mObj, propXVal, propYVal); } } } this->popCurrentContext(); } void handleShapes( const PxRigidActorShapeCollection& inProp ) { physx::Sn::readShapesProperty( *this, mObj, &inProp ); } void handleRigidActorGlobalPose(const PxRigidActorGlobalPosePropertyInfo& inProp) { PxArticulationLink* link = mObj->template is<PxArticulationLink>(); bool isReducedCoordinateLink = (link != NULL); if (!isReducedCoordinateLink) { PxRepXPropertyAccessor<PxPropertyInfoName::PxRigidActor_GlobalPose, PxRigidActor, const PxTransform &, PxTransform> theAccessor(inProp); simpleProperty(PxPropertyInfoName::PxRigidActor_GlobalPose, theAccessor); } } }; template<typename TObjType> struct RepXVisitorReader : public RepXVisitorReaderBase<TObjType> { RepXVisitorReader( TReaderNameStack& names, PxProfileArray<PxU32>& contexts, const PxRepXInstantiationArgs& args, XmlReader& reader, TObjType* obj , XmlMemoryAllocator& alloc, PxCollection& collection, bool& ret) : RepXVisitorReaderBase<TObjType>( names, contexts, args, reader, obj, alloc, collection, ret) { } RepXVisitorReader( const RepXVisitorReader<TObjType>& other ) : RepXVisitorReaderBase<TObjType>( other ) { } }; // Specialized template to load dynamic rigid, to determine the kinematic state first template<> struct RepXVisitorReader<PxRigidDynamic> : public RepXVisitorReaderBase<PxRigidDynamic> { RepXVisitorReader( TReaderNameStack& names, PxProfileArray<PxU32>& contexts, const PxRepXInstantiationArgs& args, XmlReader& reader, PxRigidDynamic* obj , XmlMemoryAllocator& alloc, PxCollection& collection, bool& ret) : RepXVisitorReaderBase<PxRigidDynamic>( names, contexts, args, reader, obj, alloc, collection, ret) { } RepXVisitorReader( const RepXVisitorReader<PxRigidDynamic>& other ) : RepXVisitorReaderBase<PxRigidDynamic>( other ) { } void handleShapes( const PxRigidActorShapeCollection& inProp ) { // Need to read the parental actor to check if actor is kinematic // in that case we need to apply the kinematic flag before a shape is set XmlReaderWriter* parentReader = static_cast<XmlReaderWriter*>(mReader.getParentReader()); if(mObj) { const char* value; if (parentReader->read( "RigidBodyFlags", value )) { if(strstr(value, "eKINEMATIC")) { mObj->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); } } } physx::Sn::readShapesProperty( *this, mObj, &inProp ); parentReader->release(); } template<typename TAccessorType> void simpleProperty( PxU32 /*key*/, TAccessorType& inProp ) { typedef typename TAccessorType::prop_type TPropertyType; TPropertyType value; if (readProperty(value)) { // If the rigid body is kinematic, we cannot set the LinearVelocity or AngularVelocity const bool kinematic = (mObj->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC); if(kinematic && (inProp.mProperty.mKey == PxPropertyInfoName::PxRigidDynamic_LinearVelocity || inProp.mProperty.mKey == PxPropertyInfoName::PxRigidDynamic_AngularVelocity)) return; inProp.set(mObj, value ); } } private: RepXVisitorReader<PxRigidDynamic>& operator=(const RepXVisitorReader<PxRigidDynamic>&); }; template<> struct RepXVisitorReader<PxShape> : public RepXVisitorReaderBase<PxShape> { RepXVisitorReader( TReaderNameStack& names, PxProfileArray<PxU32>& contexts, const PxRepXInstantiationArgs& args, XmlReader& reader, PxShape* obj , XmlMemoryAllocator& alloc, PxCollection& collection, bool& ret ) : RepXVisitorReaderBase<PxShape>( names, contexts, args, reader, obj, alloc, collection, ret ) { } RepXVisitorReader( const RepXVisitorReader<PxShape>& other ) : RepXVisitorReaderBase<PxShape>( other ) { } void handleShapeMaterials( const PxShapeMaterialsProperty& ) //these were handled during construction. { } void handleGeomProperty( const PxShapeGeomProperty& ) { } private: RepXVisitorReader<PxShape>& operator=(const RepXVisitorReader<PxShape>&); }; template<> struct RepXVisitorReader<PxArticulationLink> : public RepXVisitorReaderBase<PxArticulationLink> { RepXVisitorReader( TReaderNameStack& names, PxProfileArray<PxU32>& contexts, const PxRepXInstantiationArgs& args, XmlReader& reader, PxArticulationLink* obj , XmlMemoryAllocator& alloc, PxCollection& collection, bool& ret ) : RepXVisitorReaderBase<PxArticulationLink>( names, contexts, args, reader, obj, alloc, collection, ret ) { } RepXVisitorReader( const RepXVisitorReader<PxArticulationLink>& other ) : RepXVisitorReaderBase<PxArticulationLink>( other ) { } void handleIncomingJoint( const TIncomingJointPropType& prop ) { pushName( "Joint" ); if ( gotoTopName() ) { PxArticulationJointReducedCoordinate* theJoint = static_cast<PxArticulationJointReducedCoordinate*>((prop.get(mObj))); readComplexObj(*this, theJoint); //Add joint to PxCollection, since PxArticulation requires PxArticulationLink and joint. mCollection.add(*theJoint); } popName(); } private: RepXVisitorReader<PxArticulationLink>& operator=(const RepXVisitorReader<PxArticulationLink>&); }; template<typename ArticulationType> inline void readProperty( RepXVisitorReaderBase<ArticulationType>& inSerializer, ArticulationType* inObj, const PxArticulationLinkCollectionProp&) { PxProfileAllocatorWrapper theWrapper( inSerializer.mAllocator.getAllocator() ); PxCollection& collection( inSerializer.mCollection ); TArticulationLinkLinkMap linkRemapMap( theWrapper ); inSerializer.pushCurrentContext(); if( inSerializer.gotoTopName() ) { for ( bool links = inSerializer.gotoFirstChild(); links != false; links = inSerializer.gotoNextSibling() ) { //Need enough information to create the link... PxSerialObjectId theParentPtr = 0; const PxArticulationLink* theParentLink = NULL; if ( inSerializer.mReader.read( "Parent", theParentPtr ) ) { const TArticulationLinkLinkMap::Entry* theRemappedParent( linkRemapMap.find( theParentPtr ) ); //If we have a valid at write time, we had better have a valid parent at read time. PX_ASSERT( theRemappedParent ); theParentLink = theRemappedParent->second; } PxArticulationLink* newLink = inObj->createLink( const_cast<PxArticulationLink*>( theParentLink ), PxTransform(PxIdentity) ); PxSerialObjectId theIdPtr = 0; inSerializer.mReader.read( "Id", theIdPtr ); linkRemapMap.insert( theIdPtr, newLink ); readComplexObj( inSerializer, newLink ); //Add link to PxCollection, since PxArticulation requires PxArticulationLink and joint. collection.add( *newLink, theIdPtr ); } } inSerializer.popCurrentContext(); } template<> struct RepXVisitorReader<PxArticulationReducedCoordinate> : public RepXVisitorReaderBase<PxArticulationReducedCoordinate> { RepXVisitorReader(TReaderNameStack& names, PxProfileArray<PxU32>& contexts, const PxRepXInstantiationArgs& args, XmlReader& reader, PxArticulationReducedCoordinate* obj , XmlMemoryAllocator& alloc, PxCollection& collection, bool& ret) : RepXVisitorReaderBase<PxArticulationReducedCoordinate>(names, contexts, args, reader, obj, alloc, collection, ret) {} RepXVisitorReader(const RepXVisitorReader<PxArticulationReducedCoordinate>& other) : RepXVisitorReaderBase<PxArticulationReducedCoordinate>(other) {} void handleArticulationLinks(const PxArticulationLinkCollectionProp& inProp) { physx::Sn::readProperty(*this, mObj, inProp); } }; template<typename TObjType, typename TInfoType> inline bool readAllProperties( PxRepXInstantiationArgs args, TReaderNameStack& names, PxProfileArray<PxU32>& contexts, XmlReader& reader, TObjType* obj, XmlMemoryAllocator& alloc, PxCollection& collection, TInfoType& info ) { bool hadError = false; RepXVisitorReader<TObjType> theReader( names, contexts, args, reader, obj, alloc, collection, hadError); RepXPropertyFilter<RepXVisitorReader<TObjType> > theOp( theReader ); info.visitBaseProperties( theOp ); info.visitInstanceProperties( theOp ); return !hadError; } template<typename TObjType> inline bool readAllProperties( PxRepXInstantiationArgs args, XmlReader& reader, TObjType* obj, XmlMemoryAllocator& alloc, PxCollection& collection ) { PxProfileAllocatorWrapper wrapper( alloc.getAllocator() ); TReaderNameStack names( wrapper ); PxProfileArray<PxU32> contexts( wrapper ); PxClassInfoTraits<TObjType> info; return readAllProperties( args, names, contexts, reader, obj, alloc, collection, info.Info ); } template<typename TObjType, typename TReaderType, typename TInfoType> inline void readComplexObj( TReaderType& oldVisitor, TObjType* inObj, TInfoType& info) { if(!readAllProperties( oldVisitor.mArgs, oldVisitor.mNames, oldVisitor.mContexts, oldVisitor.mReader, inObj, oldVisitor.mAllocator, oldVisitor.mCollection, info )) oldVisitor.mHadError = true; } template<typename TObjType, typename TReaderType, typename TInfoType> inline void readComplexObj( TReaderType& oldVisitor, TObjType* inObj, const TInfoType& info) { if(!readAllProperties( oldVisitor.mArgs, oldVisitor.mNames, oldVisitor.mContexts, oldVisitor.mReader, inObj, oldVisitor.mAllocator, oldVisitor.mCollection, info )) oldVisitor.mHadError = true; } template<typename TObjType, typename TReaderType> inline void readComplexObj( TReaderType& oldVisitor, TObjType* inObj, const PxUnknownClassInfo& /*info*/) { const char* value = oldVisitor.mReader.getCurrentItemValue(); if ( value && *value ) { stringToType( value, *inObj ); return; } oldVisitor.mHadError = true; } template<typename TObjType, typename TReaderType> inline void readComplexObj( TReaderType& oldVisitor, TObjType* inObj) { PxClassInfoTraits<TObjType> info; if(!readAllProperties( oldVisitor.mArgs, oldVisitor.mNames, oldVisitor.mContexts, oldVisitor.mReader, inObj, oldVisitor.mAllocator, oldVisitor.mCollection, info.Info )) oldVisitor.mHadError = true; } } } #endif
30,176
C
32.016411
224
0.710101
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlMemoryPoolStreams.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_MEMORY_POOL_STREAMS_H #define SN_XML_MEMORY_POOL_STREAMS_H #include "foundation/PxTransform.h" #include "foundation/PxIO.h" #include "SnXmlMemoryPool.h" namespace physx { template<typename TDataType> struct XmlDefaultValue { bool force_compile_error; }; #define XML_DEFINE_DEFAULT_VALUE(type, defVal ) \ template<> \ struct XmlDefaultValue<type> \ { \ type getDefaultValue() { return type(defVal); } \ }; XML_DEFINE_DEFAULT_VALUE(PxU8, 0) XML_DEFINE_DEFAULT_VALUE(PxI8, 0) XML_DEFINE_DEFAULT_VALUE(PxU16, 0) XML_DEFINE_DEFAULT_VALUE(PxI16, 0) XML_DEFINE_DEFAULT_VALUE(PxU32, 0) XML_DEFINE_DEFAULT_VALUE(PxI32, 0) XML_DEFINE_DEFAULT_VALUE(PxU64, 0) XML_DEFINE_DEFAULT_VALUE(PxI64, 0) XML_DEFINE_DEFAULT_VALUE(PxF32, 0) XML_DEFINE_DEFAULT_VALUE(PxF64, 0) #undef XML_DEFINE_DEFAULT_VALUE template<> struct XmlDefaultValue<PxVec3> { PxVec3 getDefaultValue() { return PxVec3( 0,0,0 ); } }; template<> struct XmlDefaultValue<PxTransform> { PxTransform getDefaultValue() { return PxTransform(PxIdentity); } }; template<> struct XmlDefaultValue<PxQuat> { PxQuat getDefaultValue() { return PxQuat(PxIdentity); } }; /** * Mapping of PxOutputStream to a memory pool manager. * Allows write-then-read semantics of a set of * data. Can safely write up to 4GB of data; then you * will silently fail... */ template<typename TAllocatorType> struct MemoryBufferBase : public PxOutputStream, public PxInputStream { TAllocatorType* mManager; mutable PxU32 mWriteOffset; mutable PxU32 mReadOffset; PxU8* mBuffer; PxU32 mCapacity; MemoryBufferBase( TAllocatorType* inManager ) : mManager( inManager ) , mWriteOffset( 0 ) , mReadOffset( 0 ) , mBuffer( NULL ) , mCapacity( 0 ) { } virtual ~MemoryBufferBase() { mManager->deallocate( mBuffer ); } PxU8* releaseBuffer() { clear(); mCapacity = 0; PxU8* retval(mBuffer); mBuffer = NULL; return retval; } void clear() { mWriteOffset = mReadOffset = 0; } virtual PxU32 read(void* dest, PxU32 count) { bool fits = ( mReadOffset + count ) <= mWriteOffset; PX_ASSERT( fits ); if ( fits ) { PxMemCopy( dest, mBuffer + mReadOffset, count ); mReadOffset += count; return count; } return 0; } inline void checkCapacity( PxU32 inNewCapacity ) { if ( mCapacity < inNewCapacity ) { PxU32 newCapacity = 32; while( newCapacity < inNewCapacity ) newCapacity = newCapacity << 1; PxU8* newData( mManager->allocate( newCapacity ) ); if ( mWriteOffset ) PxMemCopy( newData, mBuffer, mWriteOffset ); mManager->deallocate( mBuffer ); mBuffer = newData; mCapacity = newCapacity; } } virtual PxU32 write(const void* src, PxU32 count) { checkCapacity( mWriteOffset + count ); PxMemCopy( mBuffer + mWriteOffset, src, count ); mWriteOffset += count; return count; } }; class MemoryBuffer : public MemoryBufferBase<CMemoryPoolManager > { public: MemoryBuffer( CMemoryPoolManager* inManager ) : MemoryBufferBase<CMemoryPoolManager >( inManager ) {} }; } #endif
4,874
C
27.179191
102
0.707838
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepX3_1Defaults.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Length", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Mass", "1000" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Speed", "10" ) DEFINE_REPX_DEFAULT_PROPERTY("PxBoxGeometry.HalfExtents", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphereGeometry.Radius", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.Scale.Scale", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.Scale.Rotation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.ConvexMesh", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.Scale.Scale", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.Scale.Rotation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.MeshFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.TriangleMesh", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightField", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.RowScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.ColumnScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightFieldFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DynamicFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.StaticFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DynamicFrictionV", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.StaticFrictionV", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DirOfAnisotropy", "1 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.FrictionCombineMode", "eAVERAGE" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.RestitutionCombineMode", "eAVERAGE" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.LocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.SimulationFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.QueryFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.ContactOffset", "0.02" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.RestOffset", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.Flags", "eSIMULATION_SHAPE|eSCENE_QUERY_SHAPE|eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.CMassLocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.Mass", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.MassSpaceInertiaTensor", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.LinearVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.AngularVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.LinearDamping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.AngularDamping", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.MaxAngularVelocity", "7" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SleepThreshold", "0.005" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SolverIterationCounts.minPositionIters", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SolverIterationCounts.minVelocityIters", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ContactReportThreshold", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.RigidDynamicFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ParentPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ChildPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TargetOrientation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TargetVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.InternalCompliance", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ExternalCompliance", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimit.yLimit", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimit.zLimit", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TangentialSpring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TangentialDamping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimitContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimitEnabled", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimit.lower", "-0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimit.upper", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimitEnabled", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimitContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.CMassLocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.Mass", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.MassSpaceInertiaTensor", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.LinearVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.AngularVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.MaxProjectionIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SeparationTolerance", "0.1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.InternalDriveIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.ExternalDriveIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SolverIterationCounts.minPositionIters", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SolverIterationCounts.minVelocityIters", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SleepThreshold", "0.005" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eX", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eY", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eZ", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eTWIST", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eSWING1", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eSWING2", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Value", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Upper", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Lower", "-1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.YAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.ZAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DrivePosition", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DriveVelocity.linear", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DriveVelocity.angular", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.MinDistance", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.MaxDistance", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Tolerance", "0.025" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.DistanceJointFlags", "eMAX_DISTANCE_ENABLED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Upper", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Lower", "-1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveVelocity", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveGearRatio", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.RevoluteJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.ContactDistance", "0.01" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Upper", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Lower", "-3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.PrismaticJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.YAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.ZAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.SphericalJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.MotionConstraintScaleBias.scale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.MotionConstraintScaleBias.bias", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.ExternalAcceleration", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.DampingCoefficient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.SolverFrequency", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.SleepLinearVelocity", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("THEEND", "false" )
19,802
C
71.273722
102
0.773811
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlVisitorWriter.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_VISITOR_WRITER_H #define SN_XML_VISITOR_WRITER_H #include "foundation/PxInlineArray.h" #include "RepXMetaDataPropertyVisitor.h" #include "SnPxStreamOperators.h" #include "SnXmlMemoryPoolStreams.h" #include "SnXmlWriter.h" #include "SnXmlImpl.h" #include "foundation/PxStrideIterator.h" namespace physx { namespace Sn { template<typename TDataType> inline void writeReference( XmlWriter& writer, PxCollection& inCollection, const char* inPropName, const TDataType* inDatatype ) { const PxBase* s = static_cast<const PxBase*>( inDatatype ) ; if( inDatatype && !inCollection.contains( *const_cast<PxBase*>(s) )) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PxSerialization::serializeCollectionToXml: Reference \"%s\" could not be resolved.", inPropName); } PxSerialObjectId theId = 0; if( s ) { theId = inCollection.getId( *s ); if( theId == 0 ) theId = static_cast<uint64_t>(size_t(inDatatype)); } writer.write( inPropName, PxCreateRepXObject( inDatatype, theId ) ); } inline void writeProperty( XmlWriter& inWriter, MemoryBuffer& inBuffer, const char* inProp ) { PxU8 data = 0; inBuffer.write( &data, sizeof(PxU8) ); inWriter.write( inProp, reinterpret_cast<const char*>( inBuffer.mBuffer ) ); inBuffer.clear(); } template<typename TDataType> inline void writeProperty( XmlWriter& inWriter, PxCollection&, MemoryBuffer& inBuffer, const char* inPropName, TDataType inValue ) { inBuffer << inValue; writeProperty( inWriter, inBuffer, inPropName ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, const PxConvexMesh* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxConvexMesh* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, const PxTriangleMesh* inDatatype ) { if (inDatatype->getConcreteType() == PxConcreteType::eTRIANGLE_MESH_BVH33) { const PxBVH33TriangleMesh* dataType = inDatatype->is<PxBVH33TriangleMesh>(); writeReference(writer, inCollection, inPropName, dataType); } else if (inDatatype->getConcreteType() == PxConcreteType::eTRIANGLE_MESH_BVH34) { const PxBVH34TriangleMesh* dataType = inDatatype->is<PxBVH34TriangleMesh>(); writeReference(writer, inCollection, inPropName, dataType); } else { PX_ASSERT(0); } } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxTriangleMesh* inDatatype ) { if (inDatatype->getConcreteType() == PxConcreteType::eTRIANGLE_MESH_BVH33) { PxBVH33TriangleMesh* dataType = inDatatype->is<PxBVH33TriangleMesh>(); writeReference(writer, inCollection, inPropName, dataType); } else if (inDatatype->getConcreteType() == PxConcreteType::eTRIANGLE_MESH_BVH34) { PxBVH34TriangleMesh* dataType = inDatatype->is<PxBVH34TriangleMesh>(); writeReference(writer, inCollection, inPropName, dataType); } else { PX_ASSERT(0); } } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, const PxBVH33TriangleMesh* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxBVH33TriangleMesh* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, const PxBVH34TriangleMesh* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxBVH34TriangleMesh* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, const PxHeightField* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxHeightField* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, const PxRigidActor* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeProperty(XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxArticulationReducedCoordinate* inDatatype) { writeReference(writer, inCollection, inPropName, inDatatype); } inline void writeProperty( XmlWriter& writer, PxCollection& inCollection, MemoryBuffer& /*inBuffer*/, const char* inPropName, PxRigidActor* inDatatype ) { writeReference( writer, inCollection, inPropName, inDatatype ); } inline void writeFlagsProperty( XmlWriter& inWriter, MemoryBuffer& tempBuf, const char* inPropName, PxU32 inFlags, const PxU32ToName* inTable ) { if ( inTable ) { PxU32 flagValue( inFlags ); if ( flagValue ) { for ( PxU32 idx =0; inTable[idx].mName != NULL; ++idx ) { if ( (inTable[idx].mValue & flagValue) == inTable[idx].mValue ) { if ( tempBuf.mWriteOffset != 0 ) tempBuf << "|"; tempBuf << inTable[idx].mName; } } writeProperty( inWriter, tempBuf, inPropName ); } else { if ( tempBuf.mWriteOffset != 0 ) tempBuf << "|"; tempBuf << "0"; writeProperty( inWriter, tempBuf, inPropName ); } } } inline void writeFlagsBuffer( MemoryBuffer& tempBuf, PxU32 flagValue, const PxU32ToName* inTable ) { PX_ASSERT(inTable); bool added = false; if ( flagValue ) { for ( PxU32 item =0; inTable[item].mName != NULL; ++item ) { if ( (inTable[item].mValue & flagValue) != 0 ) { if ( added ) tempBuf << "|"; tempBuf << inTable[item].mName; added = true; } } } } inline void writePxVec3( PxOutputStream& inStream, const PxVec3& inVec ) { inStream << inVec; } template<typename TDataType> inline const TDataType& PtrAccess( const TDataType* inPtr, PxU32 inIndex ) { return inPtr[inIndex]; } template<typename TDataType> inline void BasicDatatypeWrite( PxOutputStream& inStream, const TDataType& item ) { inStream << item; } template<typename TObjType, typename TAccessOperator, typename TWriteOperator> inline void writeBuffer( XmlWriter& inWriter, MemoryBuffer& inTempBuffer , PxU32 inObjPerLine, const TObjType* inObjType, TAccessOperator inAccessOperator , PxU32 inBufSize, const char* inPropName, TWriteOperator inOperator ) { if ( inBufSize && inObjType ) { for ( PxU32 idx = 0; idx < inBufSize; ++idx ) { if ( idx && ( idx % inObjPerLine == 0 ) ) inTempBuffer << "\n\t\t\t"; else inTempBuffer << " "; inOperator( inTempBuffer, inAccessOperator( inObjType, idx ) ); } writeProperty( inWriter, inTempBuffer, inPropName ); } } template<typename TDataType, typename TAccessOperator, typename TWriteOperator> inline void writeStrideBuffer( XmlWriter& inWriter, MemoryBuffer& inTempBuffer , PxU32 inObjPerLine, PxStrideIterator<const TDataType>& inData, TAccessOperator inAccessOperator , PxU32 inBufSize, const char* inPropName, PxU32 /*inStride*/, TWriteOperator inOperator ) { #if PX_SWITCH const auto *dat = &inData[0]; if (inBufSize && dat != NULL) #else if ( inBufSize && &inData[0]) #endif { for ( PxU32 idx = 0; idx < inBufSize; ++idx ) { if ( idx && ( idx % inObjPerLine == 0 ) ) inTempBuffer << "\n\t\t\t"; else inTempBuffer << " "; inOperator( inTempBuffer, inAccessOperator( &inData[idx], 0 ) ); } writeProperty( inWriter, inTempBuffer, inPropName ); } } template<typename TDataType, typename TAccessOperator> inline void writeStrideFlags( XmlWriter& inWriter, MemoryBuffer& inTempBuffer , PxU32 inObjPerLine, PxStrideIterator<const TDataType>& inData, TAccessOperator /*inAccessOperator*/ , PxU32 inBufSize, const char* inPropName, const PxU32ToName* inTable) { #if PX_SWITCH const auto *dat = &inData[0]; if (inBufSize && dat != NULL) #else if ( inBufSize && &inData[0]) #endif { for ( PxU32 idx = 0; idx < inBufSize; ++idx ) { writeFlagsBuffer(inTempBuffer, inData[idx], inTable); if ( idx && ( idx % inObjPerLine == 0 ) ) inTempBuffer << "\n\t\t\t"; else inTempBuffer << " "; } writeProperty( inWriter, inTempBuffer, inPropName ); } } template<typename TDataType, typename TWriteOperator> inline void writeBuffer( XmlWriter& inWriter, MemoryBuffer& inTempBuffer , PxU32 inObjPerLine, const TDataType* inBuffer , PxU32 inBufSize, const char* inPropName, TWriteOperator inOperator ) { writeBuffer( inWriter, inTempBuffer, inObjPerLine, inBuffer, PtrAccess<TDataType>, inBufSize, inPropName, inOperator ); } template<typename TEnumType> inline void writeEnumProperty( XmlWriter& inWriter, const char* inPropName, TEnumType inEnumValue, const PxU32ToName* inConversions ) { PxU32 theValue = static_cast<PxU32>( inEnumValue ); for ( const PxU32ToName* conv = inConversions; conv->mName != NULL; ++conv ) if ( conv->mValue == theValue ) inWriter.write( inPropName, conv->mName ); } template<typename TObjType, typename TWriterType, typename TInfoType> inline void handleComplexObj( TWriterType& oldVisitor, const TObjType* inObj, const TInfoType& info); template<typename TCollectionType, typename TVisitor, typename TPropType, typename TInfoType > void handleComplexCollection( TVisitor& visitor, const TPropType& inProp, const char* childName, TInfoType& inInfo ) { PxU32 count( inProp.size( visitor.mObj ) ); if ( count ) { PxInlineArray<TCollectionType*,5> theData; theData.resize( count ); inProp.get( visitor.mObj, theData.begin(), count ); for( PxU32 idx =0; idx < count; ++idx ) { visitor.pushName( childName ); handleComplexObj( visitor, theData[idx], inInfo ); visitor.popName(); } } } template<typename TCollectionType, typename TVisitor, typename TPropType, typename TInfoType > void handleBufferCollection( TVisitor& visitor, const TPropType& inProp, const char* childName, TInfoType& inInfo ) { PxU32 count( inProp.size( visitor.mObj ) ); if ( count ) { PxInlineArray<TCollectionType*,5> theData; theData.resize( count ); inProp.get( visitor.mObj, theData.begin()); for( PxU32 idx =0; idx < count; ++idx ) { visitor.pushName( childName ); handleComplexObj( visitor, theData[idx], inInfo ); visitor.popName(); } } } template<typename TVisitor> void handleShapes( TVisitor& visitor, const PxRigidActorShapeCollection& inProp ) { PxShapeGeneratedInfo theInfo; PxU32 count( inProp.size( visitor.mObj ) ); if ( count ) { PxInlineArray<PxShape*,5> theData; theData.resize( count ); inProp.get( visitor.mObj, theData.begin(), count ); for( PxU32 idx = 0; idx < count; ++idx ) { const PxShape* shape = theData[idx]; visitor.pushName( "PxShape" ); if( !shape->isExclusive() ) { writeReference( visitor.mWriter, visitor.mCollection, "PxShapeRef", shape ); } else { handleComplexObj( visitor, shape, theInfo ); } visitor.popName(); } } } template<typename TVisitor> void handleShapeMaterials( TVisitor& visitor, const PxShapeMaterialsProperty& inProp ) { PxU32 count( inProp.size( visitor.mObj ) ); if ( count ) { PxInlineArray<PxMaterial*,5> theData; theData.resize( count ); inProp.get( visitor.mObj, theData.begin(), count ); visitor.pushName( "PxMaterialRef" ); for( PxU32 idx =0; idx < count; ++idx ) writeReference( visitor.mWriter, visitor.mCollection, "PxMaterialRef", theData[idx] ); visitor.popName(); } } template<typename TObjType> struct RepXVisitorWriterBase { TNameStack& mNameStack; XmlWriter& mWriter; const TObjType* mObj; MemoryBuffer& mTempBuffer; PxCollection& mCollection; RepXVisitorWriterBase( TNameStack& ns, XmlWriter& writer, const TObjType* obj, MemoryBuffer& buf, PxCollection& collection ) : mNameStack( ns ) , mWriter( writer ) , mObj( obj ) , mTempBuffer( buf ) , mCollection( collection ) { } RepXVisitorWriterBase( const RepXVisitorWriterBase<TObjType>& other ) : mNameStack( other.mNameStack ) , mWriter( other.mWriter ) , mObj( other.mObj ) , mTempBuffer( other.mTempBuffer ) , mCollection( other.mCollection ) { } RepXVisitorWriterBase& operator=( const RepXVisitorWriterBase& ){ PX_ASSERT( false ); return *this; } void gotoTopName() { if ( mNameStack.size() && mNameStack.back().mOpen == false ) { mWriter.addAndGotoChild( mNameStack.back().mName ); mNameStack.back().mOpen = true; } } void pushName( const char* inName ) { gotoTopName(); mNameStack.pushBack( inName ); } void pushBracketedName( const char* inName ) { pushName( inName ); } void popName() { if ( mNameStack.size() ) { if ( mNameStack.back().mOpen ) mWriter.leaveChild(); mNameStack.popBack(); } } const char* topName() const { if ( mNameStack.size() ) return mNameStack.back().mName; PX_ASSERT( false ); return "bad__repx__name"; } template<typename TAccessorType> void simpleProperty( PxU32 /*key*/, TAccessorType& inProp ) { typedef typename TAccessorType::prop_type TPropertyType; TPropertyType propVal = inProp.get( mObj ); writeProperty( mWriter, mCollection, mTempBuffer, topName(), propVal ); } template<typename TAccessorType> void enumProperty( PxU32 /*key*/, TAccessorType& inProp, const PxU32ToName* inConversions ) { writeEnumProperty( mWriter, topName(), inProp.get( mObj ), inConversions ); } template<typename TAccessorType> void flagsProperty( PxU32 /*key*/, const TAccessorType& inProp, const PxU32ToName* inConversions ) { writeFlagsProperty( mWriter, mTempBuffer, topName(), inProp.get( mObj ), inConversions ); } template<typename TAccessorType, typename TInfoType> void complexProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo ) { typedef typename TAccessorType::prop_type TPropertyType; TPropertyType propVal = inProp.get( mObj ); handleComplexObj( *this, &propVal, inInfo ); } template<typename TAccessorType, typename TInfoType> void bufferCollectionProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo ) { typedef typename TAccessorType::prop_type TPropertyType; PxU32 count( inProp.size( mObj ) ); PxInlineArray<TPropertyType,5> theData; theData.resize( count ); PxClassInfoTraits<TInfoType> theTraits; PX_UNUSED(theTraits); PxU32 numItems = inProp.get( mObj, theData.begin(), count ); PX_ASSERT( numItems == count ); for( PxU32 idx =0; idx < numItems; ++idx ) { pushName( inProp.name() ); handleComplexObj( *this, &theData[idx], inInfo ); popName(); } } template<typename TAccessorType, typename TInfoType> void extendedIndexedProperty( PxU32* /*key*/, const TAccessorType& inProp, TInfoType& /*inInfo */) { typedef typename TAccessorType::prop_type TPropertyType; PxU32 count( inProp.size( mObj ) ); PxInlineArray<TPropertyType,5> theData; theData.resize( count ); for(PxU32 i = 0; i < count; ++i) { char buffer[32] = { 0 }; sprintf( buffer, "id_%u", i ); pushName( buffer ); TPropertyType propVal = inProp.get( mObj, i ); TInfoType& infoType = PxClassInfoTraits<TPropertyType>().Info; handleComplexObj(*this, &propVal, infoType); popName(); } } template<typename TAccessorType, typename TInfoType> void PxFixedSizeLookupTableProperty( PxU32* /*key*/, TAccessorType& inProp, TInfoType& /*inInfo */) { typedef typename TAccessorType::prop_type TPropertyType; PxU32 count( inProp.size( mObj ) ); PxU32 index = 0; for(PxU32 i = 0; i < count; ++i) { char buffer[32] = { 0 }; sprintf( buffer, "id_%u", index++ ); pushName( buffer ); TPropertyType propVal = inProp.getX( mObj , i); writeProperty( mWriter, mCollection, mTempBuffer, topName(), propVal ); popName(); sprintf( buffer, "id_%u", index++ ); pushName( buffer ); propVal = inProp.getY( mObj , i); writeProperty( mWriter, mCollection, mTempBuffer, topName(), propVal ); popName(); } } void handleShapes( const PxRigidActorShapeCollection& inProp ) { physx::Sn::handleShapes( *this, inProp ); } void handleShapeMaterials( const PxShapeMaterialsProperty& inProp ) { physx::Sn::handleShapeMaterials( *this, inProp ); } void handleRigidActorGlobalPose(const PxRigidActorGlobalPosePropertyInfo& inProp) { PxRepXPropertyAccessor<PxPropertyInfoName::PxRigidActor_GlobalPose, PxRigidActor, const PxTransform &, PxTransform> theAccessor(inProp); simpleProperty(PxPropertyInfoName::PxRigidActor_GlobalPose, theAccessor); } }; template<typename TObjType> struct RepXVisitorWriter : RepXVisitorWriterBase<TObjType> { RepXVisitorWriter( TNameStack& ns, XmlWriter& writer, const TObjType* obj, MemoryBuffer& buf, PxCollection& collection ) : RepXVisitorWriterBase<TObjType>( ns, writer, obj, buf, collection ) { } RepXVisitorWriter( const RepXVisitorWriter<TObjType>& other ) : RepXVisitorWriterBase<TObjType>( other ) { } }; template<> struct RepXVisitorWriter<PxArticulationLink> : RepXVisitorWriterBase<PxArticulationLink> { RepXVisitorWriter( TNameStack& ns, XmlWriter& writer, const PxArticulationLink* obj, MemoryBuffer& buf, PxCollection& collection ) : RepXVisitorWriterBase<PxArticulationLink>( ns, writer, obj, buf, collection ) { } RepXVisitorWriter( const RepXVisitorWriter<PxArticulationLink>& other ) : RepXVisitorWriterBase<PxArticulationLink>( other ) { } void handleIncomingJoint( const TIncomingJointPropType& prop ) { const PxArticulationJointReducedCoordinate* joint( prop.get( mObj ) ); if (joint) { pushName( "Joint" ); handleComplexObj( *this, joint, PxArticulationJointReducedCoordinateGeneratedInfo()); popName(); } } }; typedef PxProfileHashMap< const PxSerialObjectId, const PxArticulationLink* > TArticulationLinkLinkMap; static void recurseAddLinkAndChildren( const PxArticulationLink* inLink, PxInlineArray<const PxArticulationLink*, 64>& ioLinks ) { ioLinks.pushBack( inLink ); PxInlineArray<PxArticulationLink*, 8> theChildren; PxU32 childCount( inLink->getNbChildren() ); theChildren.resize( childCount ); inLink->getChildren( theChildren.begin(), childCount ); for ( PxU32 idx = 0; idx < childCount; ++idx ) recurseAddLinkAndChildren( theChildren[idx], ioLinks ); } template<> struct RepXVisitorWriter<PxArticulationReducedCoordinate> : RepXVisitorWriterBase<PxArticulationReducedCoordinate> { TArticulationLinkLinkMap& mArticulationLinkParents; RepXVisitorWriter(TNameStack& ns, XmlWriter& writer, const PxArticulationReducedCoordinate* inArticulation, MemoryBuffer& buf, PxCollection& collection, TArticulationLinkLinkMap* artMap = NULL) : RepXVisitorWriterBase<PxArticulationReducedCoordinate>(ns, writer, inArticulation, buf, collection) , mArticulationLinkParents(*artMap) { PxInlineArray<PxArticulationLink*, 64, PxProfileWrapperReflectionAllocator<PxArticulationLink*> > linkList(PxProfileWrapperReflectionAllocator<PxArticulationLink*>(buf.mManager->getWrapper())); PxU32 numLinks = inArticulation->getNbLinks(); linkList.resize(numLinks); inArticulation->getLinks(linkList.begin(), numLinks); for (PxU32 idx = 0; idx < numLinks; ++idx) { const PxArticulationLink* theLink(linkList[idx]); PxInlineArray<PxArticulationLink*, 64> theChildList; PxU32 numChildren = theLink->getNbChildren(); theChildList.resize(numChildren); theLink->getChildren(theChildList.begin(), numChildren); for (PxU32 childIdx = 0; childIdx < numChildren; ++childIdx) mArticulationLinkParents.insert(static_cast<uint64_t>(size_t(theChildList[childIdx])), theLink); } } RepXVisitorWriter(const RepXVisitorWriter<PxArticulationReducedCoordinate>& other) : RepXVisitorWriterBase<PxArticulationReducedCoordinate>(other) , mArticulationLinkParents(other.mArticulationLinkParents) { } template<typename TAccessorType, typename TInfoType> void complexProperty(PxU32* /*key*/, const TAccessorType& inProp, TInfoType& inInfo) { typedef typename TAccessorType::prop_type TPropertyType; TPropertyType propVal = inProp.get(mObj); handleComplexObj(*this, &propVal, inInfo); } void writeArticulationLink(const PxArticulationLink* inLink) { pushName("PxArticulationLink"); gotoTopName(); const TArticulationLinkLinkMap::Entry* theParentPtr = mArticulationLinkParents.find(static_cast<uint64_t>(size_t(inLink))); if (theParentPtr != NULL) writeProperty(mWriter, mCollection, mTempBuffer, "Parent", theParentPtr->second); writeProperty(mWriter, mCollection, mTempBuffer, "Id", inLink); PxArticulationLinkGeneratedInfo info; handleComplexObj(*this, inLink, info); popName(); } void handleArticulationLinks(const PxArticulationLinkCollectionProp& inProp) { //topologically sort the links as per my discussion with Dilip because //links aren't guaranteed to have the parents before the children in the //overall link list and it is unlikely to be done by beta 1. PxU32 count(inProp.size(mObj)); if (count) { PxInlineArray<PxArticulationLink*, 64> theLinks; theLinks.resize(count); inProp.get(mObj, theLinks.begin(), count); PxInlineArray<const PxArticulationLink*, 64> theSortedLinks; for (PxU32 idx = 0; idx < count; ++idx) { const PxArticulationLink* theLink(theLinks[idx]); if (mArticulationLinkParents.find(static_cast<uint64_t>(size_t(theLink))) == NULL) recurseAddLinkAndChildren(theLink, theSortedLinks); } PX_ASSERT(theSortedLinks.size() == count); for (PxU32 idx = 0; idx < count; ++idx) writeArticulationLink(theSortedLinks[idx]); popName(); } } private: RepXVisitorWriter<PxArticulationReducedCoordinate>& operator=(const RepXVisitorWriter<PxArticulationReducedCoordinate>&); }; template<> struct RepXVisitorWriter<PxShape> : RepXVisitorWriterBase<PxShape> { RepXVisitorWriter( TNameStack& ns, XmlWriter& writer, const PxShape* obj, MemoryBuffer& buf, PxCollection& collection ) : RepXVisitorWriterBase<PxShape>( ns, writer, obj, buf, collection ) { } RepXVisitorWriter( const RepXVisitorWriter<PxShape>& other ) : RepXVisitorWriterBase<PxShape>( other ) { } template<typename GeometryType> inline void writeGeomProperty( const PxShapeGeomProperty& inProp, const char* inTypeName ) { pushName( "Geometry" ); pushName( inTypeName ); GeometryType theType; inProp.getGeometry( mObj, theType ); PxClassInfoTraits<GeometryType> theTraits; PxU32 count = theTraits.Info.totalPropertyCount(); if(count) { handleComplexObj( *this, &theType, theTraits.Info); } else { writeProperty(mWriter, mTempBuffer, inTypeName); } popName(); popName(); } void handleGeomProperty( const PxShapeGeomProperty& inProp ) { switch( mObj->getGeometry().getType() ) { case PxGeometryType::eSPHERE: writeGeomProperty<PxSphereGeometry>( inProp, "PxSphereGeometry" ); break; case PxGeometryType::ePLANE: writeGeomProperty<PxPlaneGeometry>( inProp, "PxPlaneGeometry" ); break; case PxGeometryType::eCAPSULE: writeGeomProperty<PxCapsuleGeometry>( inProp, "PxCapsuleGeometry" ); break; case PxGeometryType::eBOX: writeGeomProperty<PxBoxGeometry>( inProp, "PxBoxGeometry" ); break; case PxGeometryType::eCONVEXMESH: writeGeomProperty<PxConvexMeshGeometry>( inProp, "PxConvexMeshGeometry" ); break; case PxGeometryType::eTRIANGLEMESH: writeGeomProperty<PxTriangleMeshGeometry>( inProp, "PxTriangleMeshGeometry" ); break; case PxGeometryType::eHEIGHTFIELD: writeGeomProperty<PxHeightFieldGeometry>( inProp, "PxHeightFieldGeometry" ); break; case PxGeometryType::eTETRAHEDRONMESH: writeGeomProperty<PxTetrahedronMeshGeometry>( inProp, "PxTetrahedronMeshGeometry" ); break; default: PX_ASSERT( false ); } } }; template<typename TObjType> inline void writeAllProperties( TNameStack& inNameStack, const TObjType* inObj, XmlWriter& writer, MemoryBuffer& buffer, PxCollection& collection ) { RepXVisitorWriter<TObjType> newVisitor( inNameStack, writer, inObj, buffer, collection ); RepXPropertyFilter<RepXVisitorWriter<TObjType> > theOp( newVisitor ); PxClassInfoTraits<TObjType> info; info.Info.visitBaseProperties( theOp ); info.Info.visitInstanceProperties( theOp ); } template<typename TObjType> inline void writeAllProperties( TNameStack& inNameStack, TObjType* inObj, XmlWriter& writer, MemoryBuffer& buffer, PxCollection& collection ) { RepXVisitorWriter<TObjType> newVisitor( inNameStack, writer, inObj, buffer, collection ); RepXPropertyFilter<RepXVisitorWriter<TObjType> > theOp( newVisitor ); PxClassInfoTraits<TObjType> info; info.Info.visitBaseProperties( theOp ); info.Info.visitInstanceProperties( theOp ); } template<typename TObjType> inline void writeAllProperties( const TObjType* inObj, XmlWriter& writer, MemoryBuffer& buffer, PxCollection& collection ) { TNameStack theNames( buffer.mManager->getWrapper() ); writeAllProperties( theNames, inObj, writer, buffer, collection ); } template<typename TObjType, typename TWriterType, typename TInfoType> inline void handleComplexObj( TWriterType& oldVisitor, const TObjType* inObj, const TInfoType& /*info*/) { writeAllProperties( oldVisitor.mNameStack, inObj, oldVisitor.mWriter, oldVisitor.mTempBuffer, oldVisitor.mCollection ); } template<typename TObjType, typename TWriterType> inline void handleComplexObj( TWriterType& oldVisitor, const TObjType* inObj, const PxUnknownClassInfo& /*info*/) { writeProperty( oldVisitor.mWriter, oldVisitor.mCollection, oldVisitor.mTempBuffer, oldVisitor.topName(), *inObj ); } } } #endif
28,548
C
34.332921
196
0.722713
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnJointRepXSerializer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_JOINT_REPX_SERIALIZER_H #define SN_JOINT_REPX_SERIALIZER_H /** \addtogroup RepXSerializers @{ */ #include "extensions/PxRepXSimpleType.h" #include "SnRepXSerializerImpl.h" #if !PX_DOXYGEN namespace physx { #endif class XmlReader; class XmlMemoryAllocator; class XmlWriter; class MemoryBuffer; template<typename TJointType> struct PX_DEPRECATED PxJointRepXSerializer : public RepXSerializerImpl<TJointType> { PxJointRepXSerializer(PxAllocatorCallback& inAllocator) : RepXSerializerImpl<TJointType>(inAllocator) {} virtual PxRepXObject fileToObject(XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection); virtual void objectToFileImpl(const TJointType* inObj, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs&); virtual TJointType* allocateObject(PxRepXInstantiationArgs&) { return NULL; } }; #if PX_SUPPORT_EXTERN_TEMPLATE // explicit template instantiations declarations extern template struct PX_DEPRECATED PxJointRepXSerializer<PxD6Joint>; extern template struct PX_DEPRECATED PxJointRepXSerializer<PxDistanceJoint>; extern template struct PX_DEPRECATED PxJointRepXSerializer<PxContactJoint>; extern template struct PX_DEPRECATED PxJointRepXSerializer<PxFixedJoint>; extern template struct PX_DEPRECATED PxJointRepXSerializer<PxPrismaticJoint>; extern template struct PX_DEPRECATED PxJointRepXSerializer<PxRevoluteJoint>; extern template struct PX_DEPRECATED PxJointRepXSerializer<PxSphericalJoint>; #endif #if !PX_DOXYGEN } // namespace physx #endif /** @} */ #endif
3,325
C
44.561643
160
0.792481
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepX3_2Defaults.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Length", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Mass", "1000" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Speed", "10" ) DEFINE_REPX_DEFAULT_PROPERTY("PxBoxGeometry.HalfExtents", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphereGeometry.Radius", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.Scale.Scale", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.Scale.Rotation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.ConvexMesh", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.Scale.Scale", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.Scale.Rotation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.MeshFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.TriangleMesh", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightField", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.RowScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.ColumnScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightFieldFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DynamicFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.StaticFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.FrictionCombineMode", "eAVERAGE" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.RestitutionCombineMode", "eAVERAGE" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.LocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.SimulationFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.QueryFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.ContactOffset", "0.02" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.RestOffset", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.Flags", "eSIMULATION_SHAPE|eSCENE_QUERY_SHAPE|eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.CMassLocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.Mass", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.MassSpaceInertiaTensor", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.LinearVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.AngularVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.LinearDamping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.AngularDamping", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.MaxAngularVelocity", "7" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SleepThreshold", "0.005" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SolverIterationCounts.minPositionIters", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SolverIterationCounts.minVelocityIters", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ContactReportThreshold", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.RigidDynamicFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ParentPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ChildPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TargetOrientation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TargetVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.InternalCompliance", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ExternalCompliance", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimit.yLimit", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimit.zLimit", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TangentialSpring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TangentialDamping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimitContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimitEnabled", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimit.lower", "-0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimit.upper", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimitEnabled", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimitContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.CMassLocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.Mass", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.MassSpaceInertiaTensor", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.LinearVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.AngularVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.MaxProjectionIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SeparationTolerance", "0.1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.InternalDriveIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.ExternalDriveIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SolverIterationCounts.minPositionIters", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SolverIterationCounts.minVelocityIters", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SleepThreshold", "0.005" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eX", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eY", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eZ", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eTWIST", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eSWING1", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eSWING2", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Value", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Upper", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Lower", "-1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.YAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.ZAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DrivePosition", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DriveVelocity.linear", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DriveVelocity.angular", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.MinDistance", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.MaxDistance", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Tolerance", "0.025" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.DistanceJointFlags", "eMAX_DISTANCE_ENABLED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Upper", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Lower", "-1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveVelocity", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveGearRatio", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.RevoluteJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.ContactDistance", "0.01" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Upper", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Lower", "-3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.PrismaticJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Actors.actor0", "8887040" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Actors.actor1", "8887456" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LocalPose.eACTOR0", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LocalPose.eACTOR1", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.YAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.ZAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.SphericalJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.MotionConstraintScaleBias.scale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.MotionConstraintScaleBias.bias", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.ExternalAcceleration", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.DampingCoefficient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.SolverFrequency", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.SleepLinearVelocity", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.InertiaScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.FrictionCoefficient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.DragCoefficient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxCloth.CollisionMassScale", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ExternalAcceleration", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ParticleMass", "0.001" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.Restitution", "0.5" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.DynamicFriction", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.StaticFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.SimulationFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.MaxMotionDistance", "0.06" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.RestOffset", "0.004" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ContactOffset", "0.008" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.GridSize", "0.96" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ProjectionPlane", "0 0 1 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ParticleReadDataFlags", "ePOSITION_BUFFER|eFLAGS_BUFFER" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleSystem.ParticleBaseFlags", "eCOLLISION_WITH_DYNAMIC_ACTORS|eENABLED|ePER_PARTICLE_REST_OFFSET|ePER_PARTICLE_COLLISION_CACHE_HINT") DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ExternalAcceleration", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ParticleMass", "0.001" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.Restitution", "0.5" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.DynamicFriction", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.StaticFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.SimulationFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.MaxMotionDistance", "0.06" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.RestOffset", "0.004" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ContactOffset", "0.008" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.GridSize", "0.64" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ProjectionPlane", "0 0 1 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.Stiffness", "20" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.Viscosity", "6" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.RestParticleDistance", "0.02" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ParticleReadDataFlags", "ePOSITION_BUFFER|eFLAGS_BUFFER" ) DEFINE_REPX_DEFAULT_PROPERTY("PxParticleFluid.ParticleBaseFlags", "eCOLLISION_WITH_DYNAMIC_ACTORS|eENABLED|ePER_PARTICLE_REST_OFFSET|ePER_PARTICLE_COLLISION_CACHE_HINT") DEFINE_REPX_DEFAULT_PROPERTY("PxAggregate.SelfCollision", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("THEEND", "false" )
22,899
C
72.162939
171
0.77558
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlSerialization.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 "SnXmlImpl.h" #include "foundation/PxHash.h" #include "foundation/PxHashMap.h" #include "foundation/PxString.h" #include "SnSimpleXmlWriter.h" #include "foundation/PxSort.h" #include "PsFastXml.h" #include "SnXmlMemoryPool.h" #include "PxExtensionMetaDataObjects.h" #include "SnXmlVisitorWriter.h" #include "SnXmlVisitorReader.h" #include "SnXmlMemoryAllocator.h" #include "SnXmlStringToType.h" #include "SnRepXCollection.h" #include "SnRepXUpgrader.h" #include "../SnSerializationRegistry.h" #include "CmCollection.h" using namespace physx; using namespace Sn; using namespace physx::profile; //for the foundation wrapper system. namespace physx { namespace Sn { class XmlNodeWriter : public SimpleXmlWriter { XmlMemoryAllocatorImpl& mParseAllocator; XmlNode* mCurrentNode; XmlNode* mTopNode; PxU32 mTabCount; public: XmlNodeWriter( XmlMemoryAllocatorImpl& inAllocator, PxU32 inTabCount = 0 ) : mParseAllocator( inAllocator ) , mCurrentNode( NULL ) , mTopNode( NULL ) , mTabCount( inTabCount ) {} XmlNodeWriter& operator=(const XmlNodeWriter&); virtual ~XmlNodeWriter(){} void onNewNode( XmlNode* newNode ) { if ( mCurrentNode != NULL ) mCurrentNode->addChild( newNode ); if ( mTopNode == NULL ) mTopNode = newNode; mCurrentNode = newNode; ++mTabCount; } XmlNode* getTopNode() const { return mTopNode; } virtual void beginTag( const char* inTagname ) { onNewNode( allocateRepXNode( &mParseAllocator.mManager, inTagname, NULL ) ); } virtual void endTag() { if ( mCurrentNode ) mCurrentNode = mCurrentNode->mParent; if ( mTabCount ) --mTabCount; } virtual void addAttribute( const char*, const char* ) { PX_ASSERT( false ); } virtual void writeContentTag( const char* inTag, const char* inContent ) { onNewNode( allocateRepXNode( &mParseAllocator.mManager, inTag, inContent ) ); endTag(); } virtual void addContent( const char* inContent ) { if ( mCurrentNode->mData ) releaseStr( &mParseAllocator.mManager, mCurrentNode->mData ); mCurrentNode->mData = copyStr( &mParseAllocator.mManager, inContent ); } virtual PxU32 tabCount() { return mTabCount; } }; struct XmlWriterImpl : public XmlWriter { PxU32 mTagDepth; SimpleXmlWriter* mWriter; MemoryBuffer* mMemBuffer; XmlWriterImpl( SimpleXmlWriter* inWriter, MemoryBuffer* inMemBuffer ) : mTagDepth( 0 ) , mWriter( inWriter ) , mMemBuffer( inMemBuffer ) { } ~XmlWriterImpl() { while( mTagDepth ) { --mTagDepth; mWriter->endTag(); } } virtual void write( const char* inName, const char* inData ) { mWriter->writeContentTag( inName, inData ); } virtual void write( const char* inName, const PxRepXObject& inLiveObject ) { (*mMemBuffer) << inLiveObject.id; writeProperty( *mWriter, *mMemBuffer, inName ); } virtual void addAndGotoChild( const char* inName ) { mWriter->beginTag( inName ); mTagDepth++; } virtual void leaveChild() { if ( mTagDepth ) { mWriter->endTag(); --mTagDepth; } } }; struct XmlParseArgs { XmlMemoryAllocatorImpl* mAllocator; PxProfileArray<RepXCollectionItem>* mCollection; XmlParseArgs( XmlMemoryAllocatorImpl* inAllocator , PxProfileArray<RepXCollectionItem>* inCollection) : mAllocator( inAllocator ) , mCollection( inCollection ) { } }; struct XmlNodeReader : public XmlReaderWriter { PxProfileAllocatorWrapper mWrapper; CMemoryPoolManager& mManager; XmlNode* mCurrentNode; XmlNode* mTopNode; PxProfileArray<XmlNode*> mContext; XmlNodeReader( XmlNode* inCurrentNode, PxAllocatorCallback& inAllocator, CMemoryPoolManager& nodePoolManager ) : mWrapper( inAllocator ) , mManager( nodePoolManager ) , mCurrentNode( inCurrentNode ) , mTopNode( inCurrentNode ) , mContext( mWrapper ) { } //Does this node exist as data in the format. virtual bool read( const char* inName, const char*& outData ) { XmlNode* theChild( mCurrentNode->findChildByName( inName ) ); if ( theChild ) { outData = theChild->mData; return outData && *outData; } return false; } virtual bool read( const char* inName, PxSerialObjectId& outId ) { XmlNode* theChild( mCurrentNode->findChildByName( inName ) ); if ( theChild ) { const char* theValue( theChild->mData ); strto( outId, theValue ); return true; } return false; } virtual bool gotoChild( const char* inName ) { XmlNode* theChild( mCurrentNode->findChildByName( inName ) ); if ( theChild ) { mCurrentNode =theChild; return true; } return false; } virtual bool gotoFirstChild() { if ( mCurrentNode->mFirstChild ) { mCurrentNode = mCurrentNode->mFirstChild; return true; } return false; } virtual bool gotoNextSibling() { if ( mCurrentNode->mNextSibling ) { mCurrentNode = mCurrentNode->mNextSibling; return true; } return false; } virtual PxU32 countChildren() { PxU32 retval= 0; for ( XmlNode* theChild = mCurrentNode->mFirstChild; theChild != NULL; theChild = theChild->mNextSibling ) ++retval; return retval; } virtual const char* getCurrentItemName() { return mCurrentNode->mName; } virtual const char* getCurrentItemValue() { return mCurrentNode->mData; } virtual bool leaveChild() { if ( mCurrentNode != mTopNode && mCurrentNode->mParent ) { mCurrentNode = mCurrentNode->mParent; return true; } return false; } virtual void pushCurrentContext() { mContext.pushBack( mCurrentNode ); } virtual void popCurrentContext() { if ( mContext.size() ) { mCurrentNode = mContext.back(); mContext.popBack(); } } virtual void setNode( XmlNode& inNode ) { mContext.clear(); mCurrentNode = &inNode; mTopNode = mCurrentNode; } virtual XmlReader* getParentReader() { XmlReader* retval = PX_PLACEMENT_NEW((mWrapper.getAllocator().allocate(sizeof(XmlNodeReader), "createNodeEditor", PX_FL)), XmlNodeReader) ( mTopNode, mWrapper.getAllocator(), mManager ); return retval; } virtual void addOrGotoChild( const char* inName ) { if ( gotoChild( inName )== false ) { XmlNode* newNode = allocateRepXNode( &mManager, inName, NULL ); mCurrentNode->addChild( newNode ); mCurrentNode = newNode; } } virtual void setCurrentItemValue( const char* inValue ) { mCurrentNode->mData = copyStr( &mManager, inValue ); } virtual bool removeChild( const char* name ) { XmlNode* theChild( mCurrentNode->findChildByName( name ) ); if ( theChild ) { releaseNodeAndChildren( &mManager, theChild ); return true; } return false; } virtual void release() { this->~XmlNodeReader(); mWrapper.getAllocator().deallocate(this); } private: XmlNodeReader& operator=(const XmlNodeReader&); }; PX_INLINE void freeNodeAndChildren( XmlNode* tempNode, TMemoryPoolManager& inManager ) { for( XmlNode* theNode = tempNode->mFirstChild; theNode != NULL; theNode = theNode->mNextSibling ) freeNodeAndChildren( theNode, inManager ); tempNode->orphan(); release( &inManager, tempNode ); } class XmlParser : public shdfnd::FastXml::Callback { XmlParseArgs mParseArgs; //For parse time only allocations XmlMemoryAllocatorImpl& mParseAllocator; XmlNode* mCurrentNode; XmlNode* mTopNode; public: XmlParser( XmlParseArgs inArgs, XmlMemoryAllocatorImpl& inParseAllocator ) : mParseArgs( inArgs ) , mParseAllocator( inParseAllocator ) , mCurrentNode( NULL ) , mTopNode( NULL ) { } virtual ~XmlParser(){} virtual bool processComment(const char* /*comment*/) { return true; } // 'element' is the name of the element that is being closed. // depth is the recursion depth of this element. // Return true to continue processing the XML file. // Return false to stop processing the XML file; leaves the read pointer of the stream right after this close tag. // The bool 'isError' indicates whether processing was stopped due to an error, or intentionally canceled early. virtual bool processClose(const char* /*element*/,physx::PxU32 /*depth*/,bool& isError) { if (NULL != mCurrentNode) { mCurrentNode = mCurrentNode->mParent; return true; } isError = true; return false; } // return true to continue processing the XML document, false to skip. virtual bool processElement( const char *elementName, // name of the element const char *elementData, // element data, null if none const shdfnd::FastXml::AttributePairs& attr, // attributes PxI32 /*lineno*/) { XmlNode* newNode = allocateRepXNode( &mParseAllocator.mManager, elementName, elementData ); if ( mCurrentNode ) mCurrentNode->addChild( newNode ); mCurrentNode = newNode; //Add the elements as children. for( PxI32 item = 0; item < attr.getNbAttr(); item ++ ) { XmlNode* node = allocateRepXNode( &mParseAllocator.mManager, attr.getKey(PxU32(item)), attr.getValue(PxU32(item)) ); mCurrentNode->addChild( node ); } if ( mTopNode == NULL ) mTopNode = newNode; return true; } XmlNode* getTopNode() { return mTopNode; } virtual void * allocate(PxU32 size) { if ( size ) return mParseAllocator.allocate(size); return NULL; } virtual void deallocate(void *mem) { if ( mem ) mParseAllocator.deallocate(reinterpret_cast<PxU8*>(mem)); } private: XmlParser& operator=(const XmlParser&); }; struct RepXCollectionSharedData { PxProfileAllocatorWrapper mWrapper; XmlMemoryAllocatorImpl mAllocator; PxU32 mRefCount; RepXCollectionSharedData( PxAllocatorCallback& inAllocator ) : mWrapper( inAllocator ) , mAllocator( inAllocator ) , mRefCount( 0 ) { } ~RepXCollectionSharedData() {} void addRef() { ++mRefCount;} void release() { if ( mRefCount ) --mRefCount; if ( !mRefCount ) { this->~RepXCollectionSharedData(); mWrapper.getAllocator().deallocate(this);} } }; struct SharedDataPtr { RepXCollectionSharedData* mData; SharedDataPtr( RepXCollectionSharedData* inData ) : mData( inData ) { mData->addRef(); } SharedDataPtr( const SharedDataPtr& inOther ) : mData( inOther.mData ) { mData->addRef(); } SharedDataPtr& operator=( const SharedDataPtr& inOther ); ~SharedDataPtr() { mData->release(); mData = NULL; } RepXCollectionSharedData* operator->() { return mData; } const RepXCollectionSharedData* operator->() const { return mData; } }; class RepXCollectionImpl : public RepXCollection, public PxUserAllocated { SharedDataPtr mSharedData; XmlMemoryAllocatorImpl& mAllocator; PxSerializationRegistry& mSerializationRegistry; PxProfileArray<RepXCollectionItem> mCollection; TMemoryPoolManager mSerializationManager; MemoryBuffer mPropertyBuffer; PxTolerancesScale mScale; PxVec3 mUpVector; const char* mVersionStr; PxCollection* mPxCollection; public: RepXCollectionImpl( PxSerializationRegistry& inRegistry, PxAllocatorCallback& inAllocator, PxCollection& inPxCollection ) : mSharedData( &PX_NEW_REPX_SERIALIZER( RepXCollectionSharedData )) , mAllocator( mSharedData->mAllocator ) , mSerializationRegistry( inRegistry ) , mCollection( mSharedData->mWrapper ) , mSerializationManager( inAllocator ) , mPropertyBuffer( &mSerializationManager ) , mScale(0.f, 0.f) , mUpVector( 0,0,0 ) , mVersionStr( getLatestVersion() ) , mPxCollection( &inPxCollection ) { PX_ASSERT( mScale.isValid() == false ); } RepXCollectionImpl( PxSerializationRegistry& inRegistry, const RepXCollectionImpl& inSrc, const char* inNewVersion ) : mSharedData( inSrc.mSharedData ) , mAllocator( mSharedData->mAllocator ) , mSerializationRegistry( inRegistry ) , mCollection( mSharedData->mWrapper ) , mSerializationManager( mSharedData->mWrapper.getAllocator() ) , mPropertyBuffer( &mSerializationManager ) , mScale( inSrc.mScale ) , mUpVector( inSrc.mUpVector ) , mVersionStr( inNewVersion ) , mPxCollection( NULL ) { } virtual ~RepXCollectionImpl() { PxU32 numItems = mCollection.size(); for ( PxU32 idx = 0; idx < numItems; ++idx ) { XmlNode* theNode = mCollection[idx].descriptor; releaseNodeAndChildren( &mAllocator.mManager, theNode ); } } RepXCollectionImpl& operator=(const RepXCollectionImpl&); virtual void destroy() { PxProfileAllocatorWrapper tempWrapper( mSharedData->mWrapper.getAllocator() ); this->~RepXCollectionImpl(); tempWrapper.getAllocator().deallocate(this); } virtual void setTolerancesScale(const PxTolerancesScale& inScale) { mScale = inScale; } virtual PxTolerancesScale getTolerancesScale() const { return mScale; } virtual void setUpVector( const PxVec3& inUpVector ) { mUpVector = inUpVector; } virtual PxVec3 getUpVector() const { return mUpVector; } PX_INLINE RepXCollectionItem findItemBySceneItem( const PxRepXObject& inObject ) const { //See if the object is in the collection for ( PxU32 idx =0; idx < mCollection.size(); ++idx ) if ( mCollection[idx].liveObject.serializable == inObject.serializable ) return mCollection[idx]; return RepXCollectionItem(); } virtual RepXAddToCollectionResult addRepXObjectToCollection( const PxRepXObject& inObject, PxCollection* inCollection, PxRepXInstantiationArgs& inArgs ) { PX_ASSERT( inObject.serializable ); PX_ASSERT( inObject.id ); if ( inObject.serializable == NULL || inObject.id == 0 ) return RepXAddToCollectionResult( RepXAddToCollectionResult::InvalidParameters ); PxRepXSerializer* theSerializer = mSerializationRegistry.getRepXSerializer( inObject.typeName ); if ( theSerializer == NULL ) return RepXAddToCollectionResult( RepXAddToCollectionResult::SerializerNotFound ); RepXCollectionItem existing = findItemBySceneItem( inObject ); if ( existing.liveObject.serializable ) return RepXAddToCollectionResult( RepXAddToCollectionResult::AlreadyInCollection, existing.liveObject.id ); XmlNodeWriter theXmlWriter( mAllocator, 1 ); XmlWriterImpl theRepXWriter( &theXmlWriter, &mPropertyBuffer ); { SimpleXmlWriter::STagWatcher theWatcher( theXmlWriter, inObject.typeName ); writeProperty( theXmlWriter, mPropertyBuffer, "Id", inObject.id ); theSerializer->objectToFile( inObject, inCollection, theRepXWriter, mPropertyBuffer,inArgs ); } mCollection.pushBack( RepXCollectionItem( inObject, theXmlWriter.getTopNode() ) ); return RepXAddToCollectionResult( RepXAddToCollectionResult::Success, inObject.id ); } virtual bool instantiateCollection( PxRepXInstantiationArgs& inArgs, PxCollection& inCollection ) { for ( PxU32 idx =0; idx < mCollection.size(); ++idx ) { RepXCollectionItem theItem( mCollection[idx] ); PxRepXSerializer* theSerializer = mSerializationRegistry.getRepXSerializer( theItem.liveObject.typeName ); if (theSerializer ) { XmlNodeReader theReader( theItem.descriptor, mAllocator.getAllocator(), mAllocator.mManager ); XmlMemoryAllocatorImpl instantiationAllocator( mAllocator.getAllocator() ); PxRepXObject theLiveObject = theSerializer->fileToObject( theReader, instantiationAllocator, inArgs, &inCollection ); if (theLiveObject.isValid()) { const PxBase* s = reinterpret_cast<const PxBase*>( theLiveObject.serializable ) ; inCollection.add( *const_cast<PxBase*>(s), PxSerialObjectId( theItem.liveObject.id )); } else return false; } else { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PxSerialization::createCollectionFromXml: " "PxRepXSerializer missing for type %s", theItem.liveObject.typeName); return false; } } return true; } void saveXmlNode( XmlNode* inNode, SimpleXmlWriter& inWriter ) { XmlNode* theNode( inNode ); if ( theNode->mData && *theNode->mData && theNode->mFirstChild == NULL ) inWriter.writeContentTag( theNode->mName, theNode->mData ); else { inWriter.beginTag( theNode->mName ); if ( theNode->mData && *theNode->mData ) inWriter.addContent( theNode->mData ); for ( XmlNode* theChild = theNode->mFirstChild; theChild != NULL; theChild = theChild->mNextSibling ) saveXmlNode( theChild, inWriter ); inWriter.endTag(); } } virtual void save( PxOutputStream& inStream ) { SimpleXmlWriterImpl<PxOutputStream> theWriter( inStream, mAllocator.getAllocator() ); theWriter.beginTag( "PhysXCollection" ); theWriter.addAttribute( "version", mVersionStr ); { XmlWriterImpl theRepXWriter( &theWriter, &mPropertyBuffer ); writeProperty( theWriter, mPropertyBuffer, "UpVector", mUpVector ); theRepXWriter.addAndGotoChild( "Scale" ); writeAllProperties( &mScale, theRepXWriter, mPropertyBuffer, *mPxCollection); theRepXWriter.leaveChild(); } for ( PxU32 idx =0; idx < mCollection.size(); ++idx ) { RepXCollectionItem theItem( mCollection[idx] ); XmlNode* theNode( theItem.descriptor ); saveXmlNode( theNode, theWriter ); } } void load( PxInputData& inFileBuf, SerializationRegistry& s ) { inFileBuf.seek(0); XmlParser theParser( XmlParseArgs( &mAllocator, &mCollection ), mAllocator ); shdfnd::FastXml* theFastXml = shdfnd::createFastXml( &theParser ); theFastXml->processXml( inFileBuf ); XmlNode* theTopNode = theParser.getTopNode(); if ( theTopNode != NULL ) { { XmlMemoryAllocatorImpl instantiationAllocator( mAllocator.getAllocator() ); XmlNodeReader theReader( theTopNode, mAllocator.getAllocator(), mAllocator.mManager ); readProperty( theReader, "UpVector", mUpVector ); if ( theReader.gotoChild( "Scale" ) ) { readAllProperties( PxRepXInstantiationArgs( s.getPhysics() ), theReader, &mScale, instantiationAllocator, *mPxCollection); theReader.leaveChild(); } const char* verStr = NULL; if ( theReader.read( "version", verStr ) ) mVersionStr = verStr; } for ( XmlNode* theChild = theTopNode->mFirstChild; theChild != NULL; theChild = theChild->mNextSibling ) { if ( physx::Pxstricmp( theChild->mName, "scale" ) == 0 || physx::Pxstricmp( theChild->mName, "version" ) == 0 || physx::Pxstricmp( theChild->mName, "upvector" ) == 0 ) continue; XmlNodeReader theReader( theChild, mAllocator.getAllocator(), mAllocator.mManager ); PxRepXObject theObject; theObject.typeName = theChild->mName; theObject.serializable = NULL; PxSerialObjectId theId = 0; theReader.read( "Id", theId ); theObject.id = theId; mCollection.pushBack( RepXCollectionItem( theObject, theChild ) ); } } else { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "Cannot parse any object from the input buffer, please check the input repx data."); } theFastXml->release(); } virtual const char* getVersion() { return mVersionStr; } virtual const RepXCollectionItem* begin() const { return mCollection.begin(); } virtual const RepXCollectionItem* end() const { return mCollection.end(); } virtual RepXCollection& createCollection( const char* inVersionStr ) { PxAllocatorCallback& allocator = mSharedData->mWrapper.getAllocator(); RepXCollectionImpl* retval = PX_PLACEMENT_NEW((allocator.allocate(sizeof(RepXCollectionImpl), "createCollection", PX_FL)), RepXCollectionImpl) ( mSerializationRegistry, *this, inVersionStr ); return *retval; } //Performs a deep copy of the repx node. virtual XmlNode* copyRepXNode( const XmlNode* srcNode ) { return physx::Sn::copyRepXNode( &mAllocator.mManager, srcNode ); } virtual void addCollectionItem( RepXCollectionItem inItem ) { mCollection.pushBack( inItem ); } virtual PxAllocatorCallback& getAllocator() { return mSharedData->mAllocator.getAllocator(); } //Create a new repx node with this name. Its value is unset. virtual XmlNode& createRepXNode( const char* name ) { XmlNode* newNode = allocateRepXNode( &mSharedData->mAllocator.mManager, name, NULL ); return *newNode; } //Release this when finished. virtual XmlReaderWriter& createNodeEditor() { PxAllocatorCallback& allocator = mSharedData->mWrapper.getAllocator(); XmlReaderWriter* retval = PX_PLACEMENT_NEW((allocator.allocate(sizeof(XmlNodeReader), "createNodeEditor", PX_FL)), XmlNodeReader) ( NULL, allocator, mAllocator.mManager ); return *retval; } }; const char* RepXCollection::getLatestVersion() { #define TOSTR_(x) #x #define CONCAT_(a, b, c) TOSTR_(a.##b.##c) #define MAKE_VERSION_STR(a,b,c) CONCAT_(a, b, c) return MAKE_VERSION_STR(PX_PHYSICS_VERSION_MAJOR,PX_PHYSICS_VERSION_MINOR,PX_PHYSICS_VERSION_BUGFIX); } static RepXCollection* create(SerializationRegistry& s, PxAllocatorCallback& inAllocator, PxCollection& inCollection ) { return PX_PLACEMENT_NEW((inAllocator.allocate(sizeof(RepXCollectionImpl), "RepXCollection::create", PX_FL)), RepXCollectionImpl) ( s, inAllocator, inCollection ); } static RepXCollection* create(SerializationRegistry& s, PxInputData &data, PxAllocatorCallback& inAllocator, PxCollection& inCollection ) { RepXCollectionImpl* theCollection = static_cast<RepXCollectionImpl*>( create(s, inAllocator, inCollection ) ); theCollection->load( data, s ); return theCollection; } } bool PxSerialization::serializeCollectionToXml( PxOutputStream& outputStream, PxCollection& collection, PxSerializationRegistry& sr, const PxCookingParams* params, const PxCollection* externalRefs, PxXmlMiscParameter* inArgs ) { if( !PxSerialization::isSerializable(collection, sr, const_cast<PxCollection*>(externalRefs)) ) return false; bool bRet = true; SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr); PxRepXInstantiationArgs args( sn.getPhysics(), params ); PxCollection* tmpCollection = PxCreateCollection(); PX_ASSERT(tmpCollection); tmpCollection->add( collection ); if(externalRefs) { tmpCollection->add(*const_cast<PxCollection*>(externalRefs)); } PxAllocatorCallback& allocator = *PxGetAllocatorCallback(); Sn::RepXCollection* theRepXCollection = Sn::create(sn, allocator, *tmpCollection ); if(inArgs != NULL) { theRepXCollection->setTolerancesScale(inArgs->scale); theRepXCollection->setUpVector(inArgs->upVector); } PxU32 nbObjects = collection.getNbObjects(); if( nbObjects ) { sortCollection( static_cast<Cm::Collection&>(collection), sn, true); for( PxU32 i = 0; i < nbObjects; i++ ) { PxBase& s = collection.getObject(i); if( PxConcreteType::eSHAPE == s.getConcreteType() ) { PxShape& shape = static_cast<PxShape&>(s); if( shape.isExclusive() ) continue; } PxSerialObjectId id = collection.getId(s); if(id == PX_SERIAL_OBJECT_ID_INVALID) id = static_cast<PxSerialObjectId>( size_t( &s )); PxRepXObject ro = PxCreateRepXObject( &s, id ); if ( ro.serializable == NULL || ro.id == 0 ) { bRet = false; break; } theRepXCollection->addRepXObjectToCollection( ro, tmpCollection, args ); } } tmpCollection->release(); theRepXCollection->save(outputStream); theRepXCollection->destroy(); return bRet; } PxCollection* PxSerialization::createCollectionFromXml(PxInputData& inputData, const PxCookingParams& params, PxSerializationRegistry& sr, const PxCollection* externalRefs, PxStringTable* stringTable, PxXmlMiscParameter* outArgs) { SerializationRegistry& sn = static_cast<SerializationRegistry&>(sr); PxCollection* collection = PxCreateCollection(); PX_ASSERT(collection); if( externalRefs ) collection->add(*const_cast<PxCollection*>(externalRefs)); PxAllocatorCallback& allocator = *PxGetAllocatorCallback(); Sn::RepXCollection* theRepXCollection = Sn::create(sn, inputData, allocator, *collection); theRepXCollection = &Sn::RepXUpgrader::upgradeCollection( *theRepXCollection ); PxRepXInstantiationArgs args( sn.getPhysics(), &params, stringTable ); if( !theRepXCollection->instantiateCollection(args, *collection) ) { collection->release(); theRepXCollection->destroy(); return NULL; } if( externalRefs ) collection->remove(*const_cast<PxCollection*>(externalRefs)); if(outArgs != NULL) { outArgs->upVector = theRepXCollection->getUpVector(); outArgs->scale = theRepXCollection->getTolerancesScale(); } theRepXCollection->destroy(); return collection; } }
26,530
C++
30.69773
230
0.705277
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlDeserializer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_DESERIALIZER_H #define SN_XML_DESERIALIZER_H #include "SnXmlVisitorReader.h" namespace physx { namespace Sn { //Definitions needed internally in the Serializer headers. template<typename TTriIndexElem> struct Triangle { TTriIndexElem mIdx0; TTriIndexElem mIdx1; TTriIndexElem mIdx2; Triangle( TTriIndexElem inIdx0 = 0, TTriIndexElem inIdx1 = 0, TTriIndexElem inIdx2 = 0) : mIdx0( inIdx0 ) , mIdx1( inIdx1 ) , mIdx2( inIdx2 ) { } }; struct XmlMemoryAllocateMemoryPoolAllocator { XmlMemoryAllocator* mAllocator; XmlMemoryAllocateMemoryPoolAllocator( XmlMemoryAllocator* inAlloc ) : mAllocator( inAlloc ) {} PxU8* allocate( PxU32 inSize ) { return mAllocator->allocate( inSize ); } void deallocate( PxU8* inMem ) { mAllocator->deallocate( inMem ); } }; inline bool isEmpty(const char *s) { while (*s != '\0') { if (!isspace(*s)) return false; s++; } return true; } inline void strtoLong( Triangle<PxU32>& ioDatatype,const char*& ioData ) { strto( ioDatatype.mIdx0, ioData ); strto( ioDatatype.mIdx1, ioData ); strto( ioDatatype.mIdx2, ioData ); } inline void strtoLong( PxHeightFieldSample& ioDatatype,const char*& ioData ) { PxU32 tempData; strto( tempData, ioData ); if ( isBigEndian() ) { PxU32& theItem(tempData); PxU32 theDest = 0; PxU8* theReadPtr( reinterpret_cast< PxU8* >( &theItem ) ); PxU8* theWritePtr( reinterpret_cast< PxU8* >( &theDest ) ); //A height field sample is a 16 bit number //followed by two bytes. //We write this out as a 32 bit integer, LE. //Thus, on a big endian, we need to move the bytes //around a bit. //LE - 1 2 3 4 //BE - 4 3 2 1 - after convert from xml number //Correct BE - 2 1 3 4, just like LE but with the 16 number swapped theWritePtr[0] = theReadPtr[2]; theWritePtr[1] = theReadPtr[3]; theWritePtr[2] = theReadPtr[1]; theWritePtr[3] = theReadPtr[0]; theItem = theDest; } ioDatatype = *reinterpret_cast<PxHeightFieldSample*>( &tempData ); } template<typename TDataType> inline void readStridedFlagsProperty( XmlReader& ioReader, const char* inPropName, TDataType*& outData, PxU32& outStride, PxU32& outCount, XmlMemoryAllocator& inAllocator, const PxU32ToName* inConversions) { const char* theSrcData; outStride = sizeof( TDataType ); outData = NULL; outCount = 0; if ( ioReader.read( inPropName, theSrcData ) ) { XmlMemoryAllocateMemoryPoolAllocator tempAllocator( &inAllocator ); MemoryBufferBase<XmlMemoryAllocateMemoryPoolAllocator> tempBuffer( &tempAllocator ); if ( theSrcData ) { static PxU32 theCount = 0; ++theCount; char* theStartData = const_cast< char*>( copyStr( &tempAllocator, theSrcData ) ); char* aData = strtok(theStartData, " \n"); while( aData ) { TDataType tempValue; stringToFlagsType( aData, inAllocator, tempValue, inConversions ); aData = strtok(NULL," \n"); tempBuffer.write( &tempValue, sizeof(TDataType) ); } outData = reinterpret_cast< TDataType* >( tempBuffer.mBuffer ); outCount = tempBuffer.mWriteOffset / sizeof( TDataType ); tempAllocator.deallocate( reinterpret_cast<PxU8*>(theStartData) ); } tempBuffer.releaseBuffer(); } } template<typename TDataType> inline void readStridedBufferProperty( XmlReader& ioReader, const char* inPropName, TDataType*& outData, PxU32& outStride, PxU32& outCount, XmlMemoryAllocator& inAllocator) { const char* theSrcData; outStride = sizeof( TDataType ); outData = NULL; outCount = 0; if ( ioReader.read( inPropName, theSrcData ) ) { XmlMemoryAllocateMemoryPoolAllocator tempAllocator( &inAllocator ); MemoryBufferBase<XmlMemoryAllocateMemoryPoolAllocator> tempBuffer( &tempAllocator ); if ( theSrcData ) { static PxU32 theCount = 0; ++theCount; char* theStartData = const_cast< char*>( copyStr( &tempAllocator, theSrcData ) ); const char* theData = theStartData; while( !isEmpty(theData) ) { //These buffers are whitespace delimited. TDataType theType; strtoLong( theType, theData ); tempBuffer.write( &theType, sizeof(theType) ); } outData = reinterpret_cast< TDataType* >( tempBuffer.mBuffer ); outCount = tempBuffer.mWriteOffset / sizeof( TDataType ); tempAllocator.deallocate( reinterpret_cast<PxU8*>(theStartData) ); } tempBuffer.releaseBuffer(); } } template<typename TDataType> inline void readStridedBufferProperty( XmlReader& ioReader, const char* inPropName, PxStridedData& ioData, PxU32& outCount, XmlMemoryAllocator& inAllocator) { TDataType* tempData = NULL; readStridedBufferProperty<TDataType>( ioReader, inPropName, tempData, ioData.stride, outCount, inAllocator ); ioData.data = tempData; } template<typename TDataType> inline void readStridedBufferProperty( XmlReader& ioReader, const char* inPropName, PxTypedStridedData<TDataType>& ioData, PxU32& outCount, XmlMemoryAllocator& inAllocator) { TDataType* tempData = NULL; readStridedBufferProperty<TDataType>( ioReader, inPropName, tempData, ioData.stride, outCount, inAllocator ); ioData.data = reinterpret_cast<PxMaterialTableIndex*>( tempData ); } template<typename TDataType> inline void readStridedBufferProperty( XmlReader& ioReader, const char* inPropName, PxBoundedData& ioData, XmlMemoryAllocator& inAllocator) { return readStridedBufferProperty<TDataType>( ioReader, inPropName, ioData, ioData.count, inAllocator ); } } } #endif
7,210
C
35.419192
173
0.725936
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepX1_0Defaults.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. DEFINE_REPX_DEFAULT_PROPERTY("PxBoxGeometry.HalfExtents", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphereGeometry.Radius", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.Scale.Scale", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.Scale.Rotation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxConvexMeshGeometry.ConvexMesh", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.Scale.Scale", "1 1 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.Scale.Rotation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.MeshFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTriangleMeshGeometry.TriangleMesh", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightField", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.RowScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.ColumnScale", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxHeightFieldGeometry.HeightFieldFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Length", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Mass", "1000" ) DEFINE_REPX_DEFAULT_PROPERTY("PxTolerancesScale.Speed", "10" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DynamicFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.StaticFriction", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DynamicFrictionV", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.StaticFrictionV", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.DirOfAnisotropy", "1 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.FrictionCombineMode", "eAVERAGE" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.RestitutionCombineMode", "eAVERAGE" ) DEFINE_REPX_DEFAULT_PROPERTY("PxMaterial.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.LocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.SimulationFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.QueryFilterData", "0 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.ContactOffset", "0.02" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.RestOffset", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.Flags", "eSIMULATION_SHAPE|eSCENE_QUERY_SHAPE|eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxShape.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidStatic.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.CMassLocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.Mass", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.MassSpaceInertiaTensor", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.LinearVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.AngularVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.LinearDamping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.AngularDamping", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.MaxAngularVelocity", "7" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SleepEnergyThreshold", "0.005" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SolverIterationCounts.minPositionIters", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.SolverIterationCounts.minVelocityIters", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.ContactReportThreshold", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRigidDynamic.RigidDynamicFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ParentPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ChildPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TargetOrientation", "0 0 0 1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TargetVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.InternalCompliance", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.ExternalCompliance", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimit.yLimit", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimit.zLimit", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.SwingLimitEnabled", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimit.lower", "-0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimit.upper", "0.78539816339" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationJoint.TwistLimitEnabled", "false" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.ActorFlags", "eVISUALIZATION" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.DominanceGroup", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.OwnerClient", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.ClientBehaviorBits", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.CMassLocalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.Mass", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.MassSpaceInertiaTensor", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.GlobalPose", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.LinearVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulationLink.AngularVelocity", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.MaxProjectionIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SeparationTolerance", "0.1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.InternalDriveIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.ExternalDriveIterations", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SolverIterationCounts.minPositionIters", "4" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.SolverIterationCounts.minVelocityIters", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxArticulation.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eX", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eY", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eZ", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eTWIST", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eSWING1", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Motion.eSWING2", "eLOCKED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.LinearLimit.Value", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Upper", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.TwistLimit.Lower", "-1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.YAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.SwingLimit.ZAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eX.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eY.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eZ.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSWING.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eTWIST.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.ForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.Drive.eSLERP.Flags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DrivePosition", "0 0 0 1 0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DriveVelocity.linear", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.DriveVelocity.angular", "0 0 0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxD6Joint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxFixedJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.MinDistance", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.MaxDistance", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Tolerance", "0.025" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxDistanceJoint.DistanceJointFlags", "eMAX_DISTANCE_ENABLED" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Upper", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.Limit.Lower", "-1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveVelocity", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveForceLimit", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.DriveGearRatio", "1" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.RevoluteJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxRevoluteJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.ContactDistance", "0.01" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Upper", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.Limit.Lower", "-3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.PrismaticJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("PxPrismaticJoint.ProjectionAngularTolerance", "3.14159" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.BreakForce.force", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.BreakForce.torque", "3.40282e+038" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.ConstraintFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.Name", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.UserData", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Restitution", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Spring", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.Damping", "0" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.ContactDistance", "0.05" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.YAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.LimitCone.ZAngle", "1.5708" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.SphericalJointFlags", "" ) DEFINE_REPX_DEFAULT_PROPERTY("PxSphericalJoint.ProjectionLinearTolerance", "1e+010" ) DEFINE_REPX_DEFAULT_PROPERTY("THEEND", "false" )
17,457
C
70.257143
102
0.774589
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepXSerializerImpl.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_REPX_SERIALIZER_IMPL_H #define SN_REPX_SERIALIZER_IMPL_H #include "foundation/PxUserAllocated.h" #include "SnXmlVisitorWriter.h" #include "SnXmlVisitorReader.h" namespace physx { using namespace Sn; /** * The repx serializer impl takes the raw, untyped repx extension interface * and implements the simpler functions plus does the reinterpret-casts required * for any object to implement the serializer safely. */ template<typename TLiveType> struct RepXSerializerImpl : public PxRepXSerializer, PxUserAllocated { protected: RepXSerializerImpl( const RepXSerializerImpl& inOther ); RepXSerializerImpl& operator=( const RepXSerializerImpl& inOther ); public: PxAllocatorCallback& mAllocator; RepXSerializerImpl( PxAllocatorCallback& inAllocator ) : mAllocator( inAllocator ) { } virtual const char* getTypeName() { return PxTypeInfo<TLiveType>::name(); } virtual void objectToFile( const PxRepXObject& inLiveObject, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& inArgs ) { const TLiveType* theObj = reinterpret_cast<const TLiveType*>( inLiveObject.serializable ); objectToFileImpl( theObj, inCollection, inWriter, inTempBuffer, inArgs ); } virtual PxRepXObject fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) { TLiveType* theObj( allocateObject( inArgs ) ); if ( theObj ) if(fileToObjectImpl( theObj, inReader, inAllocator, inArgs, inCollection )) return PxCreateRepXObject(theObj); return PxRepXObject(); } virtual void objectToFileImpl( const TLiveType* inObj, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& /*inArgs*/) { writeAllProperties( inObj, inWriter, inTempBuffer, *inCollection ); } virtual bool fileToObjectImpl( TLiveType* inObj, XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) { return readAllProperties( inArgs, inReader, inObj, inAllocator, *inCollection ); } virtual TLiveType* allocateObject( PxRepXInstantiationArgs& inArgs ) = 0; }; } #endif
3,942
C
42.32967
173
0.767377
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlImpl.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_IMPL_H #define SN_XML_IMPL_H #include "SnXmlMemoryPool.h" #include "foundation/PxString.h" #include "foundation/PxMemory.h" namespace physx { namespace Sn { typedef CMemoryPoolManager TMemoryPoolManager; namespace snXmlImpl { inline PxU32 strLen( const char* inStr ) { PxU32 len = 0; if ( inStr ) { while ( *inStr ) { ++len; ++inStr; } } return len; } } inline const char* copyStr( PxAllocatorCallback& inAllocator, const char* inStr ) { if ( inStr && *inStr ) { PxU32 theLen = snXmlImpl::strLen( inStr ); //The memory will never be released by repx. If you want it released, you need to pass in a custom allocator //that tracks all allocations and releases unreleased allocations yourself. char* dest = reinterpret_cast<char* >( inAllocator.allocate( theLen + 1, "Repx::const char*", PX_FL ) ); PxMemCopy( dest, inStr, theLen ); dest[theLen] = 0; return dest; } return ""; } template<typename TManagerType> inline const char* copyStr( TManagerType* inMgr, const char* inStr ) { if ( inStr && *inStr ) { PxU32 theLen = snXmlImpl::strLen( inStr ); char* dest = reinterpret_cast<char* >( inMgr->allocate( theLen + 1 ) ); PxMemCopy( dest, inStr, theLen ); dest[theLen] = 0; return dest; } return ""; } inline void releaseStr( TMemoryPoolManager* inMgr, const char* inStr, PxU32 ) { if ( inStr && *inStr ) { inMgr->deallocate( reinterpret_cast< PxU8* >( const_cast<char*>( inStr ) ) ); } } inline void releaseStr( TMemoryPoolManager* inMgr, const char* inStr ) { if ( inStr && *inStr ) { PxU32 theLen = snXmlImpl::strLen( inStr ); releaseStr( inMgr, inStr, theLen ); } } struct XmlNode { const char* mName; //Never released until all collections are released const char* mData; //Never released until all collections are released XmlNode* mNextSibling; XmlNode* mPreviousSibling; XmlNode* mFirstChild; XmlNode* mParent; XmlNode( const XmlNode& ); XmlNode& operator=( const XmlNode& ); PX_INLINE void initPtrs() { mNextSibling = NULL; mPreviousSibling = NULL; mFirstChild = NULL; mParent = NULL; } PX_INLINE XmlNode( const char* inName = "", const char* inData = "" ) : mName( inName ) , mData( inData ) { initPtrs(); } void addChild( XmlNode* inItem ) { inItem->mParent = this; if ( mFirstChild == NULL ) mFirstChild = inItem; else { XmlNode* theNode = mFirstChild; //Follow the chain till the end. while( theNode->mNextSibling != NULL ) theNode = theNode->mNextSibling; theNode->mNextSibling = inItem; inItem->mPreviousSibling = theNode; } } PX_INLINE XmlNode* findChildByName( const char* inName ) { for ( XmlNode* theNode = mFirstChild; theNode; theNode = theNode->mNextSibling ) { XmlNode* theRepXNode = theNode; if ( physx::Pxstricmp( theRepXNode->mName, inName ) == 0 ) return theNode; } return NULL; } PX_INLINE void orphan() { if ( mParent ) { if ( mParent->mFirstChild == this ) mParent->mFirstChild = mNextSibling; } if ( mPreviousSibling ) mPreviousSibling->mNextSibling = mNextSibling; if ( mNextSibling ) mNextSibling->mPreviousSibling = mPreviousSibling; if ( mFirstChild ) mFirstChild->mParent = NULL; initPtrs(); } }; inline XmlNode* allocateRepXNode( TMemoryPoolManager* inManager, const char* inName, const char* inData ) { XmlNode* retval = inManager->allocate<XmlNode>(); retval->mName = copyStr( inManager, inName ); retval->mData = copyStr( inManager, inData ); return retval; } inline void release( TMemoryPoolManager* inManager, XmlNode* inNode ) { //We *don't* release the strings associated with the node //because they could be shared. Instead, we just let them 'leak' //in some sense, at least until the memory manager itself is deleted. //DO NOT UNCOMMENT THE LINES BELOW!! //releaseStr( inManager, inNode->mName ); //releaseStr( inManager, inNode->mData ); inManager->deallocate( inNode ); } static PX_INLINE void releaseNodeAndChildren( TMemoryPoolManager* inManager, XmlNode* inNode ) { if ( inNode->mFirstChild ) { XmlNode* childNode( inNode->mFirstChild ); while( childNode ) { XmlNode* _node( childNode ); childNode = _node->mNextSibling; releaseNodeAndChildren( inManager, _node ); } } inNode->orphan(); release( inManager, inNode ); } static XmlNode* copyRepXNodeAndSiblings( TMemoryPoolManager* inManager, const XmlNode* inNode, XmlNode* inParent ); static XmlNode* copyRepXNode( TMemoryPoolManager* inManager, const XmlNode* inNode, XmlNode* inParent = NULL ) { XmlNode* newNode( allocateRepXNode( inManager, NULL, NULL ) ); newNode->mName = inNode->mName; //Some light structural sharing newNode->mData = inNode->mData; //Some light structural sharing newNode->mParent = inParent; if ( inNode->mFirstChild ) newNode->mFirstChild = copyRepXNodeAndSiblings( inManager, inNode->mFirstChild, newNode ); return newNode; } static XmlNode* copyRepXNodeAndSiblings( TMemoryPoolManager* inManager, const XmlNode* inNode, XmlNode* inParent ) { XmlNode* sibling = inNode->mNextSibling; if ( sibling ) sibling = copyRepXNodeAndSiblings( inManager, sibling, inParent ); XmlNode* newNode = copyRepXNode( inManager, inNode, inParent ); newNode->mNextSibling = sibling; if ( sibling ) sibling->mPreviousSibling = newNode; return newNode; } inline bool isBigEndian() { int i = 1; return *(reinterpret_cast<char*>(&i))==0; } struct NameStackEntry { const char* mName; bool mOpen; NameStackEntry( const char* nm ) : mName( nm ), mOpen( false ) {} }; typedef PxProfileArray<NameStackEntry> TNameStack; } } #endif
7,484
C
29.676229
116
0.699359
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlSimpleXmlWriter.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_SIMPLE_XML_WRITER_H #define SN_XML_SIMPLE_XML_WRITER_H #include "foundation/PxArray.h" #include "SnXmlMemoryPoolStreams.h" namespace physx { namespace Sn { class XmlWriter { public: struct STagWatcher { typedef XmlWriter TXmlWriterType; TXmlWriterType& mWriter; STagWatcher( const STagWatcher& inOther ); STagWatcher& operator-( const STagWatcher& inOther ); STagWatcher( TXmlWriterType& inWriter, const char* inTagName ) : mWriter( inWriter ) { mWriter.beginTag( inTagName ); } ~STagWatcher() { mWriter.endTag(); } }; virtual ~XmlWriter(){} virtual void beginTag( const char* inTagname ) = 0; virtual void endTag() = 0; virtual void addAttribute( const char* inName, const char* inValue ) = 0; virtual void writeContentTag( const char* inTag, const char* inContent ) = 0; virtual void addContent( const char* inContent ) = 0; virtual PxU32 tabCount() = 0; }; template<typename TStreamType> class XmlWriterImpl : public XmlWriter { PxProfileAllocatorWrapper mWrapper; TStreamType& mStream; XmlWriterImpl( const XmlWriterImpl& inOther ); XmlWriterImpl& operator=( const XmlWriterImpl& inOther ); PxProfileArray<const char*> mTags; bool mTagOpen; PxU32 mInitialTagDepth; public: XmlWriterImpl( TStreamType& inStream, PxAllocatorCallback& inAllocator, PxU32 inInitialTagDepth = 0 ) : mWrapper( inAllocator ) , mStream( inStream ) , mTags( mWrapper ) , mTagOpen( false ) , mInitialTagDepth( inInitialTagDepth ) { } virtual ~XmlWriterImpl() { while( mTags.size() ) endTag(); } PxU32 tabCount() { return mTags.size() + mInitialTagDepth; } void writeTabs( PxU32 inSize ) { inSize += mInitialTagDepth; for ( PxU32 idx =0; idx < inSize; ++idx ) mStream << "\t"; } void beginTag( const char* inTagname ) { closeTag(); writeTabs(mTags.size()); mTags.pushBack( inTagname ); mStream << "<" << inTagname; mTagOpen = true; } void addAttribute( const char* inName, const char* inValue ) { PX_ASSERT( mTagOpen ); mStream << " " << inName << "=" << "\"" << inValue << "\""; } void closeTag(bool useNewline = true) { if ( mTagOpen ) { mStream << " " << ">"; if (useNewline ) mStream << "\n"; } mTagOpen = false; } void doEndOpenTag() { mStream << "</" << mTags.back() << ">" << "\n"; } void endTag() { PX_ASSERT( mTags.size() ); if ( mTagOpen ) mStream << " " << "/>" << "\n"; else { writeTabs(mTags.size()-1); doEndOpenTag(); } mTagOpen = false; mTags.popBack(); } void addContent( const char* inContent ) { closeTag(false); mStream << inContent; } void writeContentTag( const char* inTag, const char* inContent ) { beginTag( inTag ); addContent( inContent ); doEndOpenTag(); mTags.popBack(); } void insertXml( const char* inXml ) { closeTag(); mStream << inXml; } }; struct BeginTag { const char* mTagName; BeginTag( const char* inTagName ) : mTagName( inTagName ) { } }; struct EndTag { EndTag() {} }; struct Att { const char* mAttName; const char* mAttValue; Att( const char* inAttName, const char* inAttValue ) : mAttName( inAttName ) , mAttValue( inAttValue ) { } }; struct Content { const char* mContent; Content( const char* inContent ) : mContent( inContent ) { } }; struct ContentTag { const char* mTagName; const char* mContent; ContentTag( const char* inTagName, const char* inContent ) : mTagName( inTagName ) , mContent( inContent ) { } }; inline XmlWriter& operator<<( XmlWriter& inWriter, const BeginTag& inTag ) { inWriter.beginTag( inTag.mTagName ); return inWriter; } inline XmlWriter& operator<<( XmlWriter& inWriter, const EndTag& inTag ) { inWriter.endTag(); return inWriter; } inline XmlWriter& operator<<( XmlWriter& inWriter, const Att& inTag ) { inWriter.addAttribute(inTag.mAttName, inTag.mAttValue); return inWriter; } inline XmlWriter& operator<<( XmlWriter& inWriter, const Content& inTag ) { inWriter.addContent(inTag.mContent); return inWriter; } inline XmlWriter& operator<<( XmlWriter& inWriter, const ContentTag& inTag ) { inWriter.writeContentTag(inTag.mTagName, inTag.mContent); return inWriter; } inline void writeProperty( XmlWriter& inWriter, MemoryBuffer& tempBuffer, const char* inPropName ) { PxU8 data = 0; tempBuffer.write( &data, sizeof(PxU8) ); inWriter.writeContentTag( inPropName, reinterpret_cast<const char*>( tempBuffer.mBuffer ) ); tempBuffer.clear(); } template<typename TDataType> inline void writeProperty( XmlWriter& inWriter, MemoryBuffer& tempBuffer, const char* inPropName, TDataType inValue ) { tempBuffer << inValue; writeProperty( inWriter, tempBuffer, inPropName ); } } } #endif
6,529
C
29.372093
156
0.69153
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnRepXCoreSerializer.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 "PxPhysicsAPI.h" #include "PxMetaDataObjects.h" #include "SnPxStreamOperators.h" #include "foundation/PxUtilities.h" #include "SnXmlImpl.h" #include "SnXmlSerializer.h" #include "SnXmlDeserializer.h" #include "SnRepXCoreSerializer.h" using namespace physx::Sn; namespace physx { typedef PxReadOnlyPropertyInfo<PxPropertyInfoName::PxArticulationLink_InboundJoint, PxArticulationLink, PxArticulationJointReducedCoordinate *> TIncomingJointPropType; //************************************************************* // Actual RepXSerializer implementations for PxMaterial //************************************************************* PxMaterial* PxMaterialRepXSerializer::allocateObject( PxRepXInstantiationArgs& inArgs ) { return inArgs.physics.createMaterial(0, 0, 0); } PxRepXObject PxShapeRepXSerializer::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) { PxProfileAllocatorWrapper wrapper( inAllocator.getAllocator() ); TReaderNameStack names( wrapper ); PxProfileArray<PxU32> contexts( wrapper ); bool hadError = false; RepXVisitorReader<PxShape> theVisitor( names, contexts, inArgs, inReader, NULL, inAllocator, *inCollection, hadError ); PxArray<PxMaterial*> materials; PxGeometry* geometry = NULL; parseShape( theVisitor, geometry, materials ); if(hadError) return PxRepXObject(); PxShape *theShape = inArgs.physics.createShape( *geometry, materials.begin(), PxTo16(materials.size()) ); switch(geometry->getType()) { case PxGeometryType::eSPHERE : static_cast<PxSphereGeometry*>(geometry)->~PxSphereGeometry(); break; case PxGeometryType::ePLANE : static_cast<PxPlaneGeometry*>(geometry)->~PxPlaneGeometry(); break; case PxGeometryType::eCAPSULE : static_cast<PxCapsuleGeometry*>(geometry)->~PxCapsuleGeometry(); break; case PxGeometryType::eBOX : static_cast<PxBoxGeometry*>(geometry)->~PxBoxGeometry(); break; case PxGeometryType::eCONVEXMESH : static_cast<PxConvexMeshGeometry*>(geometry)->~PxConvexMeshGeometry(); break; case PxGeometryType::eTRIANGLEMESH : static_cast<PxTriangleMeshGeometry*>(geometry)->~PxTriangleMeshGeometry(); break; case PxGeometryType::eHEIGHTFIELD : static_cast<PxHeightFieldGeometry*>(geometry)->~PxHeightFieldGeometry(); break; case PxGeometryType::eTETRAHEDRONMESH : static_cast<PxTetrahedronMeshGeometry*>(geometry)->~PxTetrahedronMeshGeometry(); break; case PxGeometryType::ePARTICLESYSTEM: static_cast<PxParticleSystemGeometry*>(geometry)->~PxParticleSystemGeometry(); break; case PxGeometryType::eHAIRSYSTEM: static_cast<PxHairSystemGeometry*>(geometry)->~PxHairSystemGeometry(); break; case PxGeometryType::eCUSTOM : static_cast<PxCustomGeometry*>(geometry)->~PxCustomGeometry(); break; case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: PX_ASSERT(0); } inAllocator.getAllocator().deallocate(geometry); bool ret = readAllProperties( inArgs, inReader, theShape, inAllocator, *inCollection ); return ret ? PxCreateRepXObject(theShape) : PxRepXObject(); } //************************************************************* // Actual RepXSerializer implementations for PxTriangleMesh //************************************************************* template<typename TTriIndexElem> inline void writeTriangle( MemoryBuffer& inTempBuffer, const Triangle<TTriIndexElem>& inTriangle ) { inTempBuffer << inTriangle.mIdx0 << " " << inTriangle.mIdx1 << " " << inTriangle.mIdx2; } PxU32 materialAccess( const PxTriangleMesh* inMesh, PxU32 inIndex ) { return inMesh->getTriangleMaterialIndex( inIndex ); } template<typename TDataType> void writeDatatype( MemoryBuffer& inTempBuffer, const TDataType& inType ) { inTempBuffer << inType; } void PxBVH33TriangleMeshRepXSerializer::objectToFileImpl( const PxBVH33TriangleMesh* mesh, PxCollection* /*inCollection*/, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& inArgs ) { bool hasMatIndex = mesh->getTriangleMaterialIndex(0) != 0xffff; PxU32 numVertices = mesh->getNbVertices(); const PxVec3* vertices = mesh->getVertices(); writeBuffer( inWriter, inTempBuffer, 2, vertices, numVertices, "Points", writePxVec3 ); bool isU16 = mesh->getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES ? true : false; PxU32 triCount = mesh->getNbTriangles(); const void* indices = mesh->getTriangles(); if ( isU16 ) writeBuffer( inWriter, inTempBuffer, 2, reinterpret_cast<const Triangle<PxU16>* >( indices ), triCount, "Triangles", writeTriangle<PxU16> ); else writeBuffer( inWriter, inTempBuffer, 2, reinterpret_cast<const Triangle<PxU32>* >( indices ), triCount, "Triangles", writeTriangle<PxU32> ); if ( hasMatIndex ) writeBuffer( inWriter, inTempBuffer, 6, mesh, materialAccess, triCount, "materialIndices", writeDatatype<PxU32> ); //Cooked stream PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVertices; meshDesc.points.data = vertices; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = triCount; meshDesc.triangles.data = indices; meshDesc.triangles.stride = isU16?3*sizeof(PxU16):3*sizeof(PxU32); if(isU16) { meshDesc.triangles.stride = sizeof(PxU16)*3; meshDesc.flags |= PxMeshFlag::e16_BIT_INDICES; } else { meshDesc.triangles.stride = sizeof(PxU32)*3; } if(hasMatIndex) { PxMaterialTableIndex* materialIndices = new PxMaterialTableIndex[triCount]; for(PxU32 i = 0; i < triCount; i++) materialIndices[i] = mesh->getTriangleMaterialIndex(i); meshDesc.materialIndices.data = materialIndices; meshDesc.materialIndices.stride = sizeof(PxMaterialTableIndex); } if(inArgs.cooker != NULL) { TMemoryPoolManager theManager(mAllocator); MemoryBuffer theTempBuf( &theManager ); theTempBuf.clear(); PxCookTriangleMesh( *inArgs.cooker, meshDesc, theTempBuf ); writeBuffer( inWriter, inTempBuffer, 16, theTempBuf.mBuffer, theTempBuf.mWriteOffset, "CookedData", writeDatatype<PxU8> ); } delete []meshDesc.materialIndices.data; } PxRepXObject PxBVH33TriangleMeshRepXSerializer::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* /*inCollection*/ ) { //We can't do a simple inverse; we *have* to cook data to get a mesh. PxTriangleMeshDesc theDesc; readStridedBufferProperty<PxVec3>( inReader, "points", theDesc.points, inAllocator); readStridedBufferProperty<Triangle<PxU32> >( inReader, "triangles", theDesc.triangles, inAllocator); PxU32 triCount; readStridedBufferProperty<PxMaterialTableIndex>( inReader, "materialIndices", theDesc.materialIndices, triCount, inAllocator); PxStridedData cookedData; cookedData.stride = sizeof(PxU8); PxU32 dataSize; readStridedBufferProperty<PxU8>( inReader, "CookedData", cookedData, dataSize, inAllocator); TMemoryPoolManager theManager(inAllocator.getAllocator()); MemoryBuffer theTempBuf( &theManager ); // PxTriangleMesh* theMesh = NULL; PxBVH33TriangleMesh* theMesh = NULL; if(dataSize != 0) { theTempBuf.write(cookedData.data, dataSize*sizeof(PxU8)); // theMesh = inArgs.physics.createTriangleMesh( theTempBuf ); theMesh = static_cast<PxBVH33TriangleMesh*>(inArgs.physics.createTriangleMesh( theTempBuf )); } if(theMesh == NULL) { PX_ASSERT(inArgs.cooker); theTempBuf.clear(); PxCookingParams params = *inArgs.cooker; params.midphaseDesc = PxMeshMidPhase::eBVH33; PxCookTriangleMesh( params, theDesc, theTempBuf ); // theMesh = inArgs.physics.createTriangleMesh( theTempBuf ); theMesh = static_cast<PxBVH33TriangleMesh*>(inArgs.physics.createTriangleMesh( theTempBuf )); } return PxCreateRepXObject( theMesh ); } void PxBVH34TriangleMeshRepXSerializer::objectToFileImpl( const PxBVH34TriangleMesh* mesh, PxCollection* /*inCollection*/, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& inArgs ) { bool hasMatIndex = mesh->getTriangleMaterialIndex(0) != 0xffff; PxU32 numVertices = mesh->getNbVertices(); const PxVec3* vertices = mesh->getVertices(); writeBuffer( inWriter, inTempBuffer, 2, vertices, numVertices, "Points", writePxVec3 ); bool isU16 = mesh->getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES ? true : false; PxU32 triCount = mesh->getNbTriangles(); const void* indices = mesh->getTriangles(); if ( isU16 ) writeBuffer( inWriter, inTempBuffer, 2, reinterpret_cast<const Triangle<PxU16>* >( indices ), triCount, "Triangles", writeTriangle<PxU16> ); else writeBuffer( inWriter, inTempBuffer, 2, reinterpret_cast<const Triangle<PxU32>* >( indices ), triCount, "Triangles", writeTriangle<PxU32> ); if ( hasMatIndex ) writeBuffer( inWriter, inTempBuffer, 6, mesh, materialAccess, triCount, "materialIndices", writeDatatype<PxU32> ); //Cooked stream PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVertices; meshDesc.points.data = vertices; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = triCount; meshDesc.triangles.data = indices; meshDesc.triangles.stride = isU16?3*sizeof(PxU16):3*sizeof(PxU32); if(isU16) { meshDesc.triangles.stride = sizeof(PxU16)*3; meshDesc.flags |= PxMeshFlag::e16_BIT_INDICES; } else { meshDesc.triangles.stride = sizeof(PxU32)*3; } if(hasMatIndex) { PxMaterialTableIndex* materialIndices = new PxMaterialTableIndex[triCount]; for(PxU32 i = 0; i < triCount; i++) materialIndices[i] = mesh->getTriangleMaterialIndex(i); meshDesc.materialIndices.data = materialIndices; meshDesc.materialIndices.stride = sizeof(PxMaterialTableIndex); } if(inArgs.cooker != NULL) { TMemoryPoolManager theManager(mAllocator); MemoryBuffer theTempBuf( &theManager ); theTempBuf.clear(); PxCookTriangleMesh( *inArgs.cooker, meshDesc, theTempBuf ); writeBuffer( inWriter, inTempBuffer, 16, theTempBuf.mBuffer, theTempBuf.mWriteOffset, "CookedData", writeDatatype<PxU8> ); } delete []meshDesc.materialIndices.data; } PxRepXObject PxBVH34TriangleMeshRepXSerializer::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* /*inCollection*/ ) { //We can't do a simple inverse; we *have* to cook data to get a mesh. PxTriangleMeshDesc theDesc; readStridedBufferProperty<PxVec3>( inReader, "points", theDesc.points, inAllocator); readStridedBufferProperty<Triangle<PxU32> >( inReader, "triangles", theDesc.triangles, inAllocator); PxU32 triCount; readStridedBufferProperty<PxMaterialTableIndex>( inReader, "materialIndices", theDesc.materialIndices, triCount, inAllocator); PxStridedData cookedData; cookedData.stride = sizeof(PxU8); PxU32 dataSize; readStridedBufferProperty<PxU8>( inReader, "CookedData", cookedData, dataSize, inAllocator); TMemoryPoolManager theManager(inAllocator.getAllocator()); MemoryBuffer theTempBuf( &theManager ); // PxTriangleMesh* theMesh = NULL; PxBVH34TriangleMesh* theMesh = NULL; if(dataSize != 0) { theTempBuf.write(cookedData.data, dataSize*sizeof(PxU8)); // theMesh = inArgs.physics.createTriangleMesh( theTempBuf ); theMesh = static_cast<PxBVH34TriangleMesh*>(inArgs.physics.createTriangleMesh( theTempBuf )); } if(theMesh == NULL) { PX_ASSERT(inArgs.cooker); theTempBuf.clear(); PxCookingParams params = *inArgs.cooker; params.midphaseDesc = PxMeshMidPhase::eBVH34; PxCookTriangleMesh( params, theDesc, theTempBuf ); // theMesh = inArgs.physics.createTriangleMesh( theTempBuf ); theMesh = static_cast<PxBVH34TriangleMesh*>(inArgs.physics.createTriangleMesh( theTempBuf )); } return PxCreateRepXObject(theMesh); } //************************************************************* // Actual RepXSerializer implementations for PxHeightField //************************************************************* void PxHeightFieldRepXSerializer::objectToFileImpl( const PxHeightField* inHeightField, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& /*inArgs*/) { PxHeightFieldDesc theDesc; theDesc.nbRows = inHeightField->getNbRows(); theDesc.nbColumns = inHeightField->getNbColumns(); theDesc.format = inHeightField->getFormat(); theDesc.samples.stride = inHeightField->getSampleStride(); theDesc.samples.data = NULL; theDesc.convexEdgeThreshold = inHeightField->getConvexEdgeThreshold(); theDesc.flags = inHeightField->getFlags(); PxU32 theCellCount = inHeightField->getNbRows() * inHeightField->getNbColumns(); PxU32 theSampleStride = sizeof( PxHeightFieldSample ); PxU32 theSampleBufSize = theCellCount * theSampleStride; PxHeightFieldSample* theSamples = reinterpret_cast< PxHeightFieldSample*> ( inTempBuffer.mManager->allocate( theSampleBufSize ) ); inHeightField->saveCells( theSamples, theSampleBufSize ); theDesc.samples.data = theSamples; writeAllProperties( &theDesc, inWriter, inTempBuffer, *inCollection ); writeStridedBufferProperty<PxHeightFieldSample>( inWriter, inTempBuffer, "samples", theDesc.samples, theDesc.nbRows * theDesc.nbColumns, 6, writeHeightFieldSample); inTempBuffer.mManager->deallocate( reinterpret_cast<PxU8*>(theSamples) ); } PxRepXObject PxHeightFieldRepXSerializer::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) { PX_ASSERT(inArgs.cooker); PxHeightFieldDesc theDesc; readAllProperties( inArgs, inReader, &theDesc, inAllocator, *inCollection ); //Now read the data... PxU32 count = 0; //ignored becaues numRows and numColumns tells the story readStridedBufferProperty<PxHeightFieldSample>( inReader, "samples", theDesc.samples, count, inAllocator); PxHeightField* retval = PxCreateHeightField( theDesc, inArgs.physics.getPhysicsInsertionCallback() ); return PxCreateRepXObject(retval); } //************************************************************* // Actual RepXSerializer implementations for PxConvexMesh //************************************************************* void PxConvexMeshRepXSerializer::objectToFileImpl( const PxConvexMesh* mesh, PxCollection* /*inCollection*/, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& inArgs ) { writeBuffer( inWriter, inTempBuffer, 2, mesh->getVertices(), mesh->getNbVertices(), "points", writePxVec3 ); if(inArgs.cooker != NULL) { //Cache cooked Data PxConvexMeshDesc theDesc; theDesc.points.data = mesh->getVertices(); theDesc.points.stride = sizeof(PxVec3); theDesc.points.count = mesh->getNbVertices(); theDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; TMemoryPoolManager theManager(mAllocator); MemoryBuffer theTempBuf( &theManager ); PxCookConvexMesh( *inArgs.cooker, theDesc, theTempBuf ); writeBuffer( inWriter, inTempBuffer, 16, theTempBuf.mBuffer, theTempBuf.mWriteOffset, "CookedData", writeDatatype<PxU8> ); } } //Conversion from scene object to descriptor. PxRepXObject PxConvexMeshRepXSerializer::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* /*inCollection*/) { PxConvexMeshDesc theDesc; readStridedBufferProperty<PxVec3>( inReader, "points", theDesc.points, inAllocator); theDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; PxStridedData cookedData; cookedData.stride = sizeof(PxU8); PxU32 dataSize; readStridedBufferProperty<PxU8>( inReader, "CookedData", cookedData, dataSize, inAllocator); TMemoryPoolManager theManager(inAllocator.getAllocator()); MemoryBuffer theTempBuf( &theManager ); PxConvexMesh* theMesh = NULL; if(dataSize != 0) { theTempBuf.write(cookedData.data, dataSize*sizeof(PxU8)); theMesh = inArgs.physics.createConvexMesh( theTempBuf ); } if(theMesh == NULL) { PX_ASSERT(inArgs.cooker); theTempBuf.clear(); PxCookConvexMesh( *inArgs.cooker, theDesc, theTempBuf ); theMesh = inArgs.physics.createConvexMesh( theTempBuf ); } return PxCreateRepXObject(theMesh); } //************************************************************* // Actual RepXSerializer implementations for PxRigidStatic //************************************************************* PxRigidStatic* PxRigidStaticRepXSerializer::allocateObject( PxRepXInstantiationArgs& inArgs ) { return inArgs.physics.createRigidStatic( PxTransform(PxIdentity) ); } //************************************************************* // Actual RepXSerializer implementations for PxRigidDynamic //************************************************************* PxRigidDynamic* PxRigidDynamicRepXSerializer::allocateObject( PxRepXInstantiationArgs& inArgs ) { return inArgs.physics.createRigidDynamic( PxTransform(PxIdentity) ); } //************************************************************* // Actual RepXSerializer implementations for PxArticulationReducedCoordinate //************************************************************* void PxArticulationReducedCoordinateRepXSerializer::objectToFileImpl(const PxArticulationReducedCoordinate* inObj, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& /*inArgs*/) { TNameStack nameStack(inTempBuffer.mManager->mWrapper); Sn::TArticulationLinkLinkMap linkMap(inTempBuffer.mManager->mWrapper); RepXVisitorWriter<PxArticulationReducedCoordinate> writer(nameStack, inWriter, inObj, inTempBuffer, *inCollection, &linkMap); RepXPropertyFilter<RepXVisitorWriter<PxArticulationReducedCoordinate> > theOp(writer); visitAllProperties<PxArticulationReducedCoordinate>(theOp); } PxArticulationReducedCoordinate* PxArticulationReducedCoordinateRepXSerializer::allocateObject(PxRepXInstantiationArgs& inArgs) { return inArgs.physics.createArticulationReducedCoordinate(); } //************************************************************* // Actual RepXSerializer implementations for PxAggregate //************************************************************* void PxAggregateRepXSerializer::objectToFileImpl( const PxAggregate* data, PxCollection* inCollection, XmlWriter& inWriter, MemoryBuffer& inTempBuffer, PxRepXInstantiationArgs& /*inArgs*/) { PxArticulationLink *link = NULL; inWriter.addAndGotoChild( "Actors" ); for(PxU32 i = 0; i < data->getNbActors(); ++i) { PxActor* actor; if(data->getActors(&actor, 1, i)) { link = actor->is<PxArticulationLink>(); } if(link && !link->getInboundJoint() ) { writeProperty( inWriter, *inCollection, inTempBuffer, "PxArticulationRef", &link->getArticulation()); } else if( !link ) { PxSerialObjectId theId = 0; theId = inCollection->getId( *actor ); if( theId == 0 ) theId = static_cast<uint64_t>(size_t(actor)); writeProperty( inWriter, *inCollection, inTempBuffer, "PxActorRef", theId ); } } inWriter.leaveChild( ); writeProperty( inWriter, *inCollection, inTempBuffer, "NumActors", data->getNbActors() ); writeProperty( inWriter, *inCollection, inTempBuffer, "MaxNbActors", data->getMaxNbActors() ); writeProperty(inWriter, *inCollection, inTempBuffer, "MaxNbShapes", data->getMaxNbShapes()); writeProperty( inWriter, *inCollection, inTempBuffer, "SelfCollision", data->getSelfCollision() ); writeAllProperties( data, inWriter, inTempBuffer, *inCollection ); } PxRepXObject PxAggregateRepXSerializer::fileToObject( XmlReader& inReader, XmlMemoryAllocator& inAllocator, PxRepXInstantiationArgs& inArgs, PxCollection* inCollection ) { PxU32 numActors; readProperty( inReader, "NumActors", numActors ); PxU32 maxNbActors; readProperty( inReader, "MaxNbActors", maxNbActors ); PxU32 maxNbShapes; readProperty(inReader, "MaxNbShapes", maxNbShapes); bool selfCollision; bool ret = readProperty( inReader, "SelfCollision", selfCollision ); PxAggregate* theAggregate = inArgs.physics.createAggregate(maxNbActors, maxNbShapes, selfCollision); ret &= readAllProperties( inArgs, inReader, theAggregate, inAllocator, *inCollection ); inReader.pushCurrentContext(); if ( inReader.gotoChild( "Actors" ) ) { inReader.pushCurrentContext(); for( bool matSuccess = inReader.gotoFirstChild(); matSuccess; matSuccess = inReader.gotoNextSibling() ) { const char* actorType = inReader.getCurrentItemName(); if ( 0 == physx::Pxstricmp( actorType, "PxActorRef" ) ) { PxActor *actor = NULL; ret &= readReference<PxActor>( inReader, *inCollection, actor ); if(actor) { PxScene *currScene = actor->getScene(); if(currScene) { currScene->removeActor(*actor); } theAggregate->addActor(*actor); } } else if ( 0 == physx::Pxstricmp( actorType, "PxArticulationRef" ) ) { PxArticulationReducedCoordinate* articulation = NULL; ret &= readReference<PxArticulationReducedCoordinate>( inReader, *inCollection, articulation ); if(articulation) { PxScene *currScene = articulation->getScene(); if(currScene) { currScene->removeArticulation(*articulation); } theAggregate->addArticulation(*articulation); } } } inReader.popCurrentContext(); inReader.leaveChild(); } inReader.popCurrentContext(); return ret ? PxCreateRepXObject(theAggregate) : PxRepXObject(); } }
23,216
C++
40.311388
229
0.720494
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlStringToType.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_STRING_TO_TYPE_H #define SN_XML_STRING_TO_TYPE_H #include "common/PxCoreUtilityTypes.h" #include "PxFiltering.h" #include "foundation/PxString.h" #include <stdio.h> #include <ctype.h> //Remapping function name for gcc-based systems. #ifndef _MSC_VER #define _strtoui64 strtoull #endif namespace physx { namespace Sn { template<typename TDataType> struct StrToImpl { bool compile_error; }; template<> struct StrToImpl<PxU64> { //Id's (void ptrs) are written to file as unsigned //64 bit integers, so this method gets called more //often than one might think. PX_INLINE void strto( PxU64& ioDatatype,const char*& ioData ) { ioDatatype = _strtoui64( ioData, const_cast<char **>(&ioData), 10 ); } }; PX_INLINE PxF32 strToFloat(const char *str,const char **nextScan) { PxF32 ret; while ( *str && isspace(static_cast<unsigned char>(*str))) str++; // skip leading whitespace char temp[256] = ""; char *dest = temp; char *end = &temp[255]; const char *begin = str; while ( *str && !isspace(static_cast<unsigned char>(*str)) && dest < end ) // copy the number up to the first whitespace or eos { *dest++ = *str++; } *dest = 0; ret = PxF32(strtod(temp,&end)); if ( nextScan ) { *nextScan = begin+(end-temp); } return ret; } template<> struct StrToImpl<PxU32> { PX_INLINE void strto( PxU32& ioDatatype,const char*& ioData ) { ioDatatype = static_cast<PxU32>( strtoul( ioData,const_cast<char **>(&ioData), 10 ) ); } }; template<> struct StrToImpl<PxI32> { PX_INLINE void strto( PxI32& ioDatatype,const char*& ioData ) { ioDatatype = static_cast<PxI32>( strtoul( ioData,const_cast<char **>(&ioData), 10 ) ); } }; template<> struct StrToImpl<PxU16> { PX_INLINE void strto( PxU16& ioDatatype,const char*& ioData ) { ioDatatype = static_cast<PxU16>( strtoul( ioData,const_cast<char **>(&ioData), 10 ) ); } }; PX_INLINE void eatwhite(const char*& ioData ) { if ( ioData ) { while( isspace( static_cast<unsigned char>(*ioData) ) ) ++ioData; } } // copy the source data to the dest buffer until the first whitespace is encountered. // Do not overflow the buffer based on the bufferLen provided. // Advance the input 'ioData' pointer so that it sits just at the next whitespace PX_INLINE void nullTerminateWhite(const char*& ioData,char *buffer,PxU32 bufferLen) { if ( ioData ) { char *eof = buffer+(bufferLen-1); char *dest = buffer; while( *ioData && !isspace(static_cast<unsigned char>(*ioData)) && dest < eof ) { *dest++ = *ioData++; } *dest = 0; } } inline void nonNullTerminateWhite(const char*& ioData ) { if ( ioData ) { while( *ioData && !isspace( static_cast<unsigned char>(*ioData) ) ) ++ioData; } } template<> struct StrToImpl<PxF32> { inline void strto( PxF32& ioDatatype,const char*& ioData ) { ioDatatype = strToFloat(ioData,&ioData); } }; template<> struct StrToImpl<void*> { inline void strto( void*& ioDatatype,const char*& ioData ) { PxU64 theData; StrToImpl<PxU64>().strto( theData, ioData ); ioDatatype = reinterpret_cast<void*>( size_t( theData ) ); } }; template<> struct StrToImpl<physx::PxVec3> { inline void strto( physx::PxVec3& ioDatatype,const char*& ioData ) { StrToImpl<PxF32>().strto( ioDatatype[0], ioData ); StrToImpl<PxF32>().strto( ioDatatype[1], ioData ); StrToImpl<PxF32>().strto( ioDatatype[2], ioData ); } }; template<> struct StrToImpl<PxU8*> { inline void strto( PxU8*& /*ioDatatype*/,const char*& /*ioData*/) { } }; template<> struct StrToImpl<bool> { inline void strto( bool& ioType,const char*& inValue ) { ioType = physx::Pxstricmp( inValue, "true" ) == 0 ? true : false; } }; template<> struct StrToImpl<PxU8> { PX_INLINE void strto( PxU8& ioType,const char* & inValue) { ioType = static_cast<PxU8>( strtoul( inValue,const_cast<char **>(&inValue), 10 ) ); } }; template<> struct StrToImpl<PxFilterData> { PX_INLINE void strto( PxFilterData& ioType,const char*& inValue) { ioType.word0 = static_cast<PxU32>( strtoul( inValue,const_cast<char **>(&inValue), 10 ) ); ioType.word1 = static_cast<PxU32>( strtoul( inValue,const_cast<char **>(&inValue), 10 ) ); ioType.word2 = static_cast<PxU32>( strtoul( inValue,const_cast<char **>(&inValue), 10 ) ); ioType.word3 = static_cast<PxU32>( strtoul( inValue, NULL, 10 ) ); } }; template<> struct StrToImpl<PxQuat> { PX_INLINE void strto( PxQuat& ioType,const char*& inValue ) { ioType.x = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.y = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.z = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.w = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); } }; template<> struct StrToImpl<PxTransform> { PX_INLINE void strto( PxTransform& ioType,const char*& inValue) { ioType.q.x = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.q.y = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.q.z = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.q.w = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.p[0] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.p[1] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.p[2] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); } }; template<> struct StrToImpl<PxBounds3> { PX_INLINE void strto( PxBounds3& ioType,const char*& inValue) { ioType.minimum[0] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.minimum[1] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.minimum[2] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.maximum[0] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.maximum[1] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.maximum[2] = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); } }; template<> struct StrToImpl<PxMetaDataPlane> { PX_INLINE void strto( PxMetaDataPlane& ioType,const char*& inValue) { ioType.normal.x = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.normal.y = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.normal.z = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); ioType.distance = static_cast<PxReal>( strToFloat( inValue, &inValue ) ); } }; template<> struct StrToImpl<PxRigidDynamic*> { PX_INLINE void strto( PxRigidDynamic*& /*ioDatatype*/,const char*& /*ioData*/) { } }; template<typename TDataType> inline void strto( TDataType& ioType,const char*& ioData ) { if ( ioData && *ioData ) StrToImpl<TDataType>().strto( ioType, ioData ); } template<typename TDataType> inline void strtoLong( TDataType& ioType,const char*& ioData ) { if ( ioData && *ioData ) StrToImpl<TDataType>().strto( ioType, ioData ); } template<typename TDataType> inline void stringToType( const char* inValue, TDataType& ioType ) { const char* theValue( inValue ); return strto( ioType, theValue ); } } } #endif
8,818
C
30.723021
129
0.687571
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/serialization/Xml/SnXmlWriter.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SN_XML_WRITER_H #define SN_XML_WRITER_H #include "foundation/PxSimpleTypes.h" namespace physx { struct PxRepXObject; /** * Writer used by extensions to write elements to a file or database */ class PX_DEPRECATED XmlWriter { protected: virtual ~XmlWriter(){} public: /** Write a key-value pair into the current item */ virtual void write( const char* inName, const char* inData ) = 0; /** Write an object id into the current item */ virtual void write( const char* inName, const PxRepXObject& inLiveObject ) = 0; /** Add a child that then becomes the current context */ virtual void addAndGotoChild( const char* inName ) = 0; /** Leave the current child */ virtual void leaveChild() = 0; }; } #endif
2,441
C
41.103448
81
0.744777
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqCompoundPruningPool.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_COMPOUND_PRUNING_POOL_H #define SQ_COMPOUND_PRUNING_POOL_H #include "SqPruner.h" #include "foundation/PxArray.h" #include "GuPrunerMergeData.h" #include "GuIncrementalAABBTree.h" #include "GuAABBTreeBounds.h" namespace physx { namespace Gu { class PruningPool; } namespace Sq { /////////////////////////////////////////////////////////////////////////////////////////////// typedef PxArray<Gu::IncrementalAABBTreeNode*> UpdateMap; /////////////////////////////////////////////////////////////////////////////////////////////// class CompoundTree { public: void updateObjectAfterManualBoundsUpdates(Gu::PrunerHandle handle); void removeObject(Gu::PrunerHandle handle, Gu::PrunerPayloadRemovalCallback* removalCallback); bool addObject(Gu::PrunerHandle& result, const PxBounds3& bounds, const Gu::PrunerPayload& data, const PxTransform& transform); private: void updateMapping(const Gu::PoolIndex poolIndex, Gu::IncrementalAABBTreeNode* node, const Gu::NodeList& changedLeaves); public: Gu::IncrementalAABBTree* mTree; Gu::PruningPool* mPruningPool; UpdateMap* mUpdateMap; PxTransform mGlobalPose; PxCompoundPrunerQueryFlags mFlags; }; /////////////////////////////////////////////////////////////////////////////////////////////// class CompoundTreePool { public: CompoundTreePool(PxU64 contextID); ~CompoundTreePool(); void preallocate(PxU32 newCapacity); Gu::PoolIndex addCompound(Gu::PrunerHandle* results, const Gu::BVH& bvh, const PxBounds3& compoundBounds, const PxTransform& transform, bool isDynamic, const Gu::PrunerPayload* data, const PxTransform* transforms); Gu::PoolIndex removeCompound(Gu::PoolIndex index, Gu::PrunerPayloadRemovalCallback* removalCallback); void shiftOrigin(const PxVec3& shift); PX_FORCE_INLINE const Gu::AABBTreeBounds& getCurrentAABBTreeBounds() const { return mCompoundBounds; } PX_FORCE_INLINE const PxBounds3* getCurrentCompoundBounds() const { return mCompoundBounds.getBounds(); } PX_FORCE_INLINE PxBounds3* getCurrentCompoundBounds() { return mCompoundBounds.getBounds(); } PX_FORCE_INLINE const CompoundTree* getCompoundTrees() const { return mCompoundTrees; } PX_FORCE_INLINE CompoundTree* getCompoundTrees() { return mCompoundTrees; } PX_FORCE_INLINE PxU32 getNbObjects() const { return mNbObjects; } private: bool resize(PxU32 newCapacity); PxU32 mNbObjects; //!< Current number of objects PxU32 mMaxNbObjects; //!< Max. number of objects (capacity for mWorldBoxes, mObjects) //!< these arrays are parallel Gu::AABBTreeBounds mCompoundBounds; //!< List of compound world boxes, stores mNbObjects, capacity=mMaxNbObjects CompoundTree* mCompoundTrees; PxU64 mContextID; }; } } #endif
4,587
C
39.60177
223
0.696752
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqCompoundPruningPool.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/PxAllocator.h" #include "SqCompoundPruningPool.h" #include "GuPruningPool.h" #include "GuAABBTree.h" #include "GuBVH.h" using namespace physx; using namespace Cm; using namespace Gu; using namespace Sq; /////////////////////////////////////////////////////////////////////////////////////////////// void CompoundTree::updateObjectAfterManualBoundsUpdates(PrunerHandle handle) { const PxBounds3* newBounds = mPruningPool->getCurrentWorldBoxes(); const PoolIndex poolIndex = mPruningPool->getIndex(handle); NodeList changedLeaves; changedLeaves.reserve(8); IncrementalAABBTreeNode* node = mTree->update((*mUpdateMap)[poolIndex], poolIndex, newBounds, changedLeaves); // we removed node during update, need to update the mapping updateMapping(poolIndex, node, changedLeaves); } /////////////////////////////////////////////////////////////////////////////////////////////// void CompoundTree::removeObject(PrunerHandle handle, PrunerPayloadRemovalCallback* removalCallback) { const PoolIndex poolIndex = mPruningPool->getIndex(handle); // save the pool index for removed object const PoolIndex poolRelocatedLastIndex = mPruningPool->removeObject(handle, removalCallback); // save the lastIndex returned by removeObject IncrementalAABBTreeNode* node = mTree->remove((*mUpdateMap)[poolIndex], poolIndex, mPruningPool->getCurrentWorldBoxes()); // if node moved to its parent if (node && node->isLeaf()) { for (PxU32 j = 0; j < node->getNbPrimitives(); j++) { const PoolIndex index = node->getPrimitives(NULL)[j]; (*mUpdateMap)[index] = node; } } (*mUpdateMap)[poolIndex] = (*mUpdateMap)[poolRelocatedLastIndex]; // fix indices if we made a swap if(poolRelocatedLastIndex != poolIndex) mTree->fixupTreeIndices((*mUpdateMap)[poolIndex], poolRelocatedLastIndex, poolIndex); } /////////////////////////////////////////////////////////////////////////////////////////////// bool CompoundTree::addObject(PrunerHandle& result, const PxBounds3& bounds, const PrunerPayload& data, const PxTransform& transform) { mPruningPool->addObjects(&result, &bounds, &data, &transform, 1); if (mPruningPool->mMaxNbObjects > mUpdateMap->size()) mUpdateMap->resize(mPruningPool->mMaxNbObjects); const PoolIndex poolIndex = mPruningPool->getIndex(result); NodeList changedLeaves; changedLeaves.reserve(8); IncrementalAABBTreeNode* node = mTree->insert(poolIndex, mPruningPool->getCurrentWorldBoxes(), changedLeaves); updateMapping(poolIndex, node, changedLeaves); return true; } /////////////////////////////////////////////////////////////////////////////////////////////// void CompoundTree::updateMapping(const PoolIndex poolIndex, IncrementalAABBTreeNode* node, const NodeList& changedLeaves) { // if a node was split we need to update the node indices and also the sibling indices if(!changedLeaves.empty()) { if(node && node->isLeaf()) { for(PxU32 j = 0; j < node->getNbPrimitives(); j++) { const PoolIndex index = node->getPrimitives(NULL)[j]; (*mUpdateMap)[index] = node; } } for(PxU32 i = 0; i < changedLeaves.size(); i++) { IncrementalAABBTreeNode* changedNode = changedLeaves[i]; PX_ASSERT(changedNode->isLeaf()); for(PxU32 j = 0; j < changedNode->getNbPrimitives(); j++) { const PoolIndex index = changedNode->getPrimitives(NULL)[j]; (*mUpdateMap)[index] = changedNode; } } } else { (*mUpdateMap)[poolIndex] = node; } } /////////////////////////////////////////////////////////////////////////////////////////////// CompoundTreePool::CompoundTreePool(PxU64 contextID) : mNbObjects (0), mMaxNbObjects (0), mCompoundTrees (NULL), mContextID (contextID) { } /////////////////////////////////////////////////////////////////////////////////////////////// CompoundTreePool::~CompoundTreePool() { PX_FREE(mCompoundTrees); } /////////////////////////////////////////////////////////////////////////////////////////////// bool CompoundTreePool::resize(PxU32 newCapacity) { mCompoundBounds.resize(newCapacity, mNbObjects); CompoundTree* newTrees = PX_ALLOCATE(CompoundTree, newCapacity, "IncrementalTrees*"); if(!newTrees) return false; // memzero, we need to set the pointers in the compound tree to NULL PxMemZero(newTrees, sizeof(CompoundTree)*newCapacity); if(mCompoundTrees) PxMemCopy(newTrees, mCompoundTrees, mNbObjects*sizeof(CompoundTree)); mMaxNbObjects = newCapacity; PX_FREE(mCompoundTrees); mCompoundTrees = newTrees; return true; } /////////////////////////////////////////////////////////////////////////////////////////////// void CompoundTreePool::preallocate(PxU32 newCapacity) { if(newCapacity>mMaxNbObjects) resize(newCapacity); } /////////////////////////////////////////////////////////////////////////////////////////////// void CompoundTreePool::shiftOrigin(const PxVec3& shift) { PxBounds3* bounds = mCompoundBounds.getBounds(); for(PxU32 i=0; i < mNbObjects; i++) { bounds[i].minimum -= shift; bounds[i].maximum -= shift; mCompoundTrees[i].mGlobalPose.p -= shift; } } /////////////////////////////////////////////////////////////////////////////////////////////// PoolIndex CompoundTreePool::addCompound(PrunerHandle* results, const BVH& bvh, const PxBounds3& compoundBounds, const PxTransform& transform, bool isDynamic, const PrunerPayload* data, const PxTransform* transforms) { if(mNbObjects==mMaxNbObjects) // increase the capacity on overflow { if(!resize(PxMax<PxU32>(mMaxNbObjects*2, 32))) { // pool can return an invalid handle if memory alloc fails PxGetFoundation().error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "CompoundTreePool::addCompound memory allocation in resize failed."); return INVALID_PRUNERHANDLE; } } PX_ASSERT(mNbObjects!=mMaxNbObjects); const PoolIndex index = mNbObjects++; mCompoundBounds.getBounds()[index] = compoundBounds; const PxU32 nbObjects = bvh.getNbBounds(); CompoundTree& tree = mCompoundTrees[index]; PX_ASSERT(tree.mPruningPool == NULL); PX_ASSERT(tree.mTree == NULL); PX_ASSERT(tree.mUpdateMap == NULL); tree.mGlobalPose = transform; tree.mFlags = isDynamic ? PxCompoundPrunerQueryFlag::eDYNAMIC : PxCompoundPrunerQueryFlag::eSTATIC; // prepare the pruning pool PruningPool* pool = PX_NEW(PruningPool)(mContextID, TRANSFORM_CACHE_LOCAL); pool->preallocate(nbObjects); pool->addObjects(results, bvh.getBounds(), data, transforms, nbObjects); tree.mPruningPool = pool; // prepare update map UpdateMap* map = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(UpdateMap), "Update map"), UpdateMap); map->resizeUninitialized(nbObjects); tree.mUpdateMap = map; IncrementalAABBTree* iTree = PX_NEW(IncrementalAABBTree); iTree->copy(bvh, *map); tree.mTree = iTree; return index; } /////////////////////////////////////////////////////////////////////////////////////////////// PoolIndex CompoundTreePool::removeCompound(PoolIndex indexOfRemovedObject, PrunerPayloadRemovalCallback* removalCallback) { PX_ASSERT(mNbObjects); // release the tree PX_DELETE(mCompoundTrees[indexOfRemovedObject].mTree); mCompoundTrees[indexOfRemovedObject].mUpdateMap->clear(); mCompoundTrees[indexOfRemovedObject].mUpdateMap->~PxArray(); PX_FREE(mCompoundTrees[indexOfRemovedObject].mUpdateMap); if(removalCallback) { const PruningPool* pool = mCompoundTrees[indexOfRemovedObject].mPruningPool; removalCallback->invoke(pool->getNbActiveObjects(), pool->getObjects()); } PX_DELETE(mCompoundTrees[indexOfRemovedObject].mPruningPool); const PoolIndex indexOfLastObject = --mNbObjects; // swap the object at last index with index if(indexOfLastObject!=indexOfRemovedObject) { // PT: move last object's data to recycled spot (from removed object) // PT: the last object has moved so we need to handle the mappings for this object mCompoundBounds.getBounds() [indexOfRemovedObject] = mCompoundBounds.getBounds() [indexOfLastObject]; mCompoundTrees [indexOfRemovedObject] = mCompoundTrees [indexOfLastObject]; mCompoundTrees [indexOfLastObject].mPruningPool = NULL; mCompoundTrees [indexOfLastObject].mUpdateMap = NULL; mCompoundTrees [indexOfLastObject].mTree = NULL; } return indexOfLastObject; }
9,880
C++
35.327206
215
0.676923
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqFactory.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 "SqFactory.h" #include "SqCompoundPruner.h" using namespace physx; using namespace Sq; CompoundPruner* physx::Sq::createCompoundPruner(PxU64 contextID) { return PX_NEW(BVHCompoundPruner)(contextID); }
1,912
C++
46.824999
74
0.768305
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqQuery.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. // PT: SQ-API LEVEL 3 (Level 1 = SqPruner.h, Level 2 = SqManager/SqPrunerData) // PT: this file is part of a "high-level" set of files within Sq. The SqPruner API doesn't rely on them. // PT: this should really be at Np level but moving it to Sq allows us to share it. #include "SqQuery.h" using namespace physx; using namespace Sq; #include "common/PxProfileZone.h" #include "foundation/PxFPU.h" #include "GuBounds.h" #include "GuIntersectionRayBox.h" #include "GuIntersectionRay.h" #include "geometry/PxGeometryQuery.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxBoxGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "geometry/PxTriangleMeshGeometry.h" #include "PxQueryFiltering.h" using namespace physx; using namespace Sq; using namespace Gu; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE void copy(PxRaycastHit* PX_RESTRICT dest, const PxRaycastHit* PX_RESTRICT src) { dest->faceIndex = src->faceIndex; dest->flags = src->flags; dest->position = src->position; dest->normal = src->normal; dest->distance = src->distance; dest->u = src->u; dest->v = src->v; dest->actor = src->actor; dest->shape = src->shape; } static PX_FORCE_INLINE void copy(PxSweepHit* PX_RESTRICT dest, const PxSweepHit* PX_RESTRICT src) { dest->faceIndex = src->faceIndex; dest->flags = src->flags; dest->position = src->position; dest->normal = src->normal; dest->distance = src->distance; dest->actor = src->actor; dest->shape = src->shape; } static PX_FORCE_INLINE void copy(PxOverlapHit* PX_RESTRICT dest, const PxOverlapHit* PX_RESTRICT src) { dest->faceIndex = src->faceIndex; dest->actor = src->actor; dest->shape = src->shape; } // these partial template specializations are used to generalize the query code to be reused for all permutations of // hit type=(raycast, overlap, sweep) x query type=(ANY, SINGLE, MULTIPLE) template <typename HitType> struct HitTypeSupport { enum { IsRaycast = 0, IsSweep = 0, IsOverlap = 0 }; }; template <> struct HitTypeSupport<PxRaycastHit> { enum { IsRaycast = 1, IsSweep = 0, IsOverlap = 0 }; static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit& hit) { return static_cast<const PxRaycastHit&>(hit).distance; } }; template <> struct HitTypeSupport<PxSweepHit> { enum { IsRaycast = 0, IsSweep = 1, IsOverlap = 0 }; static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit& hit) { return static_cast<const PxSweepHit&>(hit).distance; } }; template <> struct HitTypeSupport<PxOverlapHit> { enum { IsRaycast = 0, IsSweep = 0, IsOverlap = 1 }; static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit&) { return -1.0f; } }; #define HITDIST(hit) HitTypeSupport<HitType>::getDistance(hit) template<typename HitType> static PxU32 clipHitsToNewMaxDist(HitType* ppuHits, PxU32 count, PxReal newMaxDist) { PxU32 i=0; while(i!=count) { if(HITDIST(ppuHits[i]) > newMaxDist) ppuHits[i] = ppuHits[--count]; else i++; } return count; } namespace physx { namespace Sq { struct MultiQueryInput { const PxVec3* rayOrigin; // only valid for raycasts const PxVec3* unitDir; // only valid for raycasts and sweeps PxReal maxDistance; // only valid for raycasts and sweeps const PxGeometry* geometry; // only valid for overlaps and sweeps const PxTransform* pose; // only valid for overlaps and sweeps PxReal inflation; // only valid for sweeps // Raycast constructor MultiQueryInput(const PxVec3& aRayOrigin, const PxVec3& aUnitDir, PxReal aMaxDist) { rayOrigin = &aRayOrigin; unitDir = &aUnitDir; maxDistance = aMaxDist; geometry = NULL; pose = NULL; inflation = 0.0f; } // Overlap constructor MultiQueryInput(const PxGeometry* aGeometry, const PxTransform* aPose) { geometry = aGeometry; pose = aPose; inflation = 0.0f; rayOrigin = unitDir = NULL; } // Sweep constructor MultiQueryInput( const PxGeometry* aGeometry, const PxTransform* aPose, const PxVec3& aUnitDir, const PxReal aMaxDist, const PxReal aInflation) { rayOrigin = NULL; maxDistance = aMaxDist; unitDir = &aUnitDir; geometry = aGeometry; pose = aPose; inflation = aInflation; } PX_FORCE_INLINE const PxVec3& getDir() const { PX_ASSERT(unitDir); return *unitDir; } PX_FORCE_INLINE const PxVec3& getOrigin() const { PX_ASSERT(rayOrigin); return *rayOrigin; } }; } } // performs a single geometry query for any HitType (PxSweepHit, PxOverlapHit, PxRaycastHit) template<typename HitType> struct GeomQueryAny { static PX_FORCE_INLINE PxU32 geomHit( const CachedFuncs& funcs, const MultiQueryInput& input, const Gu::ShapeData* sd, const PxGeometry& sceneGeom, const PxTransform& pose, PxHitFlags hitFlags, PxU32 maxHits, HitType* hits, const PxReal shrunkMaxDistance, const PxBounds3* precomputedBounds, PxQueryThreadContext* context) { using namespace Gu; const PxGeometry& geom0 = *input.geometry; const PxTransform& pose0 = *input.pose; const PxGeometry& geom1 = sceneGeom; const PxTransform& pose1 = pose; // Handle raycasts if(HitTypeSupport<HitType>::IsRaycast) { // the test for mesh AABB is archived in //sw/physx/dev/apokrovsky/graveyard/sqMeshAABBTest.cpp // TODO: investigate performance impact (see US12801) PX_CHECK_AND_RETURN_VAL(input.getDir().isFinite(), "PxScene::raycast(): rayDir is not valid.", 0); PX_CHECK_AND_RETURN_VAL(input.getOrigin().isFinite(), "PxScene::raycast(): rayOrigin is not valid.", 0); PX_CHECK_AND_RETURN_VAL(pose1.isValid(), "PxScene::raycast(): pose is not valid.", 0); PX_CHECK_AND_RETURN_VAL(shrunkMaxDistance >= 0.0f, "PxScene::raycast(): maxDist is negative.", 0); PX_CHECK_AND_RETURN_VAL(PxIsFinite(shrunkMaxDistance), "PxScene::raycast(): maxDist is not valid.", 0); PX_CHECK_AND_RETURN_VAL(PxAbs(input.getDir().magnitudeSquared()-1)<1e-4f, "PxScene::raycast(): ray direction must be unit vector.", 0); // PT: TODO: investigate perf difference const RaycastFunc func = funcs.mCachedRaycastFuncs[geom1.getType()]; return func(geom1, pose1, input.getOrigin(), input.getDir(), shrunkMaxDistance, hitFlags, maxHits, reinterpret_cast<PxGeomRaycastHit*>(hits), sizeof(PxRaycastHit), context); } // Handle sweeps else if(HitTypeSupport<HitType>::IsSweep) { PX_ASSERT(precomputedBounds != NULL); PX_ASSERT(sd != NULL); // b0 = query shape bounds // b1 = scene shape bounds // AP: Here we clip the sweep to bounds with sum of extents. This is needed for GJK stability. // because sweep is equivalent to a raycast vs a scene shape with inflated bounds. // This also may (or may not) provide an optimization for meshes because top level of rtree has multiple boxes // and there is no bounds test for the whole mesh elsewhere PxBounds3 b0 = *precomputedBounds, b1; // compute the scene geometry bounds // PT: TODO: avoid recomputing the bounds here Gu::computeBounds(b1, sceneGeom, pose, 0.0f, 1.0f); const PxVec3 combExt = (b0.getExtents() + b1.getExtents())*1.01f; PxF32 tnear, tfar; if(!intersectRayAABB2(-combExt, combExt, b0.getCenter() - b1.getCenter(), input.getDir(), shrunkMaxDistance, tnear, tfar)) // returns (tnear<tfar) if(tnear>tfar) // this second test is needed because shrunkMaxDistance can be 0 for 0 length sweep return 0; PX_ASSERT(input.getDir().isNormalized()); // tfar is now the t where the ray exits the AABB. input.getDir() is normalized const PxVec3& unitDir = input.getDir(); PxSweepHit& sweepHit = reinterpret_cast<PxSweepHit&>(hits[0]); // if we don't start inside the AABB box, offset the start pos, because of precision issues with large maxDist const bool offsetPos = (tnear > GU_RAY_SURFACE_OFFSET); const PxReal offset = offsetPos ? (tnear - GU_RAY_SURFACE_OFFSET) : 0.0f; const PxVec3 offsetVec(offsetPos ? (unitDir*offset) : PxVec3(0.0f)); // we move the geometry we sweep against, so that we avoid the Gu::Capsule/Box recomputation const PxTransform pose1Offset(pose1.p - offsetVec, pose1.q); const PxReal distance = PxMin(tfar, shrunkMaxDistance) - offset; const PxReal inflation = input.inflation; PX_CHECK_AND_RETURN_VAL(pose0.isValid(), "PxScene::sweep(): pose0 is not valid.", 0); PX_CHECK_AND_RETURN_VAL(pose1Offset.isValid(), "PxScene::sweep(): pose1 is not valid.", 0); PX_CHECK_AND_RETURN_VAL(unitDir.isFinite(), "PxScene::sweep(): unitDir is not valid.", 0); PX_CHECK_AND_RETURN_VAL(PxIsFinite(distance), "PxScene::sweep(): distance is not valid.", 0); PX_CHECK_AND_RETURN_VAL((distance >= 0.0f && !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP)) || distance > 0.0f, "PxScene::sweep(): sweep distance must be >=0 or >0 with eASSUME_NO_INITIAL_OVERLAP.", 0); PxU32 retVal = 0; const GeomSweepFuncs& sf = funcs.mCachedSweepFuncs; switch(geom0.getType()) { case PxGeometryType::eSPHERE: { const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom0); const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f); const Capsule worldCapsule(pose0.p, pose0.p, sphereGeom.radius); // AP: precompute? const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP; const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom1.getType()] : sf.capsuleMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, capsuleGeom, pose0, worldCapsule, unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; case PxGeometryType::eCAPSULE: { const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP; const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom1.getType()] : sf.capsuleMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, static_cast<const PxCapsuleGeometry&>(geom0), pose0, sd->getGuCapsule(), unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; case PxGeometryType::eBOX: { const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP; const SweepBoxFunc func = precise ? sf.preciseBoxMap[geom1.getType()] : sf.boxMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, static_cast<const PxBoxGeometry&>(geom0), pose0, sd->getGuBox(), unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; case PxGeometryType::eCONVEXMESH: { const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom0); const SweepConvexFunc func = sf.convexMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, convexGeom, pose0, unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; default: outputError<physx::PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::sweep(): first geometry object parameter must be sphere, capsule, box or convex geometry."); break; } if (retVal) { // we need to offset the distance back sweepHit.distance += offset; // we need to offset the hit position back as we moved the geometry we sweep against sweepHit.position += offsetVec; } return retVal; } // Handle overlaps else if(HitTypeSupport<HitType>::IsOverlap) { const GeomOverlapTable* overlapFuncs = funcs.mCachedOverlapFuncs; return PxU32(Gu::overlap(geom0, pose0, geom1, pose1, overlapFuncs, context)); } else { PX_ALWAYS_ASSERT_MESSAGE("Unexpected template expansion in GeomQueryAny::geomHit"); return 0; } } }; /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE bool applyFilterEquation(const QueryAdapter& adapter, const PrunerPayload& payload, const PxFilterData& queryFd) { // if the filterData field is non-zero, and the bitwise-AND value of filterData AND the shape's // queryFilterData is zero, the shape is skipped. if(queryFd.word0 | queryFd.word1 | queryFd.word2 | queryFd.word3) { // PT: TODO: revisit this, there's an obvious LHS here otherwise // We could maybe make this more flexible and let the user do the filtering // const PxFilterData& objFd = adapter.getFilterData(payload); PxFilterData objFd; adapter.getFilterData(payload, objFd); const PxU32 keep = (queryFd.word0 & objFd.word0) | (queryFd.word1 & objFd.word1) | (queryFd.word2 & objFd.word2) | (queryFd.word3 & objFd.word3); if(!keep) return false; } return true; } static PX_FORCE_INLINE bool applyAllPreFiltersSQ( const QueryAdapter& adapter, const PrunerPayload& payload, const PxActorShape& as, PxQueryHitType::Enum& shapeHitType, const PxQueryFlags& inFilterFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, PxHitFlags& queryFlags/*, PxU32 maxNbTouches*/) { if(!(filterData.flags & PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR) && !applyFilterEquation(adapter, payload, filterData.data)) return false; if((inFilterFlags & PxQueryFlag::ePREFILTER) && (filterCall)) { PxHitFlags outQueryFlags = queryFlags; if(filterCall) shapeHitType = filterCall->preFilter(filterData.data, as.shape, as.actor, outQueryFlags); // AP: at this point the callback might return eTOUCH but the touch buffer can be empty, the hit will be discarded //PX_CHECK_MSG(hitType == PxQueryHitType::eTOUCH ? maxNbTouches > 0 : true, // "SceneQuery: preFilter returned eTOUCH but empty touch buffer was provided, hit discarded."); queryFlags = (queryFlags & ~PxHitFlag::eMODIFIABLE_FLAGS) | (outQueryFlags & PxHitFlag::eMODIFIABLE_FLAGS); if(shapeHitType == PxQueryHitType::eNONE) return false; } // test passed, continue to return as; return true; } static PX_NOINLINE void computeCompoundShapeTransform(PxTransform* PX_RESTRICT transform, const PxTransform* PX_RESTRICT compoundPose, const PxTransform* PX_RESTRICT transforms, PxU32 primIndex) { // PT:: tag: scalar transform*transform *transform = (*compoundPose) * transforms[primIndex]; } // struct to access protected data members in the public PxHitCallback API template<typename HitType> struct MultiQueryCallback : public PrunerRaycastCallback, public PrunerOverlapCallback, public CompoundPrunerRaycastCallback, public CompoundPrunerOverlapCallback { const SceneQueries& mScene; const MultiQueryInput& mInput; PxHitCallback<HitType>& mHitCall; const PxHitFlags mHitFlags; const PxQueryFilterData& mFilterData; PxQueryFilterCallback* mFilterCall; PxReal mShrunkDistance; const PxHitFlags mMeshAnyHitFlags; bool mReportTouchesAgain; bool mFarBlockFound; // this is to prevent repeated searches for far block const bool mNoBlock; const bool mAnyHit; // The reason we need these bounds is because we need to know combined(inflated shape) bounds to clip the sweep path // to be tolerable by GJK precision issues. This test is done for (queryShape vs touchedShapes) // So it makes sense to cache the bounds for sweep query shape, otherwise we'd have to recompute them every time // Currently only used for sweeps. const PxBounds3* mQueryShapeBounds; const ShapeData* mShapeData; PxTransform mCompoundShapeTransform; MultiQueryCallback( const SceneQueries& scene, const MultiQueryInput& input, bool anyHit, PxHitCallback<HitType>& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, PxReal shrunkDistance) : mScene (scene), mInput (input), mHitCall (hitCall), mHitFlags (hitFlags), mFilterData (filterData), mFilterCall (filterCall), mShrunkDistance (shrunkDistance), mMeshAnyHitFlags ((hitFlags.isSet(PxHitFlag::eMESH_ANY) || anyHit) ? PxHitFlag::eMESH_ANY : PxHitFlag::Enum(0)), mReportTouchesAgain (true), mFarBlockFound (filterData.flags & PxQueryFlag::eNO_BLOCK), mNoBlock (filterData.flags & PxQueryFlag::eNO_BLOCK), mAnyHit (anyHit), mQueryShapeBounds (NULL), mShapeData (NULL) { } bool processTouchHit(const HitType& hit, PxReal& aDist) #if PX_WINDOWS_FAMILY PX_RESTRICT #endif { // -------------------------- handle eTOUCH hits --------------------------------- // for qType=multiple, store the hit. For other qTypes ignore it. // <= is important for initially overlapping sweeps #if PX_CHECKED if(mHitCall.maxNbTouches == 0 && !mFilterData.flags.isSet(PxQueryFlag::eRESERVED)) // issue a warning if eTOUCH was returned by the prefilter, we have 0 touch buffer and not a batch query // not doing for BQ because the touches buffer can be overflown and thats ok by spec // eRESERVED to avoid a warning from nested callback (closest blocking hit recursive search) outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "User filter returned PxQueryHitType::eTOUCH but the touches buffer was empty. Hit was discarded."); #endif if(mHitCall.maxNbTouches && mReportTouchesAgain && HITDIST(hit) <= mShrunkDistance) { // Buffer full: need to find the closest blocking hit, clip touch hits and flush the buffer if(mHitCall.nbTouches == mHitCall.maxNbTouches) { // issue a second nested query just looking for the closest blocking hit // could do better perf-wise by saving traversal state (start looking for blocking from this point) // but this is not a perf critical case because users can provide a bigger buffer // that covers non-degenerate cases // far block search doesn't apply to overlaps because overlaps don't work with blocking hits if(HitTypeSupport<HitType>::IsOverlap == 0) { // AP: the use of eRESERVED is a bit tricky, see other comments containing #LABEL1 PxQueryFilterData fd1 = mFilterData; fd1.flags |= PxQueryFlag::eRESERVED; PxHitBuffer<HitType> buf1; // create a temp callback buffer for a single blocking hit if(!mFarBlockFound && mHitCall.maxNbTouches > 0 && mScene.SceneQueries::multiQuery<HitType>(mInput, buf1, mHitFlags, NULL, fd1, mFilterCall)) { mHitCall.block = buf1.block; mHitCall.hasBlock = true; mHitCall.nbTouches = clipHitsToNewMaxDist<HitType>(mHitCall.touches, mHitCall.nbTouches, HITDIST(buf1.block)); mShrunkDistance = HITDIST(buf1.block); aDist = mShrunkDistance; } mFarBlockFound = true; } if(mHitCall.nbTouches == mHitCall.maxNbTouches) { mReportTouchesAgain = mHitCall.processTouches(mHitCall.touches, mHitCall.nbTouches); if(!mReportTouchesAgain) return false; // optimization - buffer is full else mHitCall.nbTouches = 0; // reset nbTouches so we can continue accumulating again } } //if(hitCall.nbTouches < hitCall.maxNbTouches) // can be true if maxNbTouches is 0 mHitCall.touches[mHitCall.nbTouches++] = hit; } // if(hitCall.maxNbTouches && reportTouchesAgain && HITDIST(hit) <= shrunkDistance) return true; } template<const bool isCached> // is this call coming as a callback from the pruner or a single item cached callback? bool _invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) #if PX_WINDOWS_FAMILY PX_RESTRICT #endif { PX_ASSERT(payloads); const PrunerPayload& payload = payloads[primIndex]; const QueryAdapter& adapter = static_cast<const QueryAdapter&>(mScene.mSQManager.getAdapter()); PxActorShape actorShape; adapter.getActorShape(payload, actorShape); const PxQueryFlags filterFlags = mFilterData.flags; // for no filter callback, default to eTOUCH for MULTIPLE, eBLOCK otherwise // also always treat as eBLOCK if currently tested shape is cached // Using eRESERVED flag as a special condition to default to eTOUCH hits while only looking for a single blocking hit // from a nested query (see other comments containing #LABEL1) PxQueryHitType::Enum shapeHitType = ((mHitCall.maxNbTouches || (mFilterData.flags & PxQueryFlag::eRESERVED)) && !isCached) ? PxQueryHitType::eTOUCH : PxQueryHitType::eBLOCK; // apply pre-filter PxHitFlags filteredHitFlags = mHitFlags; if(!isCached) // don't run filters on single item cache { if(!applyAllPreFiltersSQ(adapter, payload, actorShape, shapeHitType/*in&out*/, filterFlags, mFilterData, mFilterCall, filteredHitFlags/*, mHitCall.maxNbTouches*/)) return true; // skip this shape from reporting if prefilter said to do so // if(shapeHitType == PxQueryHitType::eNONE) // return true; } const PxGeometry& shapeGeom = adapter.getGeometry(payload); PX_ASSERT(transforms); const PxTransform* shapeTransform; if(!compoundPose) { shapeTransform = transforms + primIndex; } else { computeCompoundShapeTransform(&mCompoundShapeTransform, compoundPose, transforms, primIndex); shapeTransform = &mCompoundShapeTransform; } const PxU32 tempCount = 1; HitType tempBuf[tempCount]; // Here we decide whether to use the user provided buffer in place or a local stack buffer // see if we have more room left in the callback results buffer than in the parent stack buffer // if so get subHits in-place in the hit buffer instead of the parent stack buffer // nbTouches is the number of accumulated touch hits so far // maxNbTouches is the size of the user buffer PxU32 maxSubHits1; HitType* subHits1; if(mHitCall.nbTouches >= mHitCall.maxNbTouches) // if there's no room left in the user buffer, use a stack buffer { // tried using 64 here - causes check stack code to get generated on xbox, perhaps because of guard page // need this buffer in case the input buffer is full but we still want to correctly merge results from later hits maxSubHits1 = tempCount; subHits1 = reinterpret_cast<HitType*>(tempBuf); } else { maxSubHits1 = mHitCall.maxNbTouches - mHitCall.nbTouches; // how much room is left in the user buffer subHits1 = mHitCall.touches + mHitCall.nbTouches; // pointer to the first free hit in the user buffer } // call the geometry specific intersection template const PxU32 nbSubHits = GeomQueryAny<HitType>::geomHit( mScene.mCachedFuncs, mInput, mShapeData, shapeGeom, *shapeTransform, filteredHitFlags | mMeshAnyHitFlags, maxSubHits1, subHits1, mShrunkDistance, mQueryShapeBounds, &mHitCall); // ------------------------- iterate over geometry subhits ----------------------------------- for (PxU32 iSubHit = 0; iSubHit < nbSubHits; iSubHit++) { HitType& hit = subHits1[iSubHit]; hit.actor = actorShape.actor; hit.shape = actorShape.shape; // some additional processing only for sweep hits with initial overlap if(HitTypeSupport<HitType>::IsSweep && HITDIST(hit) == 0.0f && !(filteredHitFlags & PxHitFlag::eMTD)) // PT: necessary as some leaf routines are called with reversed params, thus writing +unitDir there. // AP: apparently still necessary to also do in Gu because Gu can be used standalone (without SQ) reinterpret_cast<PxSweepHit&>(hit).normal = -mInput.getDir(); // start out with hitType for this cached shape set to a pre-filtered hit type PxQueryHitType::Enum hitType = shapeHitType; // run the post-filter if specified in filterFlags and filterCall is non-NULL if(!isCached && mFilterCall && (filterFlags & PxQueryFlag::ePOSTFILTER)) { //if(mFilterCall) hitType = mFilterCall->postFilter(mFilterData.data, hit, hit.shape, hit.actor); } // early out on any hit if eANY_HIT was specified, regardless of hit type if(mAnyHit && hitType != PxQueryHitType::eNONE) { // block or touch qualifies for qType=ANY type hit => return it as blocking according to spec. Ignore eNONE. //mHitCall.block = hit; copy(&mHitCall.block, &hit); mHitCall.hasBlock = true; return false; // found a hit for ANY qType, can early exit now } if(mNoBlock && hitType==PxQueryHitType::eBLOCK) hitType = PxQueryHitType::eTOUCH; PX_WARN_ONCE_IF(HitTypeSupport<HitType>::IsOverlap && hitType == PxQueryHitType::eBLOCK, "eBLOCK returned from user filter for overlap() query. This may cause undesired behavior. " "Consider using PxQueryFlag::eNO_BLOCK for overlap queries."); if(hitType == PxQueryHitType::eTOUCH) { if(!processTouchHit(hit, aDist)) return false; } // if(hitType == PxQueryHitType::eTOUCH) else if(hitType == PxQueryHitType::eBLOCK) { // -------------------------- handle eBLOCK hits ---------------------------------- // only eBLOCK qualifies as a closest hit candidate => compare against best distance and store // <= is needed for eTOUCH hits to be recorded correctly vs same eBLOCK distance for overlaps if(HITDIST(hit) <= mShrunkDistance) { if(HitTypeSupport<HitType>::IsOverlap == 0) { mShrunkDistance = HITDIST(hit); aDist = mShrunkDistance; } //mHitCall.block = hit; copy(&mHitCall.block, &hit); mHitCall.hasBlock = true; } } // if(hitType == eBLOCK) else { PX_ASSERT(hitType == PxQueryHitType::eNONE); } } // for iSubHit return true; } virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) { return _invoke<false>(aDist, primIndex, payloads, transforms, NULL); } virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) { float unused = 0.0f; return _invoke<false>(unused, primIndex, payloads, transforms, NULL); } virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) { return _invoke<false>(aDist, primIndex, payloads, transforms, compoundPose); } virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) { float unused = 0.0f; return _invoke<false>(unused, primIndex, payloads, transforms, compoundPose); } private: MultiQueryCallback<HitType>& operator=(const MultiQueryCallback<HitType>&); }; //======================================================================================================================== #if PX_SUPPORT_PVD template<typename HitType> struct CapturePvdOnReturn : public PxHitCallback<HitType> { // copy the arguments of multiQuery into a struct, this is strictly for PVD recording const SceneQueries* mSQ; const MultiQueryInput& mInput; const PxQueryFilterData& mFilterData; PxArray<HitType> mAllHits; PxHitCallback<HitType>& mParentCallback; CapturePvdOnReturn( const SceneQueries* sq, const MultiQueryInput& input, const PxQueryFilterData& filterData, PxHitCallback<HitType>& parentCallback) : PxHitCallback<HitType> (parentCallback.touches, parentCallback.maxNbTouches), mSQ (sq), mInput (input), mFilterData (filterData), mParentCallback (parentCallback) {} virtual PxAgain processTouches(const HitType* hits, PxU32 nbHits) { const PxAgain again = mParentCallback.processTouches(hits, nbHits); for(PxU32 i=0; i<nbHits; i++) mAllHits.pushBack(hits[i]); return again; } ~CapturePvdOnReturn() { PVDCapture* pvd = mSQ->mPVD; if(!pvd || !pvd->transmitSceneQueries()) return; if(mParentCallback.nbTouches) { for(PxU32 i = 0; i < mParentCallback.nbTouches; i++) mAllHits.pushBack(mParentCallback.touches[i]); } if(mParentCallback.hasBlock) mAllHits.pushBack(mParentCallback.block); // PT: TODO: why do we need reinterpret_casts below? if(HitTypeSupport<HitType>::IsRaycast) pvd->raycast(mInput.getOrigin(), mInput.getDir(), mInput.maxDistance, reinterpret_cast<PxRaycastHit*>(mAllHits.begin()), mAllHits.size(), mFilterData, this->maxNbTouches!=0); else if(HitTypeSupport<HitType>::IsOverlap) pvd->overlap(*mInput.geometry, *mInput.pose, reinterpret_cast<PxOverlapHit*>(mAllHits.begin()), mAllHits.size(), mFilterData); else if(HitTypeSupport<HitType>::IsSweep) pvd->sweep (*mInput.geometry, *mInput.pose, mInput.getDir(), mInput.maxDistance, reinterpret_cast<PxSweepHit*>(mAllHits.begin()), mAllHits.size(), mFilterData, this->maxNbTouches!=0); } private: CapturePvdOnReturn<HitType>& operator=(const CapturePvdOnReturn<HitType>&); }; #endif // PX_SUPPORT_PVD //======================================================================================================================== template<typename HitType> struct IssueCallbacksOnReturn { PxHitCallback<HitType>& hits; bool again; // query was stopped by previous processTouches. This means that nbTouches is still non-zero // but we don't need to issue processTouches again PX_FORCE_INLINE IssueCallbacksOnReturn(PxHitCallback<HitType>& aHits) : hits(aHits) { again = true; } ~IssueCallbacksOnReturn() { if(again) // only issue processTouches if query wasn't stopped // this is because nbTouches doesn't get reset to 0 in this case (according to spec) // and the touches in touches array were already processed by the callback { if(hits.hasBlock && hits.nbTouches) hits.nbTouches = clipHitsToNewMaxDist<HitType>(hits.touches, hits.nbTouches, HITDIST(hits.block)); if(hits.nbTouches) { bool again_ = hits.processTouches(hits.touches, hits.nbTouches); if(again_) hits.nbTouches = 0; } } hits.finalizeQuery(); } private: IssueCallbacksOnReturn<HitType>& operator=(const IssueCallbacksOnReturn<HitType>&); }; #undef HITDIST //======================================================================================================================== template<typename HitType> static bool doQueryVsCached(const PrunerHandle cacheData, PxU32 prunerIndex, const PrunerCompoundId cachedCompoundId, const PrunerManager& manager, MultiQueryCallback<HitType>& pcb, const MultiQueryInput& input); static PX_FORCE_INLINE PxCompoundPrunerQueryFlags convertFlags(PxQueryFlags inFlags) { PxCompoundPrunerQueryFlags outFlags(0); if(inFlags.isSet(PxQueryFlag::eSTATIC)) outFlags.raise(PxCompoundPrunerQueryFlag::eSTATIC); if(inFlags.isSet(PxQueryFlag::eDYNAMIC)) outFlags.raise(PxCompoundPrunerQueryFlag::eDYNAMIC); return outFlags; } // PT: TODO: revisit error messages without breaking UTs template<typename HitType> bool SceneQueries::multiQuery( const MultiQueryInput& input, PxHitCallback<HitType>& hits, PxHitFlags hitFlags, const PxQueryCache* cache, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const { const bool anyHit = (filterData.flags & PxQueryFlag::eANY_HIT) == PxQueryFlag::eANY_HIT; if(HitTypeSupport<HitType>::IsRaycast == 0) { PX_CHECK_AND_RETURN_VAL(input.pose != NULL, "NpSceneQueries::overlap/sweep pose is NULL.", 0); PX_CHECK_AND_RETURN_VAL(input.pose->isValid(), "NpSceneQueries::overlap/sweep pose is not valid.", 0); } else { PX_CHECK_AND_RETURN_VAL(input.getOrigin().isFinite(), "NpSceneQueries::raycast pose is not valid.", 0); } if(HitTypeSupport<HitType>::IsOverlap == 0) { PX_CHECK_AND_RETURN_VAL(input.getDir().isFinite(), "NpSceneQueries multiQuery input check: unitDir is not valid.", 0); PX_CHECK_AND_RETURN_VAL(input.getDir().isNormalized(), "NpSceneQueries multiQuery input check: direction must be normalized", 0); } if(HitTypeSupport<HitType>::IsRaycast) { PX_CHECK_AND_RETURN_VAL(input.maxDistance > 0.0f, "NpSceneQueries::multiQuery input check: distance cannot be negative or zero", 0); } if(HitTypeSupport<HitType>::IsOverlap && !anyHit) { PX_CHECK_AND_RETURN_VAL(hits.maxNbTouches > 0, "PxScene::overlap() calls without eANY_HIT flag require a touch hit buffer for return results.", 0); } if(HitTypeSupport<HitType>::IsSweep) { PX_CHECK_AND_RETURN_VAL(input.maxDistance >= 0.0f, "NpSceneQueries multiQuery input check: distance cannot be negative", 0); PX_CHECK_AND_RETURN_VAL(input.maxDistance != 0.0f || !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP), "NpSceneQueries multiQuery input check: zero-length sweep only valid without the PxHitFlag::eASSUME_NO_INITIAL_OVERLAP flag", 0); } PX_CHECK_MSG(!cache || (cache && cache->shape && cache->actor), "Raycast cache specified but shape or actor pointer is NULL!"); PrunerCompoundId cachedCompoundId = INVALID_COMPOUND_ID; // PT: this is similar to the code in the SqRefFinder so we could share that code maybe. But here we later retrieve the payload from the PrunerData, // i.e. we basically go back to the same pointers we started from. I suppose it's to make sure they get properly invalidated when an object is deleted etc, // but we could still probably find a more efficient way to do that here. Isn't it exactly why we had the Signature class initially? // // how can this work anyway? if the actor has been deleted the lookup won't work either => doc says it's up to users to manage that.... PxU32 prunerIndex = 0xffffffff; const PrunerHandle cacheData = cache ? static_cast<const QueryAdapter&>(mSQManager.getAdapter()).findPrunerHandle(*cache, cachedCompoundId, prunerIndex) : INVALID_PRUNERHANDLE; // this function is logically const for the SDK user, as flushUpdates() will not have an API-visible effect on this object // internally however, flushUpdates() changes the states of the Pruners in mSQManager // because here is the only place we need this, const_cast instead of making SQM mutable const_cast<SceneQueries*>(this)->mSQManager.flushUpdates(); #if PX_SUPPORT_PVD CapturePvdOnReturn<HitType> pvdCapture(this, input, filterData, hits); #endif IssueCallbacksOnReturn<HitType> cbr(hits); // destructor will execute callbacks on return from this function hits.hasBlock = false; hits.nbTouches = 0; PxReal shrunkDistance = HitTypeSupport<HitType>::IsOverlap ? PX_MAX_REAL : input.maxDistance; // can be progressively shrunk as we go over the list of shapes if(HitTypeSupport<HitType>::IsSweep) shrunkDistance = PxMin(shrunkDistance, PX_MAX_SWEEP_DISTANCE); MultiQueryCallback<HitType> pcb(*this, input, anyHit, hits, hitFlags, filterData, filterCall, shrunkDistance); if(cacheData!=INVALID_PRUNERHANDLE && hits.maxNbTouches == 0) // don't use cache for queries that can return touch hits { if(!doQueryVsCached(cacheData, prunerIndex, cachedCompoundId, mSQManager, pcb, input)) return hits.hasAnyHits(); } const Pruner* staticPruner = mSQManager.getPruner(PruningIndex::eSTATIC); const Pruner* dynamicPruner = mSQManager.getPruner(PruningIndex::eDYNAMIC); const CompoundPruner* compoundPruner = mSQManager.getCompoundPruner(); const PxU32 doStatics = staticPruner && (filterData.flags & PxQueryFlag::eSTATIC); const PxU32 doDynamics = dynamicPruner && (filterData.flags & PxQueryFlag::eDYNAMIC); const PxCompoundPrunerQueryFlags compoundPrunerQueryFlags = convertFlags(filterData.flags); if(HitTypeSupport<HitType>::IsRaycast) { bool again = doStatics ? staticPruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb) : true; if(!again) return hits.hasAnyHits(); if(doDynamics) again = dynamicPruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb); if(again && compoundPruner) again = compoundPruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb, compoundPrunerQueryFlags); cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } else if(HitTypeSupport<HitType>::IsOverlap) { PX_ASSERT(input.geometry); const ShapeData sd(*input.geometry, *input.pose, input.inflation); pcb.mShapeData = &sd; bool again = doStatics ? staticPruner->overlap(sd, pcb) : true; if(!again) // && (filterData.flags & PxQueryFlag::eANY_HIT)) return hits.hasAnyHits(); if(doDynamics) again = dynamicPruner->overlap(sd, pcb); if(again && compoundPruner) again = compoundPruner->overlap(sd, pcb, compoundPrunerQueryFlags); cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } else { PX_ASSERT(HitTypeSupport<HitType>::IsSweep); PX_ASSERT(input.geometry); const ShapeData sd(*input.geometry, *input.pose, input.inflation); pcb.mQueryShapeBounds = &sd.getPrunerInflatedWorldAABB(); pcb.mShapeData = &sd; bool again = doStatics ? staticPruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb) : true; if(!again) return hits.hasAnyHits(); if(doDynamics) again = dynamicPruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb); if(again && compoundPruner) again = compoundPruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb, compoundPrunerQueryFlags); cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } //explicit template instantiation template bool SceneQueries::multiQuery<PxRaycastHit>(const MultiQueryInput&, PxHitCallback<PxRaycastHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; template bool SceneQueries::multiQuery<PxOverlapHit>(const MultiQueryInput&, PxHitCallback<PxOverlapHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; template bool SceneQueries::multiQuery<PxSweepHit>(const MultiQueryInput&, PxHitCallback<PxSweepHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; /////////////////////////////////////////////////////////////////////////////// bool SceneQueries::_raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxHitCallback<PxRaycastHit>& hits, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { PX_PROFILE_ZONE("SceneQuery.raycast", getContextId()); PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD) MultiQueryInput input(origin, unitDir, distance); return multiQuery<PxRaycastHit>(input, hits, hitFlags, cache, filterData, filterCall); } ////////////////////////////////////////////////////////////////////////// bool SceneQueries::_overlap( const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { PX_PROFILE_ZONE("SceneQuery.overlap", getContextId()); PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD) #if PX_CHECKED if (!PxGeometryQuery::isValid(geometry)) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Provided geometry is not valid"); #endif MultiQueryInput input(&geometry, &pose); return multiQuery<PxOverlapHit>(input, hits, PxHitFlags(), cache, filterData, filterCall); } /////////////////////////////////////////////////////////////////////////////// bool SceneQueries::_sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxHitCallback<PxSweepHit>& hits, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const { PX_PROFILE_ZONE("SceneQuery.sweep", getContextId()); PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD) #if PX_CHECKED if(!PxGeometryQuery::isValid(geometry)) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Provided geometry is not valid"); #endif if((hitFlags & PxHitFlag::ePRECISE_SWEEP) && (hitFlags & PxHitFlag::eMTD)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " Precise sweep doesn't support MTD. Perform MTD with default sweep"); hitFlags &= ~PxHitFlag::ePRECISE_SWEEP; } if((hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP) && (hitFlags & PxHitFlag::eMTD)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " eMTD cannot be used in conjunction with eASSUME_NO_INITIAL_OVERLAP. eASSUME_NO_INITIAL_OVERLAP will be ignored"); hitFlags &= ~PxHitFlag::eASSUME_NO_INITIAL_OVERLAP; } PxReal realInflation = inflation; if((hitFlags & PxHitFlag::ePRECISE_SWEEP)&& inflation > 0.f) { realInflation = 0.f; outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " Precise sweep doesn't support inflation, inflation will be overwritten to be zero"); } MultiQueryInput input(&geometry, &pose, unitDir, distance, realInflation); return multiQuery<PxSweepHit>(input, hits, hitFlags, cache, filterData, filterCall); } /////////////////////////////////////////////////////////////////////////////// template<typename HitType> static bool doQueryVsCached(const PrunerHandle handle, PxU32 prunerIndex, const PrunerCompoundId cachedCompoundId, const PrunerManager& manager, MultiQueryCallback<HitType>& pcb, const MultiQueryInput& input) { // this block is only executed for single shape cache const PrunerPayload* payloads; const PxTransform* compoundPosePtr; PxTransform* transform; PxTransform compoundPose; if(cachedCompoundId == INVALID_COMPOUND_ID) { const Pruner* pruner = manager.getPruner(PruningIndex::Enum(prunerIndex)); PX_ASSERT(pruner); PrunerPayloadData ppd; const PrunerPayload& cachedPayload = pruner->getPayloadData(handle, &ppd); payloads = &cachedPayload; compoundPosePtr = NULL; transform = ppd.mTransform; } else { const CompoundPruner* pruner = manager.getCompoundPruner(); PX_ASSERT(pruner); PrunerPayloadData ppd; const PrunerPayload& cachedPayload = pruner->getPayloadData(handle, cachedCompoundId, &ppd); compoundPose = pruner->getTransform(cachedCompoundId); payloads = &cachedPayload; compoundPosePtr = &compoundPose; transform = ppd.mTransform; } PxReal dummyDist; bool againAfterCache; if(HitTypeSupport<HitType>::IsSweep) { // AP: for sweeps we cache the bounds because we need to know them for the test to clip the sweep to bounds // otherwise GJK becomes unstable. The bounds can be used multiple times so this is an optimization. const ShapeData sd(*input.geometry, *input.pose, input.inflation); pcb.mQueryShapeBounds = &sd.getPrunerInflatedWorldAABB(); pcb.mShapeData = &sd; // againAfterCache = pcb.invoke(dummyDist, 0); againAfterCache = pcb.template _invoke<true>(dummyDist, 0, payloads, transform, compoundPosePtr); pcb.mQueryShapeBounds = NULL; pcb.mShapeData = NULL; } else // againAfterCache = pcb.invoke(dummyDist, 0); againAfterCache = pcb.template _invoke<true>(dummyDist, 0, payloads, transform, compoundPosePtr); return againAfterCache; } /////////////////////////////////////////////////////////////////////////////// SceneQueries::SceneQueries( PVDCapture* pvd, PxU64 contextID, Pruner* staticPruner, Pruner* dynamicPruner, PxU32 dynamicTreeRebuildRateHint, float inflation, const PxSceneLimits& limits, const QueryAdapter& adapter) : mSQManager (contextID, staticPruner, dynamicPruner, dynamicTreeRebuildRateHint, inflation, limits, adapter), mPVD (pvd) { } SceneQueries::~SceneQueries() { }
44,533
C++
41.092628
212
0.720477
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqManager.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. // PT: SQ-API LEVEL 2 (Level 1 = SqPruner.h) // PT: this file is part of a "high-level" set of files within Sq. The SqPruner API doesn't rely on them. // PT: this should really be at Np level but moving it to Sq allows us to share it. #include "SqManager.h" #include "GuSqInternal.h" #include "GuBounds.h" using namespace physx; using namespace Sq; using namespace Gu; PrunerExt::PrunerExt() : mPruner(NULL), mDirtyList("SQmDirtyList"), mDirtyStatic(false) { } PrunerExt::~PrunerExt() { PX_DELETE(mPruner); } void PrunerExt::init(Pruner* pruner) { mPruner = pruner; } void PrunerExt::preallocate(PxU32 nbShapes) { // if(nbShapes > mDirtyMap.size()) // mDirtyMap.resize(nbShapes); if(mPruner) mPruner->preallocate(nbShapes); } void PrunerExt::flushMemory() { if(!mDirtyList.size()) mDirtyList.reset(); // PT: TODO: flush bitmap here // PT: TODO: flush pruner here? } void PrunerExt::addToDirtyList(PrunerHandle handle, bool dynamic, const PxTransform& transform) { if(mPruner) mPruner->setTransform(handle, transform); PxBitMap& dirtyMap = mDirtyMap; { if(dirtyMap.size() <= handle) { PxU32 size = PxMax<PxU32>(dirtyMap.size()*2, 1024); const PxU32 minSize = handle+1; if(minSize>size) size = minSize*2; dirtyMap.resize(size); PX_ASSERT(handle<dirtyMap.size()); PX_ASSERT(!dirtyMap.test(handle)); } } if(!dirtyMap.test(handle)) { dirtyMap.set(handle); mDirtyList.pushBack(handle); } if(!dynamic) mDirtyStatic = true; } void PrunerExt::removeFromDirtyList(PrunerHandle handle) { PxBitMap& dirtyMap = mDirtyMap; // if(dirtyMap.test(handle)) if(dirtyMap.boundedTest(handle)) { dirtyMap.reset(handle); mDirtyList.findAndReplaceWithLast(handle); } // PT: if we remove the object that made us set mDirtyStatic to true, tough luck, // we don't bother fixing that bool here. It's going to potentially cause an // unnecessary update of the character controller's caches, which is not a big deal. } bool PrunerExt::processDirtyList(PxU32 index, const Adapter& adapter, float inflation) { const PxU32 numDirtyList = mDirtyList.size(); if(!numDirtyList) return false; const PrunerHandle* const prunerHandles = mDirtyList.begin(); for(PxU32 i=0; i<numDirtyList; i++) { const PrunerHandle handle = prunerHandles[i]; mDirtyMap.reset(handle); // PT: we compute the new bounds and store them directly in the pruner structure to avoid copies. We delay the updateObjects() call // to take advantage of batching. PX_UNUSED(index); PrunerPayloadData ppd; const PrunerPayload& pp = mPruner->getPayloadData(handle, &ppd); computeBounds(*ppd.mBounds, adapter.getGeometry(pp), *ppd.mTransform, 0.0f, inflation); } // PT: batch update happens after the loop instead of once per loop iteration mPruner->updateObjects(prunerHandles, numDirtyList); mDirtyList.clear(); const bool ret = mDirtyStatic; mDirtyStatic = false; return ret; } // PT: TODO: re-inline this /*void PrunerExt::growDirtyList(PrunerHandle handle) { // pruners must either provide indices in order or reuse existing indices, so this 'if' is enough to ensure we have space for the new handle // PT: TODO: fix this. There is just no need for any of it. The pruning pool itself could support the feature for free, similar to what we do // in MBP. There would be no need for the bitmap or the dirty list array. However doing this through the virtual interface would be clumsy, // adding the cost of virtual calls for very cheap & simple operations. It would be a lot easier to drop it and go back to what we had before. PxBitMap& dirtyMap = mDirtyMap; if(dirtyMap.size() <= handle) dirtyMap.resize(PxMax<PxU32>(dirtyMap.size() * 2, 1024)); PX_ASSERT(handle<dirtyMap.size()); dirtyMap.reset(handle); }*/ /////////////////////////////////////////////////////////////////////////////// CompoundPrunerExt::CompoundPrunerExt() : mPruner (NULL) { } CompoundPrunerExt::~CompoundPrunerExt() { PX_DELETE(mPruner); } void CompoundPrunerExt::preallocate(PxU32 nbShapes) { // if(nbShapes > mDirtyList.size()) // mDirtyList.reserve(nbShapes); if(mPruner) mPruner->preallocate(nbShapes); } void CompoundPrunerExt::flushMemory() { if(!mDirtyList.size()) mDirtyList.clear(); } void CompoundPrunerExt::flushShapes(const Adapter& adapter, float inflation) { const PxU32 numDirtyList = mDirtyList.size(); if(!numDirtyList) return; const CompoundPair* const compoundPairs = mDirtyList.getEntries(); for(PxU32 i=0; i<numDirtyList; i++) { const PrunerHandle handle = compoundPairs[i].second; const PrunerCompoundId compoundId = compoundPairs[i].first; // PT: we compute the new bounds and store them directly in the pruner structure to avoid copies. We delay the updateObjects() call // to take advantage of batching. PrunerPayloadData ppd; const PrunerPayload& pp = mPruner->getPayloadData(handle, compoundId, &ppd); computeBounds(*ppd.mBounds, adapter.getGeometry(pp), *ppd.mTransform, 0.0f, inflation); // A.B. not very effective, we might do better here mPruner->updateObjectAfterManualBoundsUpdates(compoundId, handle); } mDirtyList.clear(); } void CompoundPrunerExt::addToDirtyList(PrunerCompoundId compoundId, PrunerHandle handle, const PxTransform& transform) { if(mPruner) mPruner->setTransform(handle, compoundId, transform); mDirtyList.insert(CompoundPair(compoundId, handle)); } void CompoundPrunerExt::removeFromDirtyList(PrunerCompoundId compoundId, PrunerHandle handle) { mDirtyList.erase(CompoundPair(compoundId, handle)); } /////////////////////////////////////////////////////////////////////////////// #include "SqFactory.h" #include "common/PxProfileZone.h" #include "common/PxRenderBuffer.h" #include "GuBVH.h" #include "foundation/PxAlloca.h" #include "PxSceneDesc.h" // PT: for PxSceneLimits TODO: remove namespace { enum PxScenePrunerIndex { PX_SCENE_PRUNER_STATIC = 0, PX_SCENE_PRUNER_DYNAMIC = 1, PX_SCENE_COMPOUND_PRUNER = 0xffffffff, }; } PrunerManager::PrunerManager( PxU64 contextID, Pruner* staticPruner, Pruner* dynamicPruner, PxU32 dynamicTreeRebuildRateHint, float inflation, const PxSceneLimits& limits, const Adapter& adapter) : mAdapter (adapter), mContextID (contextID), mStaticTimestamp (0), mInflation (inflation) { mPrunerExt[PruningIndex::eSTATIC].init(staticPruner); mPrunerExt[PruningIndex::eDYNAMIC].init(dynamicPruner); setDynamicTreeRebuildRateHint(dynamicTreeRebuildRateHint); mCompoundPrunerExt.mPruner = createCompoundPruner(contextID); preallocate(PruningIndex::eSTATIC, limits.maxNbStaticShapes); preallocate(PruningIndex::eDYNAMIC, limits.maxNbDynamicShapes); preallocate(PxU32(PX_SCENE_COMPOUND_PRUNER), 32); mPrunerNeedsUpdating = false; } PrunerManager::~PrunerManager() { } void PrunerManager::preallocate(PxU32 prunerIndex, PxU32 nbShapes) { if(prunerIndex==PruningIndex::eSTATIC) mPrunerExt[PruningIndex::eSTATIC].preallocate(nbShapes); else if(prunerIndex==PruningIndex::eDYNAMIC) mPrunerExt[PruningIndex::eDYNAMIC].preallocate(nbShapes); else if(prunerIndex==PX_SCENE_COMPOUND_PRUNER) mCompoundPrunerExt.preallocate(nbShapes); } void PrunerManager::flushMemory() { for(PxU32 i=0;i<PruningIndex::eCOUNT;i++) mPrunerExt[i].flushMemory(); mCompoundPrunerExt.flushMemory(); } PrunerData PrunerManager::addPrunerShape(const PrunerPayload& payload, bool dynamic, PrunerCompoundId compoundId, const PxBounds3& bounds, const PxTransform& transform, bool hasPruningStructure) { mPrunerNeedsUpdating = true; const PxU32 index = PxU32(dynamic); if(!index) invalidateStaticTimestamp(); PrunerHandle handle; if(compoundId == INVALID_COMPOUND_ID) { PX_ASSERT(mPrunerExt[index].pruner()); mPrunerExt[index].pruner()->addObjects(&handle, &bounds, &payload, &transform, 1, hasPruningStructure); //mPrunerExt[index].growDirtyList(handle); } else { PX_ASSERT(mCompoundPrunerExt.pruner()); mCompoundPrunerExt.pruner()->addObject(compoundId, handle, bounds, payload, transform); } return createPrunerData(index, handle); } void PrunerManager::removePrunerShape(PrunerCompoundId compoundId, PrunerData data, PrunerPayloadRemovalCallback* removalCallback) { mPrunerNeedsUpdating = true; const PxU32 index = getPrunerIndex(data); const PrunerHandle handle = getPrunerHandle(data); if(!index) invalidateStaticTimestamp(); if(compoundId == INVALID_COMPOUND_ID) { PX_ASSERT(mPrunerExt[index].pruner()); mPrunerExt[index].removeFromDirtyList(handle); mPrunerExt[index].pruner()->removeObjects(&handle, 1, removalCallback); } else { mCompoundPrunerExt.removeFromDirtyList(compoundId, handle); mCompoundPrunerExt.pruner()->removeObject(compoundId, handle, removalCallback); } } void PrunerManager::markForUpdate(PrunerCompoundId compoundId, PrunerData data, const PxTransform& transform) { mPrunerNeedsUpdating = true; const PxU32 index = getPrunerIndex(data); const PrunerHandle handle = getPrunerHandle(data); if(!index) invalidateStaticTimestamp(); if(compoundId == INVALID_COMPOUND_ID) // PT: TODO: at this point do we still need a dirty list? we could just update the bounds directly? mPrunerExt[index].addToDirtyList(handle, index!=0, transform); else mCompoundPrunerExt.addToDirtyList(compoundId, handle, transform); } void PrunerManager::setDynamicTreeRebuildRateHint(PxU32 rebuildRateHint) { mRebuildRateHint = rebuildRateHint; for(PxU32 i=0;i<PruningIndex::eCOUNT;i++) { Pruner* pruner = mPrunerExt[i].pruner(); if(pruner && pruner->isDynamic()) static_cast<DynamicPruner*>(pruner)->setRebuildRateHint(rebuildRateHint); } } void PrunerManager::afterSync(bool buildStep, bool commit) { PX_PROFILE_ZONE("Sim.sceneQueryBuildStep", mContextID); if(!buildStep && !commit) { mPrunerNeedsUpdating = true; return; } // flush user modified objects flushShapes(); for(PxU32 i=0; i<PruningIndex::eCOUNT; i++) { Pruner* pruner = mPrunerExt[i].pruner(); if(pruner) { if(pruner->isDynamic()) static_cast<DynamicPruner*>(pruner)->buildStep(true); if(commit) pruner->commit(); } } mPrunerNeedsUpdating = !commit; } void PrunerManager::flushShapes() { PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID); // must already have acquired writer lock here const float inflation = 1.0f + mInflation; bool mustInvalidateStaticTimestamp = false; for(PxU32 i=0; i<PruningIndex::eCOUNT; i++) { if(mPrunerExt[i].processDirtyList(i, mAdapter, inflation)) mustInvalidateStaticTimestamp = true; } if(mustInvalidateStaticTimestamp) invalidateStaticTimestamp(); mCompoundPrunerExt.flushShapes(mAdapter, inflation); } void PrunerManager::flushUpdates() { PX_PROFILE_ZONE("SceneQuery.flushUpdates", mContextID); if(mPrunerNeedsUpdating) { // no need to take lock if manual sq update is enabled // as flushUpdates will only be called from NpScene::flushQueryUpdates() mSQLock.lock(); if(mPrunerNeedsUpdating) { flushShapes(); for(PxU32 i=0; i<PruningIndex::eCOUNT; i++) if(mPrunerExt[i].pruner()) mPrunerExt[i].pruner()->commit(); PxMemoryBarrier(); mPrunerNeedsUpdating = false; } mSQLock.unlock(); } } void PrunerManager::forceRebuildDynamicTree(PxU32 prunerIndex) { PX_PROFILE_ZONE("SceneQuery.forceDynamicTreeRebuild", mContextID); PxMutex::ScopedLock lock(mSQLock); Pruner* pruner = mPrunerExt[prunerIndex].pruner(); if(pruner && pruner->isDynamic()) { static_cast<DynamicPruner*>(pruner)->purge(); static_cast<DynamicPruner*>(pruner)->commit(); } } void* PrunerManager::prepareSceneQueriesUpdate(PruningIndex::Enum index) { bool retVal = false; Pruner* pruner = mPrunerExt[index].pruner(); if(pruner && pruner->isDynamic()) retVal = static_cast<DynamicPruner*>(pruner)->prepareBuild(); return retVal ? pruner : NULL; } void PrunerManager::sceneQueryBuildStep(void* handle) { PX_PROFILE_ZONE("SceneQuery.sceneQueryBuildStep", mContextID); Pruner* pruner = reinterpret_cast<Pruner*>(handle); if(pruner && pruner->isDynamic()) { const bool buildFinished = static_cast<DynamicPruner*>(pruner)->buildStep(false); if(buildFinished) mPrunerNeedsUpdating = true; } } // PT: TODO: revisit this. Perhaps it should be the user's responsibility to call the pruner's // visualize functions directly, when & how he wants. void PrunerManager::visualize(PxU32 prunerIndex, PxRenderOutput& out) const { if(prunerIndex==PX_SCENE_PRUNER_STATIC) { if(getPruner(PruningIndex::eSTATIC)) getPruner(PruningIndex::eSTATIC)->visualize(out, SQ_DEBUG_VIZ_STATIC_COLOR, SQ_DEBUG_VIZ_STATIC_COLOR2); } else if(prunerIndex==PX_SCENE_PRUNER_DYNAMIC) { if(getPruner(PruningIndex::eDYNAMIC)) getPruner(PruningIndex::eDYNAMIC)->visualize(out, SQ_DEBUG_VIZ_DYNAMIC_COLOR, SQ_DEBUG_VIZ_DYNAMIC_COLOR2); } else if(prunerIndex==PX_SCENE_COMPOUND_PRUNER) { const CompoundPruner* cp = mCompoundPrunerExt.pruner(); if(cp) cp->visualizeEx(out, SQ_DEBUG_VIZ_COMPOUND_COLOR, true, true); } } void PrunerManager::shiftOrigin(const PxVec3& shift) { for(PxU32 i=0; i<PruningIndex::eCOUNT; i++) mPrunerExt[i].pruner()->shiftOrigin(shift); mCompoundPrunerExt.pruner()->shiftOrigin(shift); } void PrunerManager::addCompoundShape(const PxBVH& pxbvh, PrunerCompoundId compoundId, const PxTransform& compoundTransform, PrunerData* prunerData, const PrunerPayload* payloads, const PxTransform* transforms, bool isDynamic) { const BVH& bvh = static_cast<const BVH&>(pxbvh); const PxU32 nbShapes = bvh.Gu::BVH::getNbBounds(); PX_ALLOCA(res, PrunerHandle, nbShapes); PX_ASSERT(mCompoundPrunerExt.mPruner); mCompoundPrunerExt.mPruner->addCompound(res, bvh, compoundId, compoundTransform, isDynamic, payloads, transforms); const PxU32 index = PxU32(isDynamic); if(!index) invalidateStaticTimestamp(); for(PxU32 i = 0; i < nbShapes; i++) prunerData[i] = createPrunerData(index, res[i]); } void PrunerManager::updateCompoundActor(PrunerCompoundId compoundId, const PxTransform& compoundTransform) { PX_ASSERT(mCompoundPrunerExt.mPruner); const bool isDynamic = mCompoundPrunerExt.mPruner->updateCompound(compoundId, compoundTransform); if(!isDynamic) invalidateStaticTimestamp(); } void PrunerManager::removeCompoundActor(PrunerCompoundId compoundId, PrunerPayloadRemovalCallback* removalCallback) { PX_ASSERT(mCompoundPrunerExt.mPruner); const bool isDynamic = mCompoundPrunerExt.mPruner->removeCompound(compoundId, removalCallback); if(!isDynamic) invalidateStaticTimestamp(); } void PrunerManager::sync(const PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) { if(!count) return; Pruner* dynamicPruner = getPruner(PruningIndex::eDYNAMIC); if(!dynamicPruner) return; PxU32 startIndex = 0; PxU32 numIndices = count; // if shape sim map is not empty, parse the indices and skip update for the dirty one if(ignoredIndices.count()) { // PT: I think this codepath was used with SCB / buffered changes, but it's not needed anymore numIndices = 0; for(PxU32 i=0; i<count; i++) { // if(ignoredIndices.test(boundsIndices[i])) if(ignoredIndices.boundedTest(boundsIndices[i])) { dynamicPruner->updateObjects(handles + startIndex, numIndices, mInflation, boundsIndices + startIndex, bounds, transforms); numIndices = 0; startIndex = i + 1; } else numIndices++; } // PT: we fallback to the next line on purpose - no "else" } dynamicPruner->updateObjects(handles + startIndex, numIndices, mInflation, boundsIndices + startIndex, bounds, transforms); }
17,319
C++
28.965398
225
0.743519
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqCompoundPruner.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 "SqCompoundPruner.h" #include "GuSqInternal.h" #include "GuIncrementalAABBTree.h" #include "GuPruningPool.h" #include "GuAABBTreeQuery.h" #include "GuAABBTreeNode.h" #include "GuSphere.h" #include "GuBox.h" #include "GuCapsule.h" #include "GuBVH.h" #include "GuQuery.h" #include "GuInternal.h" #include "common/PxRenderBuffer.h" #include "common/PxRenderOutput.h" #include "CmVisualization.h" using namespace physx; using namespace Gu; using namespace Sq; // PT: TODO: this is copied from SqBounds.h, should be either moved to Gu and shared or passed as a user parameter #define SQ_PRUNER_EPSILON 0.005f #define SQ_PRUNER_INFLATION (1.0f + SQ_PRUNER_EPSILON) // pruner test shape inflation (not narrow phase shape) #define PARANOIA_CHECKS 0 /////////////////////////////////////////////////////////////////////////////////////////////// BVHCompoundPruner::BVHCompoundPruner(PxU64 contextID) : mCompoundTreePool(contextID), mDrawStatic(false), mDrawDynamic(false) { preallocate(32); } /////////////////////////////////////////////////////////////////////////////////////////////// BVHCompoundPruner::~BVHCompoundPruner() { } /////////////////////////////////////////////////////////////////////////////////////////////// bool BVHCompoundPruner::addCompound(PrunerHandle* results, const BVH& bvh, PrunerCompoundId compoundId, const PxTransform& transform, bool isDynamic, const PrunerPayload* data, const PxTransform* transforms) { PX_ASSERT(bvh.getNbBounds()); const PxBounds3 compoundBounds = PxBounds3::transformFast(transform, bvh.getNodes()->mBV); const PoolIndex poolIndex = mCompoundTreePool.addCompound(results, bvh, compoundBounds, transform, isDynamic, data, transforms); mChangedLeaves.clear(); IncrementalAABBTreeNode* node = mMainTree.insert(poolIndex, mCompoundTreePool.getCurrentCompoundBounds(), mChangedLeaves); updateMapping(poolIndex, node); mActorPoolMap[compoundId] = poolIndex; mPoolActorMap[poolIndex] = compoundId; #if PARANOIA_CHECKS test(); #endif return true; } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::updateMapping(const PoolIndex poolIndex, IncrementalAABBTreeNode* node) { // resize mapping if needed if(mMainTreeUpdateMap.size() <= poolIndex) { const PxU32 resizeSize = mMainTreeUpdateMap.size() * 2; mMainTreeUpdateMap.resize(resizeSize); mPoolActorMap.resize(resizeSize); } // if a node was split we need to update the node indices and also the sibling indices if(!mChangedLeaves.empty()) { if(node && node->isLeaf()) { for(PxU32 j = 0; j < node->getNbPrimitives(); j++) { mMainTreeUpdateMap[node->getPrimitives(NULL)[j]] = node; } } for(PxU32 i = 0; i < mChangedLeaves.size(); i++) { IncrementalAABBTreeNode* changedNode = mChangedLeaves[i]; PX_ASSERT(changedNode->isLeaf()); for(PxU32 j = 0; j < changedNode->getNbPrimitives(); j++) { mMainTreeUpdateMap[changedNode->getPrimitives(NULL)[j]] = changedNode; } } } else { mMainTreeUpdateMap[poolIndex] = node; } } /////////////////////////////////////////////////////////////////////////////////////////////// bool BVHCompoundPruner::removeCompound(PrunerCompoundId compoundId, PrunerPayloadRemovalCallback* removalCallback) { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); bool isDynamic = false; if(poolIndexEntry) { const PoolIndex poolIndex = poolIndexEntry->second; CompoundTree& compoundTree = mCompoundTreePool.getCompoundTrees()[poolIndex]; isDynamic = compoundTree.mFlags & PxCompoundPrunerQueryFlag::eDYNAMIC; const PoolIndex poolRelocatedLastIndex = mCompoundTreePool.removeCompound(poolIndex, removalCallback); IncrementalAABBTreeNode* node = mMainTree.remove(mMainTreeUpdateMap[poolIndex], poolIndex, mCompoundTreePool.getCurrentCompoundBounds()); // if node moved to its parent if(node && node->isLeaf()) { for (PxU32 j = 0; j < node->getNbPrimitives(); j++) { const PoolIndex index = node->getPrimitives(NULL)[j]; mMainTreeUpdateMap[index] = node; } } // fix indices if we made a swap if(poolRelocatedLastIndex != poolIndex) { mMainTreeUpdateMap[poolIndex] = mMainTreeUpdateMap[poolRelocatedLastIndex]; mMainTree.fixupTreeIndices(mMainTreeUpdateMap[poolIndex], poolRelocatedLastIndex, poolIndex); mActorPoolMap[mPoolActorMap[poolRelocatedLastIndex]] = poolIndex; mPoolActorMap[poolIndex] = mPoolActorMap[poolRelocatedLastIndex]; } mActorPoolMap.erase(compoundId); } #if PARANOIA_CHECKS test(); #endif return isDynamic; } /////////////////////////////////////////////////////////////////////////////////////////////// bool BVHCompoundPruner::updateCompound(PrunerCompoundId compoundId, const PxTransform& transform) { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); bool isDynamic = false; if(poolIndexEntry) { const PxU32 poolIndex = poolIndexEntry->second; CompoundTree& compoundTree = mCompoundTreePool.getCompoundTrees()[poolIndex]; isDynamic = compoundTree.mFlags & PxCompoundPrunerQueryFlag::eDYNAMIC; compoundTree.mGlobalPose = transform; PxBounds3 localBounds; const IncrementalAABBTreeNode* node = compoundTree.mTree->getNodes(); V4StoreU(node->mBVMin, &localBounds.minimum.x); PX_ALIGN(16, PxVec4) max4; V4StoreA(node->mBVMax, &max4.x); localBounds.maximum = PxVec3(max4.x, max4.y, max4.z); const PxBounds3 compoundBounds = PxBounds3::transformFast(transform, localBounds); mCompoundTreePool.getCurrentCompoundBounds()[poolIndex] = compoundBounds; mChangedLeaves.clear(); IncrementalAABBTreeNode* mainTreeNode = mMainTree.update(mMainTreeUpdateMap[poolIndex], poolIndex, mCompoundTreePool.getCurrentCompoundBounds(), mChangedLeaves); // we removed node during update, need to update the mapping updateMapping(poolIndex, mainTreeNode); } #if PARANOIA_CHECKS test(); #endif return isDynamic; } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::test() { if(mMainTree.getNodes()) { for(PxU32 i = 0; i < mCompoundTreePool.getNbObjects(); i++) { mMainTree.checkTreeLeaf(mMainTreeUpdateMap[i], i); } } } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::release() { } ////////////////////////////////////////////////////////////////////////// // Queries implementation ////////////////////////////////////////////////////////////////////////// namespace { struct CompoundCallbackRaycastAdapter { PX_FORCE_INLINE CompoundCallbackRaycastAdapter(CompoundPrunerRaycastCallback& pcb, const CompoundTree& tree) : mCallback(pcb), mTree(tree) {} PX_FORCE_INLINE bool invoke(PxReal& distance, PxU32 primIndex) { return mCallback.invoke(distance, primIndex, mTree.mPruningPool->getObjects(), mTree.mPruningPool->getTransforms(), &mTree.mGlobalPose); } CompoundPrunerRaycastCallback& mCallback; const CompoundTree& mTree; PX_NOCOPY(CompoundCallbackRaycastAdapter) }; struct CompoundCallbackOverlapAdapter { PX_FORCE_INLINE CompoundCallbackOverlapAdapter(CompoundPrunerOverlapCallback& pcb, const CompoundTree& tree) : mCallback(pcb), mTree(tree) {} PX_FORCE_INLINE bool invoke(PxU32 primIndex) { return mCallback.invoke(primIndex, mTree.mPruningPool->getObjects(), mTree.mPruningPool->getTransforms(), &mTree.mGlobalPose); } CompoundPrunerOverlapCallback& mCallback; const CompoundTree& mTree; PX_NOCOPY(CompoundCallbackOverlapAdapter) }; } template<class PrunerCallback> struct MainTreeCompoundPrunerCallback { MainTreeCompoundPrunerCallback(PrunerCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : mPrunerCallback(prunerCallback), mQueryFlags(flags), mCompoundTrees(compoundTrees) { } virtual ~MainTreeCompoundPrunerCallback() {} PX_FORCE_INLINE bool filtering(const CompoundTree& compoundTree) const { if(!(compoundTree.mFlags & mQueryFlags) || !compoundTree.mTree->getNodes()) return true; return false; } protected: PrunerCallback& mPrunerCallback; const PxCompoundPrunerQueryFlags mQueryFlags; const CompoundTree* mCompoundTrees; PX_NOCOPY(MainTreeCompoundPrunerCallback) }; // Raycast/sweeps callback for main AABB tree template<bool tInflate> struct MainTreeRaycastCompoundPrunerCallback : MainTreeCompoundPrunerCallback<CompoundPrunerRaycastCallback> { MainTreeRaycastCompoundPrunerCallback(const PxVec3& origin, const PxVec3& unitDir, const PxVec3& extent, CompoundPrunerRaycastCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : MainTreeCompoundPrunerCallback(prunerCallback, flags, compoundTrees), mOrigin(origin), mUnitDir(unitDir), mExtent(extent) { } virtual ~MainTreeRaycastCompoundPrunerCallback() {} bool invoke(PxReal& distance, PxU32 primIndex) { const CompoundTree& compoundTree = mCompoundTrees[primIndex]; if(filtering(compoundTree)) return true; // transfer to actor local space const PxVec3 localOrigin = compoundTree.mGlobalPose.transformInv(mOrigin); const PxVec3 localDir = compoundTree.mGlobalPose.q.rotateInv(mUnitDir); PxVec3 localExtent = mExtent; if(tInflate) { const PxBounds3 wBounds = PxBounds3::centerExtents(mOrigin, mExtent); const PxBounds3 localBounds = PxBounds3::transformSafe(compoundTree.mGlobalPose.getInverse(), wBounds); localExtent = localBounds.getExtents(); } // raycast the merged tree CompoundCallbackRaycastAdapter pcb(mPrunerCallback, compoundTree); return AABBTreeRaycast<tInflate, true, IncrementalAABBTree, IncrementalAABBTreeNode, CompoundCallbackRaycastAdapter>() (compoundTree.mPruningPool->getCurrentAABBTreeBounds(), *compoundTree.mTree, localOrigin, localDir, distance, localExtent, pcb); } PX_NOCOPY(MainTreeRaycastCompoundPrunerCallback) private: const PxVec3& mOrigin; const PxVec3& mUnitDir; const PxVec3& mExtent; }; ////////////////////////////////////////////////////////////////////////// // raycast against the compound pruner bool BVHCompoundPruner::raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, CompoundPrunerRaycastCallback& prunerCallback, PxCompoundPrunerQueryFlags flags) const { bool again = true; // search the main tree if there are nodes if(mMainTree.getNodes()) { const PxVec3 extent(0.0f); // main tree callback MainTreeRaycastCompoundPrunerCallback<false> pcb(origin, unitDir, extent, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); // traverse the main tree again = AABBTreeRaycast<false, true, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeRaycastCompoundPrunerCallback<false> >() (mCompoundTreePool.getCurrentAABBTreeBounds(), mMainTree, origin, unitDir, inOutDistance, extent, pcb); } return again; } ////////////////////////////////////////////////////////////////////////// // overlap main tree callback // A.B. templated version is complicated due to test transformations, will do a callback per primitive struct MainTreeOverlapCompoundPrunerCallback : MainTreeCompoundPrunerCallback<CompoundPrunerOverlapCallback> { MainTreeOverlapCompoundPrunerCallback(const ShapeData& queryVolume, CompoundPrunerOverlapCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : MainTreeCompoundPrunerCallback(prunerCallback, flags, compoundTrees), mQueryVolume(queryVolume) { } virtual ~MainTreeOverlapCompoundPrunerCallback() {} PX_NOCOPY(MainTreeOverlapCompoundPrunerCallback) protected: const ShapeData& mQueryVolume; }; // OBB struct MainTreeOBBOverlapCompoundPrunerCallback : public MainTreeOverlapCompoundPrunerCallback { MainTreeOBBOverlapCompoundPrunerCallback(const ShapeData& queryVolume, CompoundPrunerOverlapCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : MainTreeOverlapCompoundPrunerCallback(queryVolume, prunerCallback, flags, compoundTrees) {} bool invoke(PxU32 primIndex) { const CompoundTree& compoundTree = mCompoundTrees[primIndex]; if(filtering(compoundTree)) return true; const PxVec3 localPos = compoundTree.mGlobalPose.transformInv(mQueryVolume.getPrunerWorldPos()); const PxMat33 transfMat(compoundTree.mGlobalPose.q); const PxMat33 localRot = transfMat.getTranspose()*mQueryVolume.getPrunerWorldRot33(); const OBBAABBTest localTest(localPos, localRot, mQueryVolume.getPrunerBoxGeomExtentsInflated()); // overlap the compound local tree CompoundCallbackOverlapAdapter pcb(mPrunerCallback, compoundTree); return AABBTreeOverlap<true, OBBAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, CompoundCallbackOverlapAdapter>() (compoundTree.mPruningPool->getCurrentAABBTreeBounds(), *compoundTree.mTree, localTest, pcb); } PX_NOCOPY(MainTreeOBBOverlapCompoundPrunerCallback) }; // AABB struct MainTreeAABBOverlapCompoundPrunerCallback : public MainTreeOverlapCompoundPrunerCallback { MainTreeAABBOverlapCompoundPrunerCallback(const ShapeData& queryVolume, CompoundPrunerOverlapCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : MainTreeOverlapCompoundPrunerCallback(queryVolume, prunerCallback, flags, compoundTrees) {} bool invoke(PxU32 primIndex) { const CompoundTree& compoundTree = mCompoundTrees[primIndex]; if(filtering(compoundTree)) return true; const PxVec3 localPos = compoundTree.mGlobalPose.transformInv(mQueryVolume.getPrunerWorldPos()); const PxMat33 transfMat(compoundTree.mGlobalPose.q); const PxMat33 localRot = transfMat.getTranspose()*mQueryVolume.getPrunerWorldRot33(); // A.B. we dont have the AABB in local space, either we test OBB local space or // we retest the AABB with the worldSpace AABB of the local tree??? const OBBAABBTest localTest(localPos, localRot, mQueryVolume.getPrunerBoxGeomExtentsInflated()); // overlap the compound local tree CompoundCallbackOverlapAdapter pcb(mPrunerCallback, compoundTree); return AABBTreeOverlap<true, OBBAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, CompoundCallbackOverlapAdapter>() (compoundTree.mPruningPool->getCurrentAABBTreeBounds(), *compoundTree.mTree, localTest, pcb); } PX_NOCOPY(MainTreeAABBOverlapCompoundPrunerCallback) }; // Capsule struct MainTreeCapsuleOverlapCompoundPrunerCallback : public MainTreeOverlapCompoundPrunerCallback { MainTreeCapsuleOverlapCompoundPrunerCallback(const ShapeData& queryVolume, CompoundPrunerOverlapCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : MainTreeOverlapCompoundPrunerCallback(queryVolume, prunerCallback, flags, compoundTrees) {} bool invoke(PxU32 primIndex) { const CompoundTree& compoundTree = mCompoundTrees[primIndex]; if(filtering(compoundTree)) return true; const PxMat33 transfMat(compoundTree.mGlobalPose.q); const Capsule& capsule = mQueryVolume.getGuCapsule(); const CapsuleAABBTest localTest( compoundTree.mGlobalPose.transformInv(capsule.p1), transfMat.getTranspose()*mQueryVolume.getPrunerWorldRot33().column0, mQueryVolume.getCapsuleHalfHeight()*2.0f, PxVec3(capsule.radius*SQ_PRUNER_INFLATION)); // overlap the compound local tree CompoundCallbackOverlapAdapter pcb(mPrunerCallback, compoundTree); return AABBTreeOverlap<true, CapsuleAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, CompoundCallbackOverlapAdapter>() (compoundTree.mPruningPool->getCurrentAABBTreeBounds(), *compoundTree.mTree, localTest, pcb); } PX_NOCOPY(MainTreeCapsuleOverlapCompoundPrunerCallback) }; // Sphere struct MainTreeSphereOverlapCompoundPrunerCallback : public MainTreeOverlapCompoundPrunerCallback { MainTreeSphereOverlapCompoundPrunerCallback(const ShapeData& queryVolume, CompoundPrunerOverlapCallback& prunerCallback, PxCompoundPrunerQueryFlags flags, const CompoundTree* compoundTrees) : MainTreeOverlapCompoundPrunerCallback(queryVolume, prunerCallback, flags, compoundTrees) {} bool invoke(PxU32 primIndex) { const CompoundTree& compoundTree = mCompoundTrees[primIndex]; if(filtering(compoundTree)) return true; const Sphere& sphere = mQueryVolume.getGuSphere(); const SphereAABBTest localTest(compoundTree.mGlobalPose.transformInv(sphere.center), sphere.radius); // overlap the compound local tree CompoundCallbackOverlapAdapter pcb(mPrunerCallback, compoundTree); return AABBTreeOverlap<true, SphereAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, CompoundCallbackOverlapAdapter>() (compoundTree.mPruningPool->getCurrentAABBTreeBounds(), *compoundTree.mTree, localTest, pcb); } PX_NOCOPY(MainTreeSphereOverlapCompoundPrunerCallback) }; ////////////////////////////////////////////////////////////////////////// // overlap implementation bool BVHCompoundPruner::overlap(const ShapeData& queryVolume, CompoundPrunerOverlapCallback& prunerCallback, PxCompoundPrunerQueryFlags flags) const { if(!mMainTree.getNodes()) return true; bool again = true; const Gu::AABBTreeBounds& bounds = mCompoundTreePool.getCurrentAABBTreeBounds(); switch (queryVolume.getType()) { case PxGeometryType::eBOX: { if(queryVolume.isOBB()) { const DefaultOBBAABBTest test(queryVolume); MainTreeOBBOverlapCompoundPrunerCallback pcb(queryVolume, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); again = AABBTreeOverlap<true, OBBAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeOBBOverlapCompoundPrunerCallback>()(bounds, mMainTree, test, pcb); } else { const DefaultAABBAABBTest test(queryVolume); MainTreeAABBOverlapCompoundPrunerCallback pcb(queryVolume, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); again = AABBTreeOverlap<true, AABBAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeAABBOverlapCompoundPrunerCallback>()(bounds, mMainTree, test, pcb); } } break; case PxGeometryType::eCAPSULE: { const DefaultCapsuleAABBTest test(queryVolume, SQ_PRUNER_INFLATION); MainTreeCapsuleOverlapCompoundPrunerCallback pcb(queryVolume, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); again = AABBTreeOverlap<true, CapsuleAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeCapsuleOverlapCompoundPrunerCallback >()(bounds, mMainTree, test, pcb); } break; case PxGeometryType::eSPHERE: { const DefaultSphereAABBTest test(queryVolume); MainTreeSphereOverlapCompoundPrunerCallback pcb(queryVolume, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); again = AABBTreeOverlap<true, SphereAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeSphereOverlapCompoundPrunerCallback>()(bounds, mMainTree, test, pcb); } break; case PxGeometryType::eCONVEXMESH: { const DefaultOBBAABBTest test(queryVolume); MainTreeOBBOverlapCompoundPrunerCallback pcb(queryVolume, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); again = AABBTreeOverlap<true, OBBAABBTest, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeOBBOverlapCompoundPrunerCallback>()(bounds, mMainTree, test, pcb); } break; default: PX_ALWAYS_ASSERT_MESSAGE("unsupported overlap query volume geometry type"); } return again; } /////////////////////////////////////////////////////////////////////////////////////////////// bool BVHCompoundPruner::sweep(const ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, CompoundPrunerRaycastCallback& prunerCallback, PxCompoundPrunerQueryFlags flags) const { bool again = true; if(mMainTree.getNodes()) { const PxBounds3& aabb = queryVolume.getPrunerInflatedWorldAABB(); const PxVec3 extents = aabb.getExtents(); const PxVec3 center = aabb.getCenter(); MainTreeRaycastCompoundPrunerCallback<true> pcb(center, unitDir, extents, prunerCallback, flags, mCompoundTreePool.getCompoundTrees()); again = AABBTreeRaycast<true, true, IncrementalAABBTree, IncrementalAABBTreeNode, MainTreeRaycastCompoundPrunerCallback<true> >() (mCompoundTreePool.getCurrentAABBTreeBounds(), mMainTree, center, unitDir, inOutDistance, extents, pcb); } return again; } /////////////////////////////////////////////////////////////////////////////////////////////// const PrunerPayload& BVHCompoundPruner::getPayloadData(PrunerHandle handle, PrunerCompoundId compoundId, PrunerPayloadData* data) const { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); return mCompoundTreePool.getCompoundTrees()[poolIndexEntry->second].mPruningPool->getPayloadData(handle, data); } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::preallocate(PxU32 nbEntries) { mCompoundTreePool.preallocate(nbEntries); mMainTreeUpdateMap.resizeUninitialized(nbEntries); mPoolActorMap.resizeUninitialized(nbEntries); mChangedLeaves.reserve(nbEntries); } /////////////////////////////////////////////////////////////////////////////////////////////// bool BVHCompoundPruner::setTransform(PrunerHandle handle, PrunerCompoundId compoundId, const PxTransform& transform) { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); return mCompoundTreePool.getCompoundTrees()[poolIndexEntry->second].mPruningPool->setTransform(handle, transform); } const PxTransform& BVHCompoundPruner::getTransform(PrunerCompoundId compoundId) const { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); return mCompoundTreePool.getCompoundTrees()[poolIndexEntry->second].mGlobalPose; } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::updateObjectAfterManualBoundsUpdates(PrunerCompoundId compoundId, const PrunerHandle handle) { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); if(!poolIndexEntry) return; mCompoundTreePool.getCompoundTrees()[poolIndexEntry->second].updateObjectAfterManualBoundsUpdates(handle); const PxU32 poolIndex = poolIndexEntry->second; updateMainTreeNode(poolIndex); } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::removeObject(PrunerCompoundId compoundId, const PrunerHandle handle, PrunerPayloadRemovalCallback* removalCallback) { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); if(!poolIndexEntry) return; const PxU32 poolIndex = poolIndexEntry->second; mCompoundTreePool.getCompoundTrees()[poolIndex].removeObject(handle, removalCallback); // edge case, we removed all objects for the compound tree, we need to remove it now completely if(!mCompoundTreePool.getCompoundTrees()[poolIndex].mTree->getNodes()) removeCompound(compoundId, removalCallback); else updateMainTreeNode(poolIndex); } /////////////////////////////////////////////////////////////////////////////////////////////// bool BVHCompoundPruner::addObject(PrunerCompoundId compoundId, PrunerHandle& result, const PxBounds3& bounds, const PrunerPayload userData, const PxTransform& transform) { const ActorIdPoolIndexMap::Entry* poolIndexEntry = mActorPoolMap.find(compoundId); PX_ASSERT(poolIndexEntry); if(!poolIndexEntry) return false; mCompoundTreePool.getCompoundTrees()[poolIndexEntry->second].addObject(result, bounds, userData, transform); const PxU32 poolIndex = poolIndexEntry->second; updateMainTreeNode(poolIndex); return true; } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::updateMainTreeNode(PoolIndex poolIndex) { PxBounds3 localBounds; const IncrementalAABBTreeNode* node = mCompoundTreePool.getCompoundTrees()[poolIndex].mTree->getNodes(); V4StoreU(node->mBVMin, &localBounds.minimum.x); PX_ALIGN(16, PxVec4) max4; V4StoreA(node->mBVMax, &max4.x); localBounds.maximum = PxVec3(max4.x, max4.y, max4.z); const PxBounds3 compoundBounds = PxBounds3::transformFast(mCompoundTreePool.getCompoundTrees()[poolIndex].mGlobalPose, localBounds); mCompoundTreePool.getCurrentCompoundBounds()[poolIndex] = compoundBounds; mChangedLeaves.clear(); IncrementalAABBTreeNode* mainTreeNode = mMainTree.update(mMainTreeUpdateMap[poolIndex], poolIndex, mCompoundTreePool.getCurrentCompoundBounds(), mChangedLeaves); // we removed node during update, need to update the mapping updateMapping(poolIndex, mainTreeNode); } /////////////////////////////////////////////////////////////////////////////////////////////// void BVHCompoundPruner::shiftOrigin(const PxVec3& shift) { mCompoundTreePool.shiftOrigin(shift); mMainTree.shiftOrigin(shift); } /////////////////////////////////////////////////////////////////////////////////////////////// namespace { class CompoundTreeVizCb : public DebugVizCallback { PX_NOCOPY(CompoundTreeVizCb) public: CompoundTreeVizCb(PxRenderOutput& out, const CompoundTree& tree) : mOut (out), mPose (tree.mGlobalPose) { } virtual bool visualizeNode(const IncrementalAABBTreeNode& /*node*/, const PxBounds3& bounds) { if(0) { Cm::renderOutputDebugBox(mOut, PxBounds3::transformSafe(mPose, bounds)); } else { PxVec3 pts[8]; computeBoxPoints(bounds, pts); for(PxU32 i=0;i<8;i++) pts[i] = mPose.transform(pts[i]); const PxU8* edges = getBoxEdges(); for(PxU32 i=0;i<12;i++) { const PxVec3& p0 = pts[*edges++]; const PxVec3& p1 = pts[*edges++]; mOut.outputSegment(p0, p1); } } return true; } PxRenderOutput& mOut; const PxTransform& mPose; }; class CompoundPrunerDebugVizCb : public DebugVizCallback { PX_NOCOPY(CompoundPrunerDebugVizCb) public: CompoundPrunerDebugVizCb(PxRenderOutput& out, const CompoundTree* trees, bool debugStatic, bool debugDynamic) : mOut (out), mTrees (trees), mDebugVizStatic (debugStatic), mDebugVizDynamic(debugDynamic) {} virtual bool visualizeNode(const IncrementalAABBTreeNode& node, const PxBounds3& /*bounds*/) { if(node.isLeaf()) { PxU32 nbPrims = node.getNbPrimitives(); const PxU32* prims = node.getPrimitives(NULL); while(nbPrims--) { const CompoundTree& compoundTree = mTrees[*prims++]; const bool isDynamic = compoundTree.mFlags & PxCompoundPrunerQueryFlag::eDYNAMIC; if((mDebugVizDynamic && isDynamic) || (mDebugVizStatic && !isDynamic)) { const PxU32 color = isDynamic ? SQ_DEBUG_VIZ_DYNAMIC_COLOR : SQ_DEBUG_VIZ_STATIC_COLOR; CompoundTreeVizCb leafCB(mOut, compoundTree); visualizeTree(mOut, color, compoundTree.mTree, &leafCB); mOut << SQ_DEBUG_VIZ_COMPOUND_COLOR; } } } return false; } PxRenderOutput& mOut; const CompoundTree* mTrees; const bool mDebugVizStatic; const bool mDebugVizDynamic; }; } void BVHCompoundPruner::visualize(PxRenderOutput& out, PxU32 primaryColor, PxU32 /*secondaryColor*/) const { if(mDrawStatic || mDrawDynamic) { CompoundPrunerDebugVizCb cb(out, mCompoundTreePool.getCompoundTrees(), mDrawStatic, mDrawDynamic); visualizeTree(out, primaryColor, &mMainTree, &cb); } } void BVHCompoundPruner::visualizeEx(PxRenderOutput& out, PxU32 color, bool drawStatic, bool drawDynamic) const { mDrawStatic = drawStatic; mDrawDynamic = drawDynamic; visualize(out, color, color); } ///////////////////////////////////////////////////////////////////////////////////////////////
29,393
C++
36.349428
221
0.72997
NVIDIA-Omniverse/PhysX/physx/source/scenequery/src/SqCompoundPruner.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_COMPOUND_PRUNER_H #define SQ_COMPOUND_PRUNER_H #include "SqCompoundPruningPool.h" #include "GuSqInternal.h" #include "GuPrunerMergeData.h" #include "GuIncrementalAABBTree.h" #include "GuPruningPool.h" #include "foundation/PxHashMap.h" #include "foundation/PxArray.h" namespace physx { namespace Sq { /////////////////////////////////////////////////////////////////////////////////////////////// typedef PxHashMap<PrunerCompoundId, Gu::PoolIndex> ActorIdPoolIndexMap; typedef PxArray<PrunerCompoundId> PoolIndexActorIdMap; /////////////////////////////////////////////////////////////////////////////////////////////// class BVHCompoundPruner : public CompoundPruner { public: BVHCompoundPruner(PxU64 contextID); virtual ~BVHCompoundPruner(); void release(); // BasePruner DECLARE_BASE_PRUNER_API //~BasePruner // CompoundPruner // compound level virtual bool addCompound(Gu::PrunerHandle* results, const Gu::BVH& bvh, PrunerCompoundId compoundId, const PxTransform& transform, bool isDynamic, const Gu::PrunerPayload* data, const PxTransform* transforms); virtual bool removeCompound(PrunerCompoundId compoundId, Gu::PrunerPayloadRemovalCallback* removalCallback); virtual bool updateCompound(PrunerCompoundId compoundId, const PxTransform& transform); // object level virtual void updateObjectAfterManualBoundsUpdates(PrunerCompoundId compoundId, const Gu::PrunerHandle handle); virtual void removeObject(PrunerCompoundId compoundId, const Gu::PrunerHandle handle, Gu::PrunerPayloadRemovalCallback* removalCallback); virtual bool addObject(PrunerCompoundId compoundId, Gu::PrunerHandle& result, const PxBounds3& bounds, const Gu::PrunerPayload userData, const PxTransform& transform); //queries virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, CompoundPrunerRaycastCallback&, PxCompoundPrunerQueryFlags flags) const; virtual bool overlap(const Gu::ShapeData& queryVolume, CompoundPrunerOverlapCallback&, PxCompoundPrunerQueryFlags flags) const; virtual bool sweep(const Gu::ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, CompoundPrunerRaycastCallback&, PxCompoundPrunerQueryFlags flags) const; virtual const Gu::PrunerPayload& getPayloadData(Gu::PrunerHandle handle, PrunerCompoundId compoundId, Gu::PrunerPayloadData* data) const; virtual void preallocate(PxU32 nbEntries); virtual bool setTransform(Gu::PrunerHandle handle, PrunerCompoundId compoundId, const PxTransform& transform); virtual const PxTransform& getTransform(PrunerCompoundId compoundId) const; virtual void visualizeEx(PxRenderOutput& out, PxU32 color, bool drawStatic, bool drawDynamic) const; // ~CompoundPruner private: void updateMapping(const Gu::PoolIndex poolIndex, Gu::IncrementalAABBTreeNode* node); void updateMainTreeNode(Gu::PoolIndex index); void test(); Gu::IncrementalAABBTree mMainTree; UpdateMap mMainTreeUpdateMap; CompoundTreePool mCompoundTreePool; ActorIdPoolIndexMap mActorPoolMap; PoolIndexActorIdMap mPoolActorMap; Gu::NodeList mChangedLeaves; mutable bool mDrawStatic; mutable bool mDrawDynamic; }; } } #endif
5,057
C
48.106796
217
0.733241
NVIDIA-Omniverse/PhysX/physx/source/scenequery/include/SqQuery.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_QUERY_H #define SQ_QUERY_H // PT: SQ-API LEVEL 3 (Level 1 = SqPruner.h, Level 2 = SqManager/SqPrunerData) // PT: this file is part of a "high-level" set of files within Sq. The SqPruner API doesn't rely on them. // PT: this should really be at Np level but moving it to Sq allows us to share it. #include "foundation/PxSimpleTypes.h" #include "geometry/PxGeometryQueryFlags.h" #include "SqManager.h" #include "PxQueryReport.h" #include "GuCachedFuncs.h" namespace physx { class PxGeometry; struct PxQueryFilterData; struct PxFilterData; class PxQueryFilterCallback; namespace Sq { struct MultiQueryInput; class PVDCapture { public: PVDCapture() {} virtual ~PVDCapture() {} virtual bool transmitSceneQueries() = 0; virtual void raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) = 0; virtual void sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) = 0; virtual void overlap(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData) = 0; }; // SceneQueries-level adapter. Augments the PrunerManager-level adapter with functions needed to perform queries. class QueryAdapter : public Adapter { public: QueryAdapter() {} virtual ~QueryAdapter() {} // PT: TODO: decouple from PxQueryCache? virtual Gu::PrunerHandle findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const = 0; // PT: TODO: return reference? but this version is at least consistent with getActorShape virtual void getFilterData(const Gu::PrunerPayload& payload, PxFilterData& filterData) const = 0; virtual void getActorShape(const Gu::PrunerPayload& payload, PxActorShape& actorShape) const = 0; }; } class SceneQueries { PX_NOCOPY(SceneQueries) public: SceneQueries(Sq::PVDCapture* pvd, PxU64 contextID, Gu::Pruner* staticPruner, Gu::Pruner* dynamicPruner, PxU32 dynamicTreeRebuildRateHint, float inflation, const PxSceneLimits& limits, const Sq::QueryAdapter& adapter); ~SceneQueries(); PX_FORCE_INLINE Sq::PrunerManager& getPrunerManagerFast() { return mSQManager; } PX_FORCE_INLINE const Sq::PrunerManager& getPrunerManagerFast() const { return mSQManager; } template<typename QueryHit> bool multiQuery( const Sq::MultiQueryInput& in, PxHitCallback<QueryHit>& hits, PxHitFlags hitFlags, const PxQueryCache* cache, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const; bool _raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, // Ray data PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; bool _sweep( const PxGeometry& geometry, const PxTransform& pose, // GeomObject data const PxVec3& unitDir, const PxReal distance, // Ray data PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const; bool _overlap( const PxGeometry& geometry, const PxTransform& transform, // GeomObject data PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; PX_FORCE_INLINE PxU64 getContextId() const { return mSQManager.getContextId(); } Sq::PrunerManager mSQManager; public: Gu::CachedFuncs mCachedFuncs; Sq::PVDCapture* mPVD; }; #if PX_SUPPORT_EXTERN_TEMPLATE //explicit template instantiation declaration extern template bool SceneQueries::multiQuery<PxRaycastHit>(const Sq::MultiQueryInput&, PxHitCallback<PxRaycastHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; extern template bool SceneQueries::multiQuery<PxOverlapHit>(const Sq::MultiQueryInput&, PxHitCallback<PxOverlapHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; extern template bool SceneQueries::multiQuery<PxSweepHit>(const Sq::MultiQueryInput&, PxHitCallback<PxSweepHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; #endif } #endif
6,613
C
44.930555
212
0.732799
NVIDIA-Omniverse/PhysX/physx/source/scenequery/include/SqPrunerData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_PRUNER_DATA_H #define SQ_PRUNER_DATA_H /** \addtogroup physics @{ */ #include "SqTypedef.h" // PT: SQ-API LEVEL 2 (Level 1 = SqPruner.h) // PT: this file is part of a "high-level" set of files within Sq. The SqPruner API doesn't rely on them. // PT: this should really be at Np level but moving it to Sq allows us to share it. namespace physx { namespace Sq { struct PruningIndex { enum Enum { eSTATIC = 0, // PT: must match PX_SCENE_PRUNER_STATIC eDYNAMIC = 1, // PT: must match PX_SCENE_PRUNER_DYNAMIC eCOUNT = 2 }; }; PX_FORCE_INLINE PrunerData createPrunerData(PxU32 index, Gu::PrunerHandle h) { return PrunerData((h << 1) | index); } PX_FORCE_INLINE PxU32 getPrunerIndex(PrunerData data) { return PxU32(data & 1); } PX_FORCE_INLINE Gu::PrunerHandle getPrunerHandle(PrunerData data) { return Gu::PrunerHandle(data >> 1); } } } /** @} */ #endif
2,600
C
39.640624
118
0.734231
NVIDIA-Omniverse/PhysX/physx/source/scenequery/include/SqPruner.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_PRUNER_H #define SQ_PRUNER_H #include "foundation/PxBounds3.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxFlags.h" #include "GuPruner.h" #include "SqTypedef.h" namespace physx { namespace Gu { class BVH; } namespace Sq { /** \brief Compound-pruner-specific flags for scene queries. */ struct PxCompoundPrunerQueryFlag { enum Enum { eSTATIC = (1<<0), //!< Traverse static compounds eDYNAMIC = (1<<1), //!< Traverse dynamic compounds }; }; /** \brief Flags typedef for the set of bits defined in PxCompoundPrunerQueryFlag. */ typedef PxFlags<PxCompoundPrunerQueryFlag::Enum,PxU32> PxCompoundPrunerQueryFlags; PX_FLAGS_OPERATORS(PxCompoundPrunerQueryFlag::Enum,PxU32) struct CompoundPrunerRaycastCallback { CompoundPrunerRaycastCallback() {} virtual ~CompoundPrunerRaycastCallback() {} virtual bool invoke(PxReal& distance, PxU32 primIndex, const Gu::PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) = 0; }; struct CompoundPrunerOverlapCallback { CompoundPrunerOverlapCallback() {} virtual ~CompoundPrunerOverlapCallback() {} virtual bool invoke(PxU32 primIndex, const Gu::PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) = 0; }; ////////////////////////////////////////////////////////////////////////// /** * Pruner holding compound objects */ ////////////////////////////////////////////////////////////////////////// class CompoundPruner : public Gu::BasePruner { public: virtual ~CompoundPruner() {} /** \brief Adds compound to the pruner. \param results [out] an array for resulting handles \param bvh [in] BVH \param compoundId [in] compound id \param transform [in] compound transform \param data [in] an array of object data \return true if success, false if internal allocation failed. The first failing add results in a INVALID_PRUNERHANDLE. Handles are usable as indices. Each handle is either be a recycled handle returned by the client via removeObjects(), or a fresh handle that is either zero, or one greater than the last fresh handle returned. */ virtual bool addCompound(Gu::PrunerHandle* results, const Gu::BVH& bvh, PrunerCompoundId compoundId, const PxTransform& transform, bool isDynamic, const Gu::PrunerPayload* data, const PxTransform* transforms) = 0; /** Removes compound from the pruner. \param compoundId [in] compound to remove */ virtual bool removeCompound(PrunerCompoundId compoundId, Gu::PrunerPayloadRemovalCallback* removalCallback) = 0; /** Updates compound object \param compoundId [in] compound to update \param transform [in] compound transformation */ virtual bool updateCompound(PrunerCompoundId compoundId, const PxTransform& transform) = 0; /** Updates object after manually updating their bounds via "getPayload" calls. \param compoundId [in] compound that the object belongs to \param handle [in] the object to update */ virtual void updateObjectAfterManualBoundsUpdates(PrunerCompoundId compoundId, const Gu::PrunerHandle handle) = 0; /** Removes object from compound pruner. \param compoundId [in] compound that the object belongs to \param handle [in] the object to remove */ virtual void removeObject(PrunerCompoundId compoundId, const Gu::PrunerHandle handle, Gu::PrunerPayloadRemovalCallback* removalCallback) = 0; /** \brief Adds object to the pruner. \param compoundId [in] compound that the object belongs to \param result [out] an array for resulting handles \param bounds [in] an array of bounds. These bounds are used as-is so they should be pre-inflated if inflation is needed. \param userData [in] an array of object data \return true if success, false if internal allocation failed. The first failing add results in a INVALID_PRUNERHANDLE. */ virtual bool addObject(PrunerCompoundId compoundId, Gu::PrunerHandle& result, const PxBounds3& bounds, const Gu::PrunerPayload userData, const PxTransform& transform) = 0; /** * Query functions * * Note: return value may disappear if PrunerCallback contains the necessary information * currently it is still used for the dynamic pruner internally (to decide if added objects must be queried) */ virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal& inOutDistance, CompoundPrunerRaycastCallback&, PxCompoundPrunerQueryFlags flags) const = 0; virtual bool overlap(const Gu::ShapeData& queryVolume, CompoundPrunerOverlapCallback&, PxCompoundPrunerQueryFlags flags) const = 0; virtual bool sweep(const Gu::ShapeData& queryVolume, const PxVec3& unitDir, PxReal& inOutDistance, CompoundPrunerRaycastCallback&, PxCompoundPrunerQueryFlags flags) const = 0; /** \brief Retrieves the object's payload and data associated with the handle. This function returns the payload associated with a given handle. Additionally it can return the destination addresses for the object's bounds & transform. The user can then write the new bounds and transform there, before eventually calling updateObjects(). \param[in] handle Object handle (initially returned by addObjects()) \param[in] compoundId The compound id \param[out] data Optional location where to store the internal data associated with the payload. \return The payload associated with the given handle. */ virtual const Gu::PrunerPayload& getPayloadData(Gu::PrunerHandle handle, PrunerCompoundId compoundId, Gu::PrunerPayloadData* data) const = 0; /** \brief Preallocate space \param[in] nbEntries The number of entries to preallocate space for */ virtual void preallocate(PxU32 nbEntries) = 0; // PT: beware, shape transform virtual bool setTransform(Gu::PrunerHandle handle, PrunerCompoundId compoundId, const PxTransform& transform) = 0; // PT: beware, actor transform virtual const PxTransform& getTransform(PrunerCompoundId compoundId) const = 0; virtual void visualizeEx(PxRenderOutput& out, PxU32 color, bool drawStatic, bool drawDynamic) const = 0; }; } } #endif
7,785
C
40.195767
218
0.747848
NVIDIA-Omniverse/PhysX/physx/source/scenequery/include/SqManager.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_MANAGER_H #define SQ_MANAGER_H // PT: SQ-API LEVEL 2 (Level 1 = SqPruner.h) // PT: this file is part of a "high-level" set of files within Sq. The SqPruner API doesn't rely on them. // PT: this should really be at Np level but moving it to Sq allows us to share it. #include "common/PxPhysXCommonConfig.h" #include "foundation/PxBitMap.h" #include "foundation/PxArray.h" #include "SqPruner.h" #include "geometry/PxGeometryHelpers.h" namespace physx { namespace Sq { // PrunerManager-level adapter class Adapter { public: Adapter() {} virtual ~Adapter() {} // Retrieves the PxGeometry associated with a given PrunerPayload. This will be called by // the PrunerManager class when computing bounds. virtual const PxGeometry& getGeometry(const Gu::PrunerPayload& payload) const = 0; }; // PT: extended pruner structure. We might want to move the additional data to the pruner itself later. struct PrunerExt : public PxUserAllocated { // private: PrunerExt(); ~PrunerExt(); void init(Gu::Pruner* pruner); void flushMemory(); void preallocate(PxU32 nbShapes); void addToDirtyList(Gu::PrunerHandle handle, bool dynamic, const PxTransform& transform); void removeFromDirtyList(Gu::PrunerHandle handle); bool processDirtyList(PxU32 index, const Adapter& adapter, float inflation); // void growDirtyList(Gu::PrunerHandle handle); PX_FORCE_INLINE Gu::Pruner* pruner() { return mPruner; } PX_FORCE_INLINE const Gu::Pruner* pruner() const { return mPruner; } Gu::Pruner* mPruner; PxBitMap mDirtyMap; PxArray<Gu::PrunerHandle> mDirtyList; bool mDirtyStatic; // true if dirty list contains a static PX_NOCOPY(PrunerExt) friend class PrunerManager; }; } } #include "foundation/PxHashSet.h" namespace physx { namespace Sq { class CompoundPruner; typedef PxPair<PrunerCompoundId, Gu::PrunerHandle> CompoundPair; typedef PxCoalescedHashSet<CompoundPair > CompoundPrunerSet; // AB: extended compound pruner structure, buffers compound shape changes and flushes them. struct CompoundPrunerExt : public PxUserAllocated { // private: CompoundPrunerExt(); ~CompoundPrunerExt(); void flushMemory(); void preallocate(PxU32 nbShapes); void flushShapes(const Adapter& adapter, float inflation); void addToDirtyList(PrunerCompoundId compoundId, Gu::PrunerHandle handle, const PxTransform& transform); void removeFromDirtyList(PrunerCompoundId compoundId, Gu::PrunerHandle handle); PX_FORCE_INLINE const CompoundPruner* pruner() const { return mPruner; } PX_FORCE_INLINE CompoundPruner* pruner() { return mPruner; } CompoundPruner* mPruner; CompoundPrunerSet mDirtyList; PX_NOCOPY(CompoundPrunerExt) friend class PrunerManager; }; } } #include "foundation/PxMutex.h" #include "SqPrunerData.h" namespace physx { class PxRenderOutput; class PxBVH; class PxSceneLimits; // PT: TODO: decouple from PxSceneLimits namespace Sq { class PrunerManager : public PxUserAllocated { public: PrunerManager(PxU64 contextID, Gu::Pruner* staticPruner, Gu::Pruner* dynamicPruner, PxU32 dynamicTreeRebuildRateHint, float inflation, const PxSceneLimits& limits, const Adapter& adapter); ~PrunerManager(); PrunerData addPrunerShape(const Gu::PrunerPayload& payload, bool dynamic, PrunerCompoundId compoundId, const PxBounds3& bounds, const PxTransform& transform, bool hasPruningStructure=false); void addCompoundShape(const PxBVH& bvh, PrunerCompoundId compoundId, const PxTransform& compoundTransform, PrunerData* prunerData, const Gu::PrunerPayload* payloads, const PxTransform* transforms, bool isDynamic); void markForUpdate(PrunerCompoundId compoundId, PrunerData s, const PxTransform& transform); void removePrunerShape(PrunerCompoundId compoundId, PrunerData shapeData, Gu::PrunerPayloadRemovalCallback* removalCallback); PX_FORCE_INLINE const Gu::Pruner* getPruner(PruningIndex::Enum index) const { return mPrunerExt[index].mPruner; } PX_FORCE_INLINE Gu::Pruner* getPruner(PruningIndex::Enum index) { return mPrunerExt[index].mPruner; } PX_FORCE_INLINE const CompoundPruner* getCompoundPruner() const { return mCompoundPrunerExt.mPruner; } PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; } void preallocate(PxU32 prunerIndex, PxU32 nbShapes); void setDynamicTreeRebuildRateHint(PxU32 dynTreeRebuildRateHint); PX_FORCE_INLINE PxU32 getDynamicTreeRebuildRateHint() const { return mRebuildRateHint; } void flushUpdates(); void forceRebuildDynamicTree(PxU32 prunerIndex); void updateCompoundActor(PrunerCompoundId compoundId, const PxTransform& compoundTransform); void removeCompoundActor(PrunerCompoundId compoundId, Gu::PrunerPayloadRemovalCallback* removalCallback); void* prepareSceneQueriesUpdate(PruningIndex::Enum index); void sceneQueryBuildStep(void* handle); void sync(const Gu::PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices); void afterSync(bool buildStep, bool commit); void shiftOrigin(const PxVec3& shift); void visualize(PxU32 prunerIndex, PxRenderOutput& out) const; void flushMemory(); PX_FORCE_INLINE PxU32 getStaticTimestamp() const { return mStaticTimestamp; } PX_FORCE_INLINE const Adapter& getAdapter() const { return mAdapter; } private: const Adapter& mAdapter; PrunerExt mPrunerExt[PruningIndex::eCOUNT]; CompoundPrunerExt mCompoundPrunerExt; const PxU64 mContextID; PxU32 mStaticTimestamp; PxU32 mRebuildRateHint; const float mInflation; // SQ_PRUNER_EPSILON PxMutex mSQLock; // to make sure only one query updates the dirty pruner structure if multiple queries run in parallel volatile bool mPrunerNeedsUpdating; void flushShapes(); PX_FORCE_INLINE void invalidateStaticTimestamp() { mStaticTimestamp++; } PX_NOCOPY(PrunerManager) }; } } #endif
8,173
C
40.282828
225
0.716628
NVIDIA-Omniverse/PhysX/physx/source/scenequery/include/SqFactory.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_FACTORY_H #define SQ_FACTORY_H #include "foundation/PxSimpleTypes.h" #include "GuFactory.h" #include "SqTypedef.h" namespace physx { namespace Sq { class CompoundPruner; CompoundPruner* createCompoundPruner(PxU64 contextID); } } #endif
1,951
C
40.531914
74
0.766274
NVIDIA-Omniverse/PhysX/physx/source/scenequery/include/SqTypedef.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SQ_TYPEDEF_H #define SQ_TYPEDEF_H #include "foundation/PxSimpleTypes.h" #include "GuPrunerTypedef.h" namespace physx { namespace Sq { typedef PxU32 PrunerCompoundId; static const PrunerCompoundId INVALID_COMPOUND_ID = 0xffffffff; typedef PxU32 PrunerData; #define SQ_INVALID_PRUNER_DATA 0xffffffff } } #endif
2,023
C
41.166666
74
0.769155
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScParticleSystemSim.h" #include "ScParticleSystemCore.h" #include "ScScene.h" using namespace physx; using namespace physx::Dy; Sc::ParticleSystemSim::ParticleSystemSim(ParticleSystemCore& core, Scene& scene) : ActorSim(scene, core), mShapeSim(*this, &core.getShapeCore()) { mLLParticleSystem = scene.createLLParticleSystem(this); mNodeIndex = scene.getSimpleIslandManager()->addParticleSystem(mLLParticleSystem, false); scene.getSimpleIslandManager()->activateNode(mNodeIndex); //mCore.setSim(this); mLLParticleSystem->setElementId(mShapeSim.getElementID()); PxParticleSystemGeometry geometry; geometry.mSolverType = core.getSolverType(); core.getShapeCore().setGeometry(geometry); PxsShapeCore* shapeCore = const_cast<PxsShapeCore*>(&core.getShapeCore().getCore()); mLLParticleSystem->setShapeCore(shapeCore); } Sc::ParticleSystemSim::~ParticleSystemSim() { if (!mLLParticleSystem) return; mScene.destroyLLParticleSystem(*mLLParticleSystem); mScene.getSimpleIslandManager()->removeNode(mNodeIndex); mCore.setSim(NULL); } void Sc::ParticleSystemSim::updateBounds() { mShapeSim.updateBounds(); } void Sc::ParticleSystemSim::updateBoundsInAABBMgr() { mShapeSim.updateBoundsInAABBMgr(); } PxBounds3 Sc::ParticleSystemSim::getBounds() const { return mShapeSim.getBounds(); } bool Sc::ParticleSystemSim::isSleeping() const { return false; } void Sc::ParticleSystemSim::sleepCheck(PxReal dt) { PX_UNUSED(dt); } /*void Sc::ParticleSystemSim::activate() { activateInteractions(*this); } void Sc::ParticleSystemSim::deactivate() { deactivateInteractions(*this); }*/ #endif //PX_SUPPORT_GPU_PHYSX
3,278
C++
28.276785
90
0.769677
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimulationController.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SIMULATION_CONTROLLER_H #define SC_SIMULATION_CONTROLLER_H #include "PxsSimulationController.h" namespace physx { namespace Sc { class SimulationController : public PxsSimulationController { PX_NOCOPY(SimulationController) public: SimulationController(PxsSimulationControllerCallback* callback) : PxsSimulationController(callback, PxIntFalse) {} virtual ~SimulationController() {} virtual void updateScBodyAndShapeSim(PxsTransformCache& cache, Bp::BoundsArray& boundArray, PxBaseTask* continuation) PX_OVERRIDE; virtual void updateArticulationAfterIntegration(PxsContext* llContext, Bp::AABBManagerBase* aabbManager, PxArray<Sc::BodySim*>& ccdBodies, PxBaseTask* continuation, IG::IslandSim& islandSim, float dt) PX_OVERRIDE; }; } } #endif
2,511
C
44.672726
132
0.765432
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimStats.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SIM_STATS_H #define SC_SIM_STATS_H #include "geometry/PxGeometry.h" #include "PxSimulationStatistics.h" #include "foundation/PxAtomic.h" #include "foundation/PxUserAllocated.h" namespace physx { struct PxvSimStats; namespace Sc { /* Description: contains statistics for the scene. */ class SimStats : public PxUserAllocated { public: SimStats(); void clear(); //set counters to zero void simStart(); void readOut(PxSimulationStatistics& dest, const PxvSimStats& simStats) const; PX_INLINE void incBroadphaseAdds() { numBroadPhaseAddsPending++; } PX_INLINE void incBroadphaseRemoves() { numBroadPhaseRemovesPending++; } private: // Broadphase adds/removes for the current simulation step PxU32 numBroadPhaseAdds; PxU32 numBroadPhaseRemoves; // Broadphase adds/removes for the next simulation step PxU32 numBroadPhaseAddsPending; PxU32 numBroadPhaseRemovesPending; public: typedef PxI32 TriggerPairCountsNonVolatile[PxGeometryType::eCONVEXMESH+1][PxGeometryType::eGEOMETRY_COUNT]; typedef volatile TriggerPairCountsNonVolatile TriggerPairCounts; TriggerPairCounts numTriggerPairs; PxU64 gpuMemSizeParticles; PxU64 gpuMemSizeSoftBodies; PxU64 gpuMemSizeFEMCloths; PxU64 gpuMemSizeHairSystems; }; } // namespace Sc } #endif
3,006
C
31.684782
109
0.768796
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScTriggerInteraction.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_TRIGGER_INTERACTION_H #define SC_TRIGGER_INTERACTION_H #include "ScElementSimInteraction.h" #include "ScShapeSim.h" #include "GuOverlapTests.h" namespace physx { namespace Sc { class TriggerInteraction : public ElementSimInteraction { public: enum TriggerFlag { PAIR_FLAGS_MASK = ((PxPairFlag::eNOTIFY_TOUCH_LOST << 1) - 1), // Bits where the PxPairFlags eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST get stored NEXT_FREE = ((PAIR_FLAGS_MASK << 1) & ~PAIR_FLAGS_MASK), PROCESS_THIS_FRAME = (NEXT_FREE << 0), // the trigger pair is new or the pose of an actor was set -> initial processing required. // This is important to cover cases where a static or kinematic // (non-moving) trigger is created and overlaps with a sleeping // object. Or for the case where a static/kinematic is teleported to a new // location. TOUCH_FOUND should still get sent in that case. LAST = (NEXT_FREE << 1) }; TriggerInteraction(ShapeSimBase& triggerShape, ShapeSimBase& otherShape); ~TriggerInteraction(); PX_FORCE_INLINE Gu::TriggerCache& getTriggerCache() { return mTriggerCache; } PX_FORCE_INLINE ShapeSimBase& getTriggerShape() const { return static_cast<ShapeSimBase&>(getElement0()); } PX_FORCE_INLINE ShapeSimBase& getOtherShape() const { return static_cast<ShapeSimBase&>(getElement1()); } PX_FORCE_INLINE bool lastFrameHadContacts() const { return mLastFrameHadContacts; } PX_FORCE_INLINE void updateLastFrameHadContacts(bool hasContact) { mLastFrameHadContacts = hasContact; } PX_FORCE_INLINE PxPairFlags getTriggerFlags() const { return PxPairFlags(mFlags & PAIR_FLAGS_MASK); } PX_FORCE_INLINE void setTriggerFlags(PxPairFlags triggerFlags); PX_FORCE_INLINE void raiseFlag(TriggerFlag flag) { mFlags |= flag; } PX_FORCE_INLINE void clearFlag(TriggerFlag flag) { mFlags &= ~flag; } PX_FORCE_INLINE PxIntBool readFlag(TriggerFlag flag) const { return PxIntBool(mFlags & flag); } PX_FORCE_INLINE void forceProcessingThisFrame(Sc::Scene& scene); bool onActivate(void*); bool onDeactivate(); protected: Gu::TriggerCache mTriggerCache; bool mLastFrameHadContacts; }; } // namespace Sc PX_FORCE_INLINE void Sc::TriggerInteraction::setTriggerFlags(PxPairFlags triggerFlags) { PX_ASSERT(PxU32(triggerFlags) < (PxPairFlag::eDETECT_CCD_CONTACT << 1)); // to find out if a new PxPairFlag has been added in which case PAIR_FLAGS_MASK needs to get adjusted #if PX_CHECKED if (triggerFlags & PxPairFlag::eNOTIFY_TOUCH_PERSISTS) { PX_WARN_ONCE("Trigger pairs do not support PxPairFlag::eNOTIFY_TOUCH_PERSISTS events any longer."); } #endif PxU32 newFlags = mFlags; PxU32 fl = PxU32(triggerFlags) & PxU32(PxPairFlag::eNOTIFY_TOUCH_FOUND|PxPairFlag::eNOTIFY_TOUCH_LOST); newFlags &= (~PAIR_FLAGS_MASK); // clear old flags newFlags |= fl; mFlags = newFlags; } PX_FORCE_INLINE void Sc::TriggerInteraction::forceProcessingThisFrame(Sc::Scene& scene) { raiseFlag(PROCESS_THIS_FRAME); if (!readInteractionFlag(InteractionFlag::eIS_ACTIVE)) { raiseInteractionFlag(InteractionFlag::eIS_ACTIVE); scene.notifyInteractionActivated(this); } } } #endif
5,019
C
41.184874
176
0.725842
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScBodySim.h" #include "ScStaticSim.h" #include "ScConstraintCore.h" #include "ScConstraintSim.h" #include "ScConstraintInteraction.h" #include "ScElementSimInteraction.h" using namespace physx; using namespace Sc; static ConstraintInteraction* createInteraction(ConstraintSim* sim, RigidCore* r0, RigidCore* r1, Scene& scene) { return scene.getConstraintInteractionPool()->construct( sim, r0 ? *r0->getSim() : scene.getStaticAnchor(), r1 ? *r1->getSim() : scene.getStaticAnchor()); } static void releaseInteraction(ConstraintInteraction* interaction, const ConstraintSim* sim, Scene& scene) { if(!sim->isBroken()) interaction->destroy(); scene.getConstraintInteractionPool()->destroy(interaction); } Sc::ConstraintSim::ConstraintSim(ConstraintCore& core, RigidCore* r0, RigidCore* r1, Scene& scene) : mScene (scene), mCore (core), mInteraction(NULL), mFlags (0) { mBodies[0] = (r0 && (r0->getActorCoreType() != PxActorType::eRIGID_STATIC)) ? static_cast<BodySim*>(r0->getSim()) : 0; mBodies[1] = (r1 && (r1->getActorCoreType() != PxActorType::eRIGID_STATIC)) ? static_cast<BodySim*>(r1->getSim()) : 0; const PxU32 id = scene.getConstraintIDTracker().createID(); mLowLevelConstraint.index = id; PxPinnedArray<Dy::ConstraintWriteback>& writeBackPool = scene.getDynamicsContext()->getConstraintWriteBackPool(); if(id >= writeBackPool.capacity()) writeBackPool.reserve(writeBackPool.capacity() * 2); writeBackPool.resize(PxMax(writeBackPool.size(), id + 1)); writeBackPool[id].initialize(); if(!createLLConstraint()) return; PxReal linBreakForce, angBreakForce; core.getBreakForce(linBreakForce, angBreakForce); if ((linBreakForce < PX_MAX_F32) || (angBreakForce < PX_MAX_F32)) setFlag(eBREAKABLE); core.setSim(this); mInteraction = createInteraction(this, r0, r1, scene); PX_ASSERT(!mInteraction->isRegistered()); // constraint interactions must not register in the scene, there is a list of Sc::ConstraintSim instead } Sc::ConstraintSim::~ConstraintSim() { PX_ASSERT(mInteraction); // This is fine now, a body which gets removed from the scene removes all constraints automatically PX_ASSERT(!mInteraction->isRegistered()); // constraint interactions must not register in the scene, there is a list of Sc::ConstraintSim instead releaseInteraction(mInteraction, this, mScene); mScene.getConstraintIDTracker().releaseID(mLowLevelConstraint.index); destroyLLConstraint(); mCore.setSim(NULL); } static PX_FORCE_INLINE void setLLBodies(Dy::Constraint& c, BodySim* b0, BodySim* b1) { PxsRigidBody* body0 = b0 ? &b0->getLowLevelBody() : NULL; PxsRigidBody* body1 = b1 ? &b1->getLowLevelBody() : NULL; c.body0 = body0; c.body1 = body1; c.bodyCore0 = body0 ? &body0->getCore() : NULL; c.bodyCore1 = body1 ? &body1->getCore() : NULL; } bool Sc::ConstraintSim::createLLConstraint() { ConstraintCore& core = getCore(); const PxU32 constantBlockSize = core.getConstantBlockSize(); void* constantBlock = mScene.allocateConstraintBlock(constantBlockSize); if(!constantBlock) return PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Constraint: could not allocate low-level resources."); //Ensure the constant block isn't just random data because some functions may attempt to use it before it is //setup. Specifically pvd visualization of joints //-CN PxMemZero(constantBlock, constantBlockSize); Dy::Constraint& llc = mLowLevelConstraint; core.getBreakForce(llc.linBreakForce, llc.angBreakForce); llc.flags = core.getFlags(); llc.constantBlockSize = PxU16(constantBlockSize); llc.solverPrep = core.getSolverPrep(); llc.constantBlock = constantBlock; llc.minResponseThreshold = core.getMinResponseThreshold(); //llc.index = mLowLevelConstraint.index; setLLBodies(llc, mBodies[0], mBodies[1]); return true; } void Sc::ConstraintSim::destroyLLConstraint() { if(mLowLevelConstraint.constantBlock) mScene.deallocateConstraintBlock(mLowLevelConstraint.constantBlock, mLowLevelConstraint.constantBlockSize); } void Sc::ConstraintSim::setBodies(RigidCore* r0, RigidCore* r1) { PX_ASSERT(mInteraction); releaseInteraction(mInteraction, this, mScene); BodySim* b0 = (r0 && (r0->getActorCoreType() != PxActorType::eRIGID_STATIC)) ? static_cast<BodySim*>(r0->getSim()) : 0; BodySim* b1 = (r1 && (r1->getActorCoreType() != PxActorType::eRIGID_STATIC)) ? static_cast<BodySim*>(r1->getSim()) : 0; setLLBodies(mLowLevelConstraint, b0, b1); mBodies[0] = b0; mBodies[1] = b1; mInteraction = createInteraction(this, r0, r1, mScene); } void Sc::ConstraintSim::getForce(PxVec3& lin, PxVec3& ang) { const PxReal recipDt = mScene.getOneOverDt(); Dy::ConstraintWriteback& solverOutput= mScene.getDynamicsContext()->getConstraintWriteBackPool()[mLowLevelConstraint.index]; lin = solverOutput.linearImpulse * recipDt; ang = solverOutput.angularImpulse * recipDt; } void Sc::ConstraintSim::setBreakForceLL(PxReal linear, PxReal angular) { PxU8 wasBreakable = readFlag(eBREAKABLE); PxU8 isBreakable; if ((linear < PX_MAX_F32) || (angular < PX_MAX_F32)) isBreakable = eBREAKABLE; else isBreakable = 0; if (isBreakable != wasBreakable) { if (isBreakable) { PX_ASSERT(!readFlag(eCHECK_MAX_FORCE_EXCEEDED)); setFlag(eBREAKABLE); if (mInteraction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)) mScene.addActiveBreakableConstraint(this, mInteraction); } else { if (readFlag(eCHECK_MAX_FORCE_EXCEEDED)) mScene.removeActiveBreakableConstraint(this); clearFlag(eBREAKABLE); } } mLowLevelConstraint.linBreakForce = linear; mLowLevelConstraint.angBreakForce = angular; } void Sc::ConstraintSim::postFlagChange(PxConstraintFlags /*oldFlags*/, PxConstraintFlags newFlags) { mLowLevelConstraint.flags = newFlags; }
7,497
C++
35.048077
147
0.749366
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef PX_PHYSICS_FEMCLOTH_SIM #define PX_PHYSICS_FEMCLOTH_SIM #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxUserAllocated.h" #include "DyFEMCloth.h" #include "ScFEMClothCore.h" #include "ScFEMClothShapeSim.h" #include "ScActorSim.h" // to be deleted namespace physx { namespace Sc { class Scene; class FEMClothSim : public ActorSim { PX_NOCOPY(FEMClothSim) public: FEMClothSim(FEMClothCore& core, Scene& scene); ~FEMClothSim(); PX_INLINE Dy::FEMCloth* getLowLevelFEMCloth() const { return mLLFEMCloth; } PX_INLINE FEMClothCore& getCore() const { return static_cast<FEMClothCore&>(mCore); } virtual PxActor* getPxActor() const { return getCore().getPxActor(); } void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; bool isSleeping() const; PX_FORCE_INLINE bool isActive() const { return !isSleeping(); } void setActive(bool active, bool asPartOfCreation=false); void onSetWakeCounter(); void attachShapeCore(ShapeCore* core); FEMClothShapeSim& getShapeSim() { return mShapeSim; } private: Dy::FEMCloth* mLLFEMCloth; FEMClothShapeSim mShapeSim; PxU32 mIslandNodeIndex; void activate(); void deactivate(); }; } // namespace Sc } #endif #endif
2,955
C
33.77647
89
0.723858
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemShapeSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScParticleSystemShapeSim.h" #include "ScNPhaseCore.h" #include "ScParticleSystemSim.h" #include "PxsContext.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::ParticleSystemShapeSim::ParticleSystemShapeSim(ParticleSystemSim& particleSim, const ParticleSystemShapeCore* core) : ShapeSimBase(particleSim, core) { mLLShape.mBodySimIndex_GPU = PxNodeIndex(PX_INVALID_NODE); mLLShape.mElementIndex_GPU = PX_INVALID_U32; createLowLevelVolume(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::ParticleSystemShapeSim::~ParticleSystemShapeSim() { if (isInBroadPhase()) destroyLowLevelVolume(); PX_ASSERT(!isInBroadPhase()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::ParticleSystemShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const { filterAttr = 0; setFilterObjectAttributeType(filterAttr, PxFilterObjectType::ePARTICLESYSTEM); filterData = getBodySim().getCore().getShapeCore().getSimulationFilterData(); } void Sc::ParticleSystemShapeSim::updateBounds() { Scene& scene = getScene(); PxBounds3 worldBounds = PxBounds3(PxVec3(0.f), PxVec3(0.f)); const PxReal contactOffset = getBodySim().getCore().getContactOffset(); worldBounds.fattenSafe(contactOffset); // fatten for fast moving colliders scene.getBoundsArray().setBounds(worldBounds, getElementID()); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::ParticleSystemShapeSim::updateBoundsInAABBMgr() { //we are updating the bound in GPU so we just need to set the actor handle in CPU to make sure //the GPU BP will process the particles if (!(static_cast<Sc::ParticleSystemSim&>(getActor()).getCore().getFlags() & PxParticleFlag::eDISABLE_RIGID_COLLISION)) { Scene& scene = getScene(); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); scene.getAABBManager()->setGPUStateChanged(); } } PxBounds3 Sc::ParticleSystemShapeSim::getBounds() const { PxBounds3 bounds = getScene().getBoundsArray().getBounds(getElementID()); return bounds; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::ParticleSystemShapeSim::createLowLevelVolume() { //PX_ASSERT(getWorldBounds().isFinite()); const PxU32 index = getElementID(); if (!(static_cast<Sc::ParticleSystemSim&>(getActor()).getCore().getFlags() & PxParticleFlag::eDISABLE_RIGID_COLLISION)) { getScene().getBoundsArray().setBounds(PxBounds3(PxVec3(PX_MAX_BOUNDS_EXTENTS), PxVec3(-PX_MAX_BOUNDS_EXTENTS)), index); mInBroadPhase = true; } else getScene().getAABBManager()->reserveSpaceForBounds(index); { const PxU32 group = Bp::FilterGroup::eDYNAMICS_BASE + getActor().getActorID(); const PxU32 type = Bp::FilterType::PARTICLESYSTEM; const PxReal contactOffset = getBodySim().getCore().getContactOffset(); addToAABBMgr(contactOffset, Bp::FilterGroup::Enum((group << BP_FILTERING_TYPE_SHIFT_BIT) | type), Bp::ElementType::eSHAPE); } // PT: TODO: what's the difference between "getContactOffset()" and "getBodySim().getCore().getContactOffset()" above? getScene().updateContactDistance(index, getContactOffset()); PxsTransformCache& cache = getScene().getLowLevelContext()->getTransformCache(); cache.initEntry(index); PxTransform idt(PxIdentity); cache.setTransformCache(idt, 0, index); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::ParticleSystemShapeSim::destroyLowLevelVolume() { if (!isInBroadPhase()) return; Sc::Scene& scene = getScene(); PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs(); scene.getNPhaseCore()->onVolumeRemoved(this, 0, outputs); removeFromAABBMgr(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::ParticleSystemSim& Sc::ParticleSystemShapeSim::getBodySim() const { return static_cast<ParticleSystemSim&>(getActor()); } #endif //PX_SUPPORT_GPU_PHYSX
6,690
C++
41.891025
199
0.606577
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemShapeCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SC_PARTICLESYSTEM_SHAPECORE_H #define SC_PARTICLESYSTEM_SHAPECORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxUserAllocated.h" #include "PxvGeometry.h" #include "foundation/PxUtilities.h" #include "PxFiltering.h" #include "PxShape.h" #include "ScShapeCore.h" #include "DyParticleSystemCore.h" #include "common/PxRenderOutput.h" namespace physx { namespace Sc { class Scene; class ParticleSystemCore; class ParticleSystemSim; class ParticleSystemShapeCore : public Sc::ShapeCore { public: // PX_SERIALIZATION ParticleSystemShapeCore(const PxEMPTY); //~PX_SERIALIZATION ParticleSystemShapeCore(); ~ParticleSystemShapeCore(); PX_FORCE_INLINE const Dy::ParticleSystemCore& getLLCore() const { return mLLCore; } PX_FORCE_INLINE Dy::ParticleSystemCore& getLLCore() { return mLLCore; } void initializeLLCoreData( PxU32 maxNeighborhood); void addParticleBuffer(PxParticleBuffer* particleBuffer); void removeParticleBuffer(PxParticleBuffer* particleBuffer); PxU64 getGpuMemStat() { return mGpuMemStat; } protected: Dy::ParticleSystemCore mLLCore; PxU64 mGpuMemStat; }; } // namespace Sc } #endif #endif
2,787
C
33.85
86
0.762827
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementSimInteraction.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ELEMENT_SIM_INTERACTION_H #define SC_ELEMENT_SIM_INTERACTION_H #include "ScInteraction.h" #include "ScElementSim.h" namespace physx { namespace Sc { class ElementSimInteraction : public Interaction { public: PX_FORCE_INLINE ElementSim& getElement0() const { return mElement0; } PX_FORCE_INLINE ElementSim& getElement1() const { return mElement1; } protected: PX_INLINE ElementSimInteraction(ElementSim& element0, ElementSim& element1, InteractionType::Enum type, PxU8 flags); ~ElementSimInteraction() {} ElementSimInteraction& operator=(const ElementSimInteraction&); ElementSim& mElement0; ElementSim& mElement1; PxU32 mFlags; // PT: moved there in padding bytes, from ShapeInteraction }; } // namespace Sc ////////////////////////////////////////////////////////////////////////// PX_INLINE Sc::ElementSimInteraction::ElementSimInteraction(ElementSim& element0, ElementSim& element1, InteractionType::Enum type, PxU8 flags) : Interaction (element0.getActor(), element1.getActor(), type, flags), mElement0 (element0), mElement1 (element1) { } } #endif
2,845
C
39.084506
144
0.732162
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_CONSTRAINT_SIM_H #define SC_CONSTRAINT_SIM_H #include "foundation/PxArray.h" #include "PxSimulationEventCallback.h" #include "DyConstraint.h" namespace physx { namespace Sc { class Scene; class ConstraintInteraction; class ConstraintCore; class RigidCore; class BodySim; class RigidSim; class ConstraintSim : public PxUserAllocated { PX_NOCOPY(ConstraintSim) public: enum Enum { eBREAKABLE = (1<<1), // The constraint can break eCHECK_MAX_FORCE_EXCEEDED = (1<<2), // This constraint will get tested for breakage at the end of the sim step eBROKEN = (1<<3) }; ConstraintSim(ConstraintCore& core, RigidCore* r0, RigidCore* r1, Scene& scene); ~ConstraintSim(); void setBodies(RigidCore* r0, RigidCore* r1); void setBreakForceLL(PxReal linear, PxReal angular); PX_FORCE_INLINE void setMinResponseThresholdLL(PxReal threshold) { mLowLevelConstraint.minResponseThreshold = threshold; } PX_FORCE_INLINE const void* getConstantsLL() const { return mLowLevelConstraint.constantBlock; } void postFlagChange(PxConstraintFlags oldFlags, PxConstraintFlags newFlags); PX_FORCE_INLINE const Dy::Constraint& getLowLevelConstraint() const { return mLowLevelConstraint; } PX_FORCE_INLINE Dy::Constraint& getLowLevelConstraint() { return mLowLevelConstraint; } PX_FORCE_INLINE ConstraintCore& getCore() const { return mCore; } PX_FORCE_INLINE BodySim* getBody(PxU32 i) const // for static actors or world attached constraints NULL is returned { return mBodies[i]; } void getForce(PxVec3& force, PxVec3& torque); PX_FORCE_INLINE PxU8 readFlag(PxU8 flag) const { return PxU8(mFlags & flag); } PX_FORCE_INLINE void setFlag(PxU8 flag) { mFlags |= flag; } PX_FORCE_INLINE void clearFlag(PxU8 flag) { mFlags &= ~flag; } PX_FORCE_INLINE PxU32 isBroken() const { return PxU32(mFlags) & ConstraintSim::eBROKEN; } PX_FORCE_INLINE const ConstraintInteraction* getInteraction() const { return mInteraction; } private: bool createLLConstraint(); void destroyLLConstraint(); Dy::Constraint mLowLevelConstraint; Scene& mScene; ConstraintCore& mCore; ConstraintInteraction* mInteraction; // PT: why do we have an interaction object here? BodySim* mBodies[2]; PxU8 mFlags; }; } // namespace Sc } #endif
4,205
C
40.643564
128
0.713912
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementSim.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 "ScElementSim.h" #include "ScElementSimInteraction.h" #include "ScSimStats.h" using namespace physx; using namespace Sc; static PX_FORCE_INLINE bool interactionHasElement(const Interaction* it, const ElementSim* elem) { if(it->readInteractionFlag(InteractionFlag::eRB_ELEMENT)) { PX_ASSERT( (it->getType() == InteractionType::eMARKER) || (it->getType() == InteractionType::eOVERLAP) || (it->getType() == InteractionType::eTRIGGER) ); const ElementSimInteraction* ei = static_cast<const ElementSimInteraction*>(it); if((&ei->getElement0() == elem) || (&ei->getElement1() == elem)) return true; } return false; } Sc::ElementSimInteraction* Sc::ElementSim::ElementInteractionIterator::getNext() { while(mInteractions!=mInteractionsLast) { Interaction* it = *mInteractions++; if(interactionHasElement(it, mElement)) return static_cast<ElementSimInteraction*>(it); } return NULL; } Sc::ElementSimInteraction* Sc::ElementSim::ElementInteractionReverseIterator::getNext() { while(mInteractions!=mInteractionsLast) { Interaction* it = *--mInteractionsLast; if(interactionHasElement(it, mElement)) return static_cast<ElementSimInteraction*>(it); } return NULL; } namespace { class ElemSimPtrTableStorageManager : public Cm::PtrTableStorageManager, public PxUserAllocated { PX_NOCOPY(ElemSimPtrTableStorageManager) public: ElemSimPtrTableStorageManager() {} ~ElemSimPtrTableStorageManager() {} // PtrTableStorageManager virtual void** allocate(PxU32 capacity) PX_OVERRIDE { return PX_ALLOCATE(void*, capacity, "CmPtrTable pointer array"); } virtual void deallocate(void** addr, PxU32 /*capacity*/) PX_OVERRIDE { PX_FREE(addr); } virtual bool canReuse(PxU32 /*originalCapacity*/, PxU32 /*newCapacity*/) PX_OVERRIDE { return false; } //~PtrTableStorageManager }; ElemSimPtrTableStorageManager gElemSimTableStorageManager; } static PX_FORCE_INLINE void onElementAttach(ElementSim& element, ShapeManager& manager) { PX_ASSERT(element.mShapeArrayIndex == 0xffffffff); element.mShapeArrayIndex = manager.mShapes.getCount(); manager.mShapes.add(&element, gElemSimTableStorageManager); } void Sc::ShapeManager::onElementDetach(ElementSim& element) { const PxU32 index = element.mShapeArrayIndex; PX_ASSERT(index != 0xffffffff); PX_ASSERT(mShapes.getCount()); void** ptrs = mShapes.getPtrs(); PX_ASSERT(reinterpret_cast<ElementSim*>(ptrs[index]) == &element); const PxU32 last = mShapes.getCount() - 1; if (index != last) { ElementSim* moved = reinterpret_cast<ElementSim*>(ptrs[last]); PX_ASSERT(moved->mShapeArrayIndex == last); moved->mShapeArrayIndex = index; } mShapes.replaceWithLast(index, gElemSimTableStorageManager); element.mShapeArrayIndex = 0xffffffff; } Sc::ElementSim::ElementSim(ActorSim& actor) : mActor (actor), mInBroadPhase (false), mShapeArrayIndex(0xffffffff) { initID(); onElementAttach(*this, actor); } Sc::ElementSim::~ElementSim() { PX_ASSERT(!mInBroadPhase); releaseID(); mActor.onElementDetach(*this); } void Sc::ElementSim::addToAABBMgr(PxReal contactDistance, Bp::FilterGroup::Enum group, Bp::ElementType::Enum type) { Sc::Scene& scene = getScene(); if(!scene.getAABBManager()->addBounds(mElementID, contactDistance, group, this, mActor.getActorCore().getAggregateID(), type)) return; mInBroadPhase = true; #if PX_ENABLE_SIM_STATS scene.getStatsInternal().incBroadphaseAdds(); #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif } bool Sc::ElementSim::removeFromAABBMgr() { PX_ASSERT(mInBroadPhase); Sc::Scene& scene = getScene(); bool res = scene.getAABBManager()->removeBounds(mElementID); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndReset(mElementID); mInBroadPhase = false; #if PX_ENABLE_SIM_STATS scene.getStatsInternal().incBroadphaseRemoves(); #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif return res; }
5,601
C++
31.011428
127
0.752544
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScNPhaseCore.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 "ScNPhaseCore.h" #include "ScShapeInteraction.h" #include "ScTriggerInteraction.h" #include "ScElementInteractionMarker.h" #include "ScConstraintInteraction.h" #include "ScSimStats.h" using namespace physx; using namespace Sc; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// NPhaseCore::NPhaseCore(Scene& scene, const PxSceneDesc& sceneDesc) : mOwnerScene (scene), mContactReportActorPairSet ("contactReportPairSet"), mPersistentContactEventPairList ("persistentContactEventPairs"), mNextFramePersistentContactEventPairIndex (0), mForceThresholdContactEventPairList ("forceThresholdContactEventPairs"), mContactReportBuffer (sceneDesc.contactReportStreamBufferSize, (sceneDesc.flags & PxSceneFlag::eDISABLE_CONTACT_REPORT_BUFFER_RESIZE)), mActorPairPool ("actorPairPool"), mActorPairReportPool ("actorPairReportPool"), mShapeInteractionPool (PxAllocatorTraits<ShapeInteraction>::Type("shapeInteractionPool"), 4096), mTriggerInteractionPool ("triggerInteractionPool"), mActorPairContactReportDataPool ("actorPairContactReportPool"), mInteractionMarkerPool ("interactionMarkerPool"), mConcludeTriggerInteractionProcessingTask (scene.getContextId(), this, "ScNPhaseCore.concludeTriggerInteractionProcessing") { } NPhaseCore::~NPhaseCore() { // Clear pending actor pairs (waiting on contact report callback) clearContactReportActorPairs(false); } PxU32 NPhaseCore::getDefaultContactReportStreamBufferSize() const { return mContactReportBuffer.getDefaultBufferSize(); } ElementSimInteraction* NPhaseCore::findInteraction(const ElementSim* element0, const ElementSim* element1) { const PxHashMap<ElementSimKey, ElementSimInteraction*>::Entry* pair = mElementSimMap.find(ElementSimKey(element0->getElementID(), element1->getElementID())); return pair ? pair->second : NULL; } void NPhaseCore::registerInteraction(ElementSimInteraction* interaction) { mElementSimMap.insert(ElementSimKey(interaction->getElement0().getElementID(), interaction->getElement1().getElementID()), interaction); } void NPhaseCore::unregisterInteraction(ElementSimInteraction* interaction) { mElementSimMap.erase(ElementSimKey(interaction->getElement0().getElementID(), interaction->getElement1().getElementID())); } void NPhaseCore::onOverlapRemoved(ElementSim* volume0, ElementSim* volume1, PxU32 ccdPass, void* elemSim, PxsContactManagerOutputIterator& outputs) { ElementSim* elementHi = volume1; ElementSim* elementLo = volume0; // No actor internal interactions PX_ASSERT(&elementHi->getActor() != &elementLo->getActor()); // PT: TODO: get rid of 'findInteraction', cf US10491 ElementSimInteraction* interaction = elemSim ? reinterpret_cast<ElementSimInteraction*>(elemSim) : findInteraction(elementHi, elementLo); // MS: The check below is necessary since at the moment LowLevel broadphase still tracks // killed pairs and hence reports lost overlaps if(interaction) { PxU32 flags = PxU32(PairReleaseFlag::eWAKE_ON_LOST_TOUCH); PX_ASSERT(interaction->isElementInteraction()); releaseElementPair(static_cast<ElementSimInteraction*>(interaction), flags, NULL, ccdPass, true, outputs); } } // MS: TODO: optimize this for the actor release case? void NPhaseCore::onVolumeRemoved(ElementSim* volume, PxU32 flags, PxsContactManagerOutputIterator& outputs) { const PxU32 ccdPass = 0; flags |= PairReleaseFlag::eRUN_LOST_TOUCH_LOGIC; // Release interactions // IMPORTANT: Iterate from the back of the list to the front as we release interactions which // triggers a replace with last ElementSim::ElementInteractionReverseIterator iter = volume->getElemInteractionsReverse(); ElementSimInteraction* interaction = iter.getNext(); while(interaction) { PX_ASSERT( (interaction->getType() == InteractionType::eMARKER) || (interaction->getType() == InteractionType::eOVERLAP) || (interaction->getType() == InteractionType::eTRIGGER) ); releaseElementPair(interaction, flags, volume, ccdPass, true, outputs); interaction = iter.getNext(); } } ElementSimInteraction* NPhaseCore::createRbElementInteraction(const FilterInfo& finfo, ShapeSimBase& s0, ShapeSimBase& s1, PxsContactManager* contactManager, ShapeInteraction* shapeInteraction, ElementInteractionMarker* interactionMarker, bool isTriggerPair) { ElementSimInteraction* pair = NULL; if((finfo.filterFlags & PxFilterFlag::eSUPPRESS) == false) { if(!isTriggerPair) { PX_ASSERT(contactManager); PX_ASSERT(shapeInteraction); pair = createShapeInteraction(s0, s1, finfo.pairFlags, contactManager, shapeInteraction); } else { pair = createTriggerInteraction(s0, s1, finfo.pairFlags); } } else pair = createElementInteractionMarker(s0, s1, interactionMarker); if(finfo.hasPairID) { // Mark the pair as a filter callback pair pair->raiseInteractionFlag(InteractionFlag::eIS_FILTER_PAIR); } return pair; } void NPhaseCore::managerNewTouch(ShapeInteraction& interaction) { //(1) if the pair hasn't already been assigned, look it up! ActorPair* actorPair = interaction.getActorPair(); if(!actorPair) { ShapeSim& s0 = static_cast<ShapeSim&>(interaction.getElement0()); ShapeSim& s1 = static_cast<ShapeSim&>(interaction.getElement1()); actorPair = findActorPair(&s0, &s1, interaction.isReportPair()); actorPair->incRefCount(); //It's being referenced by a new pair... interaction.setActorPair(*actorPair); } } static bool shouldSwapBodies(const ShapeSimBase& s0, const ShapeSimBase& s1) { /* This tries to ensure that if one of the bodies is static or kinematic, it will be body B There is a further optimization to force all pairs that share the same bodies to have the same body ordering. This reduces the number of required partitions in the parallel solver. Sorting rules are: If bodyA is static, swap If bodyA is rigidDynamic and bodyB is articulation, swap If bodyA is in an earlier BP group than bodyB, swap */ // PT: some of these swaps are here to fulfill requirements from the solver code, and we // will get asserts and failures without them. Some others are only optimizations. // PT: generally speaking we want the "static" actor to be second in the pair. // "Static" can mean either: // - a proper static body // - a kinematic dynamic body // - an articulation link with a fixed base ActorSim& rs0 = s0.getActor(); const PxActorType::Enum actorType0 = rs0.getActorType(); if(actorType0 == PxActorType::eRIGID_STATIC) return true; ActorSim& rs1 = s1.getActor(); const PxActorType::Enum actorType1 = rs1.getActorType(); const bool isDyna0 = actorType0 == PxActorType::eRIGID_DYNAMIC; const bool isDyna1 = actorType1 == PxActorType::eRIGID_DYNAMIC; if(actorType0 == PxActorType::eARTICULATION_LINK) { if(isDyna1 || actorType1 == PxActorType::eARTICULATION_LINK) { if(static_cast<BodySim&>(rs0).getLowLevelBody().mCore->fixedBaseLink) return true; } } else if(isDyna0) { // PT: this tries to implement this requirement: "If bodyA is rigidDynamic and bodyB is articulation, swap" // But we do NOT do that if bodyB has a fixed base. It is unclear whether this particular swap is really needed. if(actorType1 == PxActorType::eARTICULATION_LINK) { if(!static_cast<BodySim&>(rs1).getLowLevelBody().mCore->fixedBaseLink) return true; } } // PT: initial code was: // if((actorType0 == PxActorType::eRIGID_DYNAMIC && actorType1 == PxActorType::eRIGID_DYNAMIC) && actorAKinematic) // But actorAKinematic true implies isDyna0 true, so this is equivalent to // if(isDyna1 && actorAKinematic) // And we only need actorAKinematic in this expression so it's faster to move its computation inside the if: // if(isDyna1 && isDyna0 && static_cast<BodySim&>(rs0).isKinematic()) if(isDyna1 && isDyna0 && static_cast<BodySim&>(rs0).isKinematic()) return true; // PT: initial code was: // if(actorType0 == actorType1 && rs0.getActorID() < rs1.getActorID() && !actorBKinematic) // We refactor the code a bit to avoid computing actorBKinematic. We could also test actorBKinematic // first and avoid reading actor IDs. Unclear what's best, arbitrary choice for now. if((actorType0 == actorType1) && (rs0.getActorID() < rs1.getActorID())) { const bool actorBKinematic = isDyna1 && static_cast<BodySim&>(rs1).isKinematic(); if(!actorBKinematic) return true; } #if PX_SUPPORT_GPU_PHYSX // PT: using rs0.isParticleSystem() instead of isParticleSystem(actorType0) is faster. if(actorType1 != PxActorType::eRIGID_STATIC && rs0.isParticleSystem()) return true; #endif return false; } ShapeInteraction* NPhaseCore::createShapeInteraction(ShapeSimBase& s0, ShapeSimBase& s1, PxPairFlags pairFlags, PxsContactManager* contactManager, ShapeInteraction* shapeInteraction) { ShapeSimBase* _s0 = &s0; ShapeSimBase* _s1 = &s1; if(shouldSwapBodies(s0, s1)) PxSwap(_s0, _s1); ShapeInteraction* si = shapeInteraction ? shapeInteraction : mShapeInteractionPool.allocate(); PX_PLACEMENT_NEW(si, ShapeInteraction)(*_s0, *_s1, pairFlags, contactManager); PX_ASSERT(si->mReportPairIndex == INVALID_REPORT_PAIR_ID); return si; } TriggerInteraction* NPhaseCore::createTriggerInteraction(ShapeSimBase& s0, ShapeSimBase& s1, PxPairFlags triggerFlags) { ShapeSimBase* triggerShape; ShapeSimBase* otherShape; if(s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE) { triggerShape = &s1; otherShape = &s0; } else { triggerShape = &s0; otherShape = &s1; } TriggerInteraction* pair = mTriggerInteractionPool.construct(*triggerShape, *otherShape); pair->setTriggerFlags(triggerFlags); return pair; } ElementInteractionMarker* NPhaseCore::createElementInteractionMarker(ElementSim& e0, ElementSim& e1, ElementInteractionMarker* interactionMarker) { ElementInteractionMarker* pair = interactionMarker ? interactionMarker : mInteractionMarkerPool.allocate(); PX_PLACEMENT_NEW(pair, ElementInteractionMarker)(e0, e1, interactionMarker != NULL); return pair; } ActorPair* NPhaseCore::findActorPair(ShapeSimBase* s0, ShapeSimBase* s1, PxIntBool isReportPair) { PX_ASSERT(!(s0->getFlags() & PxShapeFlag::eTRIGGER_SHAPE) && !(s1->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)); ActorSim* aLess = &s0->getActor(); ActorSim* aMore = &s1->getActor(); if(aLess->getActorID() > aMore->getActorID()) PxSwap(aLess, aMore); const BodyPairKey key(aLess->getActorID(), aMore->getActorID()); ActorPair*& actorPair = mActorPairMap[key]; if(actorPair == NULL) { if(!isReportPair) actorPair = mActorPairPool.construct(); else actorPair = mActorPairReportPool.construct(s0->getActor(), s1->getActor()); } if(!isReportPair || actorPair->isReportPair()) return actorPair; else { PxU32 size = aLess->getActorInteractionCount(); Interaction** interactions = aLess->getActorInteractions(); ActorPairReport* actorPairReport = mActorPairReportPool.construct(s0->getActor(), s1->getActor()); actorPairReport->convert(*actorPair); while(size--) { Interaction* interaction = *interactions++; if((&interaction->getActorSim0() == aMore) || (&interaction->getActorSim1() == aMore)) { PX_ASSERT(((&interaction->getActorSim0() == aLess) || (&interaction->getActorSim1() == aLess))); if(interaction->getType() == InteractionType::eOVERLAP) { ShapeInteraction* si = static_cast<ShapeInteraction*>(interaction); if(si->getActorPair() != NULL) si->setActorPair(*actorPairReport); } } } PX_ASSERT(!actorPair->isReportPair()); mActorPairPool.destroy(actorPair); actorPair = actorPairReport; } return actorPair; } PX_FORCE_INLINE void NPhaseCore::destroyActorPairReport(ActorPairReport& aPair) { PX_ASSERT(aPair.isReportPair()); aPair.releaseContactReportData(*this); mActorPairReportPool.destroy(&aPair); } ElementSimInteraction* NPhaseCore::convert(ElementSimInteraction* pair, InteractionType::Enum newType, FilterInfo& filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs) { PX_ASSERT(newType != pair->getType()); ElementSim& elementA = pair->getElement0(); ElementSim& elementB = pair->getElement1(); // Wake up the actors of the pair if((pair->getActorSim0().getActorType() == PxActorType::eRIGID_DYNAMIC) && !(static_cast<BodySim&>(pair->getActorSim0()).isActive())) pair->getActorSim0().internalWakeUp(); if((pair->getActorSim1().getActorType() == PxActorType::eRIGID_DYNAMIC) && !(static_cast<BodySim&>(pair->getActorSim1()).isActive())) pair->getActorSim1().internalWakeUp(); // Since the FilterPair struct might have been re-used in the newly created interaction, we need to clear // the filter pair marker of the old interaction to avoid that the FilterPair gets deleted by the releaseElementPair() // call that follows. pair->clearInteractionFlag(InteractionFlag::eIS_FILTER_PAIR); // PT: we need to unregister the old interaction *before* creating the new one, because Sc::NPhaseCore::registerInteraction will use // ElementSim pointers which are the same for both. Since "releaseElementPair" will call the unregister function from // the element's dtor, we don't need to do it explicitly here. Just release the object. releaseElementPair(pair, PairReleaseFlag::eWAKE_ON_LOST_TOUCH | PairReleaseFlag::eRUN_LOST_TOUCH_LOGIC, NULL, 0, removeFromDirtyList, outputs); ElementSimInteraction* result = NULL; switch(newType) { case InteractionType::eINVALID: // This means the pair should get killed break; case InteractionType::eMARKER: { result = createElementInteractionMarker(elementA, elementB, NULL); break; } case InteractionType::eOVERLAP: { result = createShapeInteraction(static_cast<ShapeSim&>(elementA), static_cast<ShapeSim&>(elementB), filterInfo.pairFlags, NULL, NULL); break; } case InteractionType::eTRIGGER: { result = createTriggerInteraction(static_cast<ShapeSim&>(elementA), static_cast<ShapeSim&>(elementB), filterInfo.pairFlags); break; } case InteractionType::eCONSTRAINTSHADER: case InteractionType::eARTICULATION: case InteractionType::eTRACKED_IN_SCENE_COUNT: PX_ASSERT(0); break; }; if(filterInfo.hasPairID) { PX_ASSERT(result); // If a filter callback pair is going to get killed, then the FilterPair struct should already have // been deleted. // Mark the new interaction as a filter callback pair result->raiseInteractionFlag(InteractionFlag::eIS_FILTER_PAIR); } return result; } namespace physx { namespace Sc { static bool findTriggerContacts(TriggerInteraction* tri, bool toBeDeleted, bool volumeRemoved, PxTriggerPair& triggerPair, TriggerPairExtraData& triggerPairExtra, SimStats::TriggerPairCountsNonVolatile& triggerPairStats, const PxsTransformCache& transformCache) { ShapeSimBase& s0 = tri->getTriggerShape(); ShapeSimBase& s1 = tri->getOtherShape(); const PxPairFlags pairFlags = tri->getTriggerFlags(); PxPairFlags pairEvent; bool overlap; PxU8 testForRemovedShapes = 0; if(toBeDeleted) { // The trigger interaction is to lie down in its tomb, hence we know that the overlap is gone. // What remains is to check whether the interaction was deleted because of a shape removal in // which case we need to later check for removed shapes. overlap = false; if(volumeRemoved) { // Note: only the first removed volume can be detected when the trigger interaction is deleted but at a later point the second volume might get removed too. testForRemovedShapes = TriggerPairFlag::eTEST_FOR_REMOVED_SHAPES; } } else { #if PX_ENABLE_SIM_STATS PX_ASSERT(s0.getGeometryType() < PxGeometryType::eCONVEXMESH+1); // The first has to be the trigger shape triggerPairStats[s0.getGeometryType()][s1.getGeometryType()]++; #else PX_UNUSED(triggerPairStats); PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif ShapeSimBase* primitive0 = &s0; ShapeSimBase* primitive1 = &s1; PX_ASSERT(primitive0->getFlags() & PxShapeFlag::eTRIGGER_SHAPE || primitive1->getFlags() & PxShapeFlag::eTRIGGER_SHAPE); // Reorder them if needed if(primitive0->getGeometryType() > primitive1->getGeometryType()) PxSwap(primitive0, primitive1); const Gu::GeomOverlapFunc overlapFunc = Gu::getOverlapFuncTable()[primitive0->getGeometryType()][primitive1->getGeometryType()]; const PxU32 elementID0 = primitive0->getElementID(); const PxU32 elementID1 = primitive1->getElementID(); const PxTransform& globalPose0 = transformCache.getTransformCache(elementID0).transform; const PxTransform& globalPose1 = transformCache.getTransformCache(elementID1).transform; PX_ASSERT(overlapFunc); overlap = overlapFunc( primitive0->getCore().getGeometry(), globalPose0, primitive1->getCore().getGeometry(), globalPose1, &tri->getTriggerCache(), UNUSED_OVERLAP_THREAD_CONTEXT); } const bool hadOverlap = tri->lastFrameHadContacts(); if(hadOverlap) { if(!overlap) pairEvent = PxPairFlag::eNOTIFY_TOUCH_LOST; } else { if(overlap) pairEvent = PxPairFlag::eNOTIFY_TOUCH_FOUND; } tri->updateLastFrameHadContacts(overlap); const PxPairFlags triggeredFlags = pairEvent & pairFlags; if(triggeredFlags) { triggerPair.triggerShape = s0.getPxShape(); triggerPair.otherShape = s1.getPxShape(); triggerPair.status = PxPairFlag::Enum(PxU32(pairEvent)); triggerPair.flags = PxTriggerPairFlags(testForRemovedShapes); const ActorCore& actorCore0 = s0.getActor().getActorCore(); const ActorCore& actorCore1 = s1.getActor().getActorCore(); #if PX_SUPPORT_GPU_PHYSX if (actorCore0.getActorCoreType() == PxActorType::eSOFTBODY) triggerPair.triggerActor = static_cast<const SoftBodyCore&>(actorCore0).getPxActor(); else #endif triggerPair.triggerActor = static_cast<const RigidCore&>(actorCore0).getPxActor(); #if PX_SUPPORT_GPU_PHYSX if (actorCore0.getActorCoreType() == PxActorType::eSOFTBODY) triggerPair.otherActor = static_cast<const SoftBodyCore&>(actorCore1).getPxActor(); else #endif triggerPair.otherActor = static_cast<const RigidCore&>(actorCore1).getPxActor(); triggerPairExtra = TriggerPairExtraData(s0.getElementID(), s1.getElementID(), actorCore0.getOwnerClient(), actorCore1.getOwnerClient()); return true; } return false; } class TriggerContactTask : public Cm::Task { PX_NOCOPY(TriggerContactTask) public: TriggerContactTask(TriggerInteraction* const* triggerPairs, PxU32 triggerPairCount, PxMutex& lock, Scene& scene, PxsTransformCache& transformCache) : Cm::Task (scene.getContextId()), mTriggerPairs (triggerPairs), mTriggerPairCount (triggerPairCount), mLock (lock), mScene (scene), mTransformCache (transformCache) { } virtual void runInternal() { SimStats::TriggerPairCountsNonVolatile triggerPairStats; #if PX_ENABLE_SIM_STATS PxMemZero(&triggerPairStats, sizeof(SimStats::TriggerPairCountsNonVolatile)); #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif PxTriggerPair triggerPair[sTriggerPairsPerTask]; TriggerPairExtraData triggerPairExtra[sTriggerPairsPerTask]; PxU32 triggerReportItemCount = 0; for(PxU32 i=0; i < mTriggerPairCount; i++) { TriggerInteraction* tri = mTriggerPairs[i]; PX_ASSERT(tri->readInteractionFlag(InteractionFlag::eIS_ACTIVE)); if (findTriggerContacts(tri, false, false, triggerPair[triggerReportItemCount], triggerPairExtra[triggerReportItemCount], triggerPairStats, mTransformCache)) { triggerReportItemCount++; } } if(triggerReportItemCount) { PxTriggerPair* triggerPairBuffer; TriggerPairExtraData* triggerPairExtraBuffer; { PxMutex::ScopedLock lock(mLock); mScene.reserveTriggerReportBufferSpace(triggerReportItemCount, triggerPairBuffer, triggerPairExtraBuffer); PxMemCopy(triggerPairBuffer, triggerPair, sizeof(PxTriggerPair) * triggerReportItemCount); PxMemCopy(triggerPairExtraBuffer, triggerPairExtra, sizeof(TriggerPairExtraData) * triggerReportItemCount); } } #if PX_ENABLE_SIM_STATS SimStats& simStats = mScene.getStatsInternal(); for(PxU32 i=0; i < PxGeometryType::eCONVEXMESH+1; i++) { for(PxU32 j=0; j < PxGeometryType::eGEOMETRY_COUNT; j++) { if(triggerPairStats[i][j] != 0) PxAtomicAdd(&simStats.numTriggerPairs[i][j], triggerPairStats[i][j]); } } #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif } virtual const char* getName() const { return "ScNPhaseCore.triggerInteractionWork"; } public: static const PxU32 sTriggerPairsPerTask = 64; private: TriggerInteraction* const* mTriggerPairs; const PxU32 mTriggerPairCount; PxMutex& mLock; Scene& mScene; PxsTransformCache& mTransformCache; }; } // namespace Sc } // namespace physx bool TriggerProcessingContext::initialize(TriggerInteraction** interactions, PxU32 pairCount, PxcScratchAllocator& allocator) { PX_ASSERT(!mTmpTriggerProcessingBlock); PX_ASSERT(mTmpTriggerPairCount == 0); PX_ASSERT(pairCount > 0); const PxU32 taskCountWithoutRemainder = pairCount / TriggerContactTask::sTriggerPairsPerTask; const PxU32 maxTaskCount = taskCountWithoutRemainder + 1; const PxU32 pairPtrSize = pairCount * sizeof(TriggerInteraction*); const PxU32 memBlockSize = pairPtrSize + (maxTaskCount * sizeof(TriggerContactTask)); PxU8* triggerProcessingBlock = reinterpret_cast<PxU8*>(allocator.alloc(memBlockSize, true)); if (triggerProcessingBlock) { PxMemCopy(triggerProcessingBlock, interactions, pairPtrSize); // needs to get copied because other tasks may change the source list // while trigger overlap tests run mTmpTriggerProcessingBlock = triggerProcessingBlock; // note: gets released in deinitialize mTmpTriggerPairCount = pairCount; return true; } else { outputError<PxErrorCode::eOUT_OF_MEMORY>(__LINE__, "Temporary memory for trigger pair processing could not be allocated. Trigger overlap tests will not take place."); } return false; } void TriggerProcessingContext::deinitialize(PxcScratchAllocator& allocator) { PX_ASSERT(mTmpTriggerProcessingBlock); PX_ASSERT(mTmpTriggerPairCount > 0); allocator.free(mTmpTriggerProcessingBlock); mTmpTriggerProcessingBlock = NULL; mTmpTriggerPairCount = 0; } PxBaseTask* NPhaseCore::prepareForTriggerInteractionProcessing(PxBaseTask* continuation) { // Triggers TriggerInteraction** triggerInteractions = reinterpret_cast<TriggerInteraction**>(mOwnerScene.getActiveInteractions(InteractionType::eTRIGGER)); const PxU32 pairCount = mOwnerScene.getNbActiveInteractions(InteractionType::eTRIGGER); if (pairCount > 0) { if (mTriggerProcessingContext.initialize(triggerInteractions, pairCount, mOwnerScene.getLowLevelContext()->getScratchAllocator())) { mConcludeTriggerInteractionProcessingTask.setContinuation(continuation); return &mConcludeTriggerInteractionProcessingTask; } } return NULL; } void NPhaseCore::processTriggerInteractions(PxBaseTask& continuation) { TriggerInteraction* const* triggerInteractions = mTriggerProcessingContext.getTriggerInteractions(); const PxU32 pairCount = mTriggerProcessingContext.getTriggerInteractionCount(); TriggerContactTask* triggerContactTaskBuffer = mTriggerProcessingContext.getTriggerContactTasks(); PxMutex& triggerWriteBackLock = mTriggerProcessingContext.getTriggerWriteBackLock(); PX_ASSERT(triggerInteractions); PX_ASSERT(pairCount > 0); PX_ASSERT(triggerContactTaskBuffer); // PT: TASK-CREATION TAG const bool hasMultipleThreads = mOwnerScene.getTaskManager().getCpuDispatcher()->getWorkerCount() > 1; const bool moreThanOneBatch = pairCount > TriggerContactTask::sTriggerPairsPerTask; const bool scheduleTasks = hasMultipleThreads && moreThanOneBatch; // when running on a single thread, the task system seems to cause the main overhead (locking and atomic operations // seemed less of an issue). Hence, the tasks get run directly in that case. Same if there is only one batch. PxsTransformCache& transformCache = mOwnerScene.getLowLevelContext()->getTransformCache(); PxU32 remainder = pairCount; while(remainder) { const PxU32 nb = remainder > TriggerContactTask::sTriggerPairsPerTask ? TriggerContactTask::sTriggerPairsPerTask : remainder; remainder -= nb; TriggerContactTask* task = triggerContactTaskBuffer; task = PX_PLACEMENT_NEW(task, TriggerContactTask( triggerInteractions, nb, triggerWriteBackLock, mOwnerScene, transformCache)); if(scheduleTasks) { task->setContinuation(&continuation); task->removeReference(); } else task->runInternal(); triggerContactTaskBuffer++; triggerInteractions += nb; } } void NPhaseCore::concludeTriggerInteractionProcessing(PxBaseTask*) { // check if active trigger pairs can be deactivated (until woken up again) TriggerInteraction* const* triggerInteractions = mTriggerProcessingContext.getTriggerInteractions(); const PxU32 pairCount = mTriggerProcessingContext.getTriggerInteractionCount(); PX_ASSERT(triggerInteractions); PX_ASSERT(pairCount > 0); for (PxU32 i = 0; i < pairCount; i++) { TriggerInteraction* tri = triggerInteractions[i]; PX_ASSERT(tri->readInteractionFlag(InteractionFlag::eIS_ACTIVE)); if (!(tri->readFlag(TriggerInteraction::PROCESS_THIS_FRAME))) { // active trigger pairs for which overlap tests were not forced should remain in the active list // to catch transitions between overlap and no overlap continue; } else { tri->clearFlag(TriggerInteraction::PROCESS_THIS_FRAME); // explicitly scheduled overlap test is done (after object creation, teleport, ...). Check if trigger pair should remain active or not. if (!tri->onActivate(NULL)) { PX_ASSERT(tri->readInteractionFlag(InteractionFlag::eIS_ACTIVE)); // Why is the assert enough? // Once an explicit overlap test is scheduled, the interaction can not get deactivated anymore until it got processed. tri->clearInteractionFlag(InteractionFlag::eIS_ACTIVE); mOwnerScene.notifyInteractionDeactivated(tri); } } } mTriggerProcessingContext.deinitialize(mOwnerScene.getLowLevelContext()->getScratchAllocator()); } #ifdef REMOVED class ProcessPersistentContactTask : public Cm::Task { Sc::NPhaseCore& mCore; ContactReportBuffer& mBuffer; PxMutex& mMutex; ShapeInteraction*const* mPersistentEventPairs; PxU32 mNbPersistentEventPairs; PxsContactManagerOutputIterator mOutputs; PX_NOCOPY(ProcessPersistentContactTask) public: ProcessPersistentContactTask(Sc::NPhaseCore& core, ContactReportBuffer& buffer, PxMutex& mutex, ShapeInteraction*const* persistentEventPairs, PxU32 nbPersistentEventPairs, PxsContactManagerOutputIterator& outputs) : Cm::Task(0), mCore(core), mBuffer(buffer), mMutex(mutex), mPersistentEventPairs(persistentEventPairs), mNbPersistentEventPairs(nbPersistentEventPairs), mOutputs(outputs) { } virtual void runInternal() { PX_PROFILE_ZONE("ProcessPersistentContactTask", mCore.getScene().getContextId()); PxU32 size = mNbPersistentEventPairs; ShapeInteraction*const* persistentEventPairs = mPersistentEventPairs; while (size--) { ShapeInteraction* pair = *persistentEventPairs++; if (size) { if (size > 1) { if (size > 2) { ShapeInteraction* nextPair = *(persistentEventPairs + 2); prefetchLine(nextPair); } ShapeInteraction* nextPair = *(persistentEventPairs + 1); ActorPair* aPair = nextPair->getActorPair(); prefetchLine(aPair); prefetchLine(&nextPair->getShape0()); prefetchLine(&nextPair->getShape1()); } ShapeInteraction* nextPair = *(persistentEventPairs); prefetchLine(&nextPair->getShape0().getActor()); prefetchLine(&nextPair->getShape1().getActor()); } PX_ASSERT(pair->hasTouch()); PX_ASSERT(pair->isReportPair()); const PxU32 pairFlags = pair->getPairFlags(); if ((pairFlags & PxU32(PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eDETECT_DISCRETE_CONTACT)) == PxU32(PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eDETECT_DISCRETE_CONTACT)) { // do not process the pair if only eDETECT_CCD_CONTACT is enabled because at this point CCD did not run yet. Plus the current CCD implementation can not reliably provide eNOTIFY_TOUCH_PERSISTS events // for performance reasons. //KS - filter based on edge activity! const ActorSim& bodySim0 = pair->getShape0().getActor(); const ActorSim& bodySim1 = pair->getShape1().getActor(); if (bodySim0.isActive() || (!bodySim1.isStaticRigid() && bodySim1.isActive())) pair->processUserNotificationAsync(PxPairFlag::eNOTIFY_TOUCH_PERSISTS, 0, false, 0, false, mOutputs/*, &alloc*/); } } } virtual const char* getName() const { return "ScNPhaseCore.ProcessPersistentContactTask"; } }; #endif void NPhaseCore::processPersistentContactEvents(PxsContactManagerOutputIterator& outputs) { PX_PROFILE_ZONE("Sc::NPhaseCore::processPersistentContactEvents", mOwnerScene.getContextId()); // Go through ShapeInteractions which requested persistent contact event reports. This is necessary since there are no low level events for persistent contact. ShapeInteraction*const* persistentEventPairs = getCurrentPersistentContactEventPairs(); PxU32 size = getCurrentPersistentContactEventPairCount(); while (size--) { ShapeInteraction* pair = *persistentEventPairs++; if (size) { ShapeInteraction* nextPair = *persistentEventPairs; PxPrefetchLine(nextPair); } ActorPair* aPair = pair->getActorPair(); PxPrefetchLine(aPair); PX_ASSERT(pair->hasTouch()); PX_ASSERT(pair->isReportPair()); const PxU32 pairFlags = pair->getPairFlags(); if ((pairFlags & PxU32(PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eDETECT_DISCRETE_CONTACT)) == PxU32(PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eDETECT_DISCRETE_CONTACT)) { // do not process the pair if only eDETECT_CCD_CONTACT is enabled because at this point CCD did not run yet. Plus the current CCD implementation can not reliably provide eNOTIFY_TOUCH_PERSISTS events // for performance reasons. //KS - filter based on edge activity! const ActorSim& actorSim0= pair->getShape0().getActor(); const ActorSim& actorSim1 = pair->getShape1().getActor(); if (actorSim0.isActive() || ((!actorSim1.isStaticRigid()) && actorSim1.isActive())) pair->processUserNotification(PxPairFlag::eNOTIFY_TOUCH_PERSISTS, 0, false, 0, false, outputs); } } } void NPhaseCore::addToDirtyInteractionList(Interaction* pair) { mDirtyInteractions.insert(pair); } void NPhaseCore::removeFromDirtyInteractionList(Interaction* pair) { PX_ASSERT(mDirtyInteractions.contains(pair)); mDirtyInteractions.erase(pair); } void NPhaseCore::updateDirtyInteractions(PxsContactManagerOutputIterator& outputs) { // The sleeping SIs will be updated on activation // clow: Sleeping SIs are not awaken for visualization updates const bool dirtyDominance = mOwnerScene.readInternalFlag(SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_DOMINANCE); const bool dirtyVisualization = mOwnerScene.readInternalFlag(SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_VISUALIZATION); if(dirtyDominance || dirtyVisualization) { // Update all interactions. const PxU8 mask = PxTo8((dirtyDominance ? InteractionDirtyFlag::eDOMINANCE : 0) | (dirtyVisualization ? InteractionDirtyFlag::eVISUALIZATION : 0)); ElementSimInteraction** it = mOwnerScene.getInteractions(InteractionType::eOVERLAP); PxU32 size = mOwnerScene.getNbInteractions(InteractionType::eOVERLAP); while(size--) { ElementSimInteraction* pair = *it++; PX_ASSERT(pair->getType() == InteractionType::eOVERLAP); if(!pair->readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)) { PX_ASSERT(!pair->getDirtyFlags()); static_cast<ShapeInteraction*>(pair)->updateState(mask); } else pair->setDirty(mask); // the pair will get processed further below anyway, so just mark the flags dirty } } // Update all interactions in the dirty list const PxU32 dirtyItcCount = mDirtyInteractions.size(); Interaction* const* dirtyInteractions = mDirtyInteractions.getEntries(); for(PxU32 i = 0; i < dirtyItcCount; i++) { Interaction* refInt = dirtyInteractions[i]; Interaction* interaction = refInt; if(interaction->isElementInteraction() && interaction->needsRefiltering()) { ElementSimInteraction* pair = static_cast<ElementSimInteraction*>(interaction); refInt = refilterInteraction(pair, NULL, false, outputs); } if(interaction == refInt) // Refiltering might convert the pair to another type and kill the old one. In that case we don't want to update the new pair since it has been updated on creation. { const InteractionType::Enum iType = interaction->getType(); if (iType == InteractionType::eOVERLAP) static_cast<ShapeInteraction*>(interaction)->updateState(0); else if (iType == InteractionType::eCONSTRAINTSHADER) static_cast<ConstraintInteraction*>(interaction)->updateState(); interaction->setClean(false); // false because the dirty interactions list gets cleard further below } } mDirtyInteractions.clear(); } void NPhaseCore::releaseElementPair(ElementSimInteraction* pair, PxU32 flags, ElementSim* removedElement, PxU32 ccdPass, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs) { pair->setClean(removeFromDirtyList); // Removes the pair from the dirty interaction list etc. if(pair->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR)) { // Check if this is a filter callback pair ShapeSimBase& s0 = static_cast<ShapeSimBase&>(pair->getElement0()); ShapeSimBase& s1 = static_cast<ShapeSimBase&>(pair->getElement1()); callPairLost(s0, s1, removedElement != NULL); } switch(pair->getType()) { case InteractionType::eTRIGGER: { PxsTransformCache& transformCache = mOwnerScene.getLowLevelContext()->getTransformCache(); TriggerInteraction* tri = static_cast<TriggerInteraction*>(pair); PxTriggerPair triggerPair; TriggerPairExtraData triggerPairExtra; if (findTriggerContacts(tri, true, (removedElement != NULL), triggerPair, triggerPairExtra, const_cast<SimStats::TriggerPairCountsNonVolatile&>(mOwnerScene.getStatsInternal().numTriggerPairs), transformCache)) // cast away volatile-ness (this is fine since the method does not run in parallel) { mOwnerScene.getTriggerBufferAPI().pushBack(triggerPair); mOwnerScene.getTriggerBufferExtraData().pushBack(triggerPairExtra); } mTriggerInteractionPool.destroy(tri); } break; case InteractionType::eMARKER: { ElementInteractionMarker* interactionMarker = static_cast<ElementInteractionMarker*>(pair); mInteractionMarkerPool.destroy(interactionMarker); } break; case InteractionType::eOVERLAP: { ShapeInteraction* si = static_cast<ShapeInteraction*>(pair); if(flags & PairReleaseFlag::eRUN_LOST_TOUCH_LOGIC) lostTouchReports(si, flags, removedElement, ccdPass, outputs); mShapeInteractionPool.destroy(si); } break; case InteractionType::eCONSTRAINTSHADER: case InteractionType::eARTICULATION: case InteractionType::eTRACKED_IN_SCENE_COUNT: case InteractionType::eINVALID: PX_ASSERT(0); return; } } void NPhaseCore::lostTouchReports(ShapeInteraction* si, PxU32 flags, ElementSim* removedElement, PxU32 ccdPass, PxsContactManagerOutputIterator& outputs) { if(si->hasTouch()) { if(si->isReportPair()) si->sendLostTouchReport((removedElement != NULL), ccdPass, outputs); si->adjustCountersOnLostTouch(); } ActorPair* aPair = si->getActorPair(); if(aPair && aPair->decRefCount() == 0) { RigidSim* sim0 = static_cast<RigidSim*>(&si->getActorSim0()); RigidSim* sim1 = static_cast<RigidSim*>(&si->getActorSim1()); if(sim0->getActorID() > sim1->getActorID()) PxSwap(sim0, sim1); const BodyPairKey pair(sim0->getActorID(), sim1->getActorID()); mActorPairMap.erase(pair); if(!aPair->isReportPair()) { mActorPairPool.destroy(aPair); } else { ActorPairReport& apr = ActorPairReport::cast(*aPair); destroyActorPairReport(apr); } } si->clearActorPair(); if(si->hasTouch() || (!si->hasKnownTouchState())) { ActorSim& b0 = si->getShape0().getActor(); ActorSim& b1 = si->getShape1().getActor(); if(flags & PairReleaseFlag::eWAKE_ON_LOST_TOUCH) { // we rely on shape pair ordering here, where the first body is never static // (see createShapeInteraction()) PX_ASSERT(!b0.isStaticRigid()); if (removedElement == NULL) { if (b1.isStaticRigid()) // no check for b0 being static, see assert further above { // given wake-on-lost-touch has been requested: // if one is static, we wake up the other immediately b0.internalWakeUp(); } else if(!si->readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) { mOwnerScene.addToLostTouchList(b0, b1); } } else { // given wake-on-lost-touch has been requested: // if an element (broadphase volume) has been removed, we wake the other actor up PX_ASSERT((removedElement == &si->getShape0()) || (removedElement == &si->getShape1())); if (&si->getShape0() == removedElement) { if (!b1.isStaticRigid()) b1.internalWakeUp(); } else b0.internalWakeUp(); // no check for b0 being non-static, see assert further above } } } } void NPhaseCore::clearContactReportActorPairs(bool shrinkToZero) { for(PxU32 i=0; i < mContactReportActorPairSet.size(); i++) { //TODO: prefetch? ActorPairReport* aPair = mContactReportActorPairSet[i]; const PxU32 refCount = aPair->getRefCount(); PX_ASSERT(aPair->isInContactReportActorPairSet()); PX_ASSERT(refCount > 0); aPair->decRefCount(); // Reference held by contact callback if(refCount > 1) { aPair->clearInContactReportActorPairSet(); } else { const PxU32 actorAID = aPair->getActorAID(); const PxU32 actorBID = aPair->getActorBID(); const BodyPairKey pair(PxMin(actorAID, actorBID), PxMax(actorAID, actorBID)); mActorPairMap.erase(pair); destroyActorPairReport(*aPair); } } if(!shrinkToZero) mContactReportActorPairSet.clear(); else mContactReportActorPairSet.reset(); } void NPhaseCore::addToPersistentContactEventPairs(ShapeInteraction* si) { // Pairs which request events which do not get triggered by the sdk and thus need to be tested actively every frame. PX_ASSERT(si->getPairFlags() & (PxPairFlag::eNOTIFY_TOUCH_PERSISTS | ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS)); PX_ASSERT(si->mReportPairIndex == INVALID_REPORT_PAIR_ID); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST)); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST)); PX_ASSERT(si->hasTouch()); // only pairs which can from now on lose or keep contact should be in this list si->raiseFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST); if(mPersistentContactEventPairList.size() == mNextFramePersistentContactEventPairIndex) { si->mReportPairIndex = mPersistentContactEventPairList.size(); mPersistentContactEventPairList.pushBack(si); } else { //swap with first entry that will be active next frame ShapeInteraction* firstDelayedSi = mPersistentContactEventPairList[mNextFramePersistentContactEventPairIndex]; firstDelayedSi->mReportPairIndex = mPersistentContactEventPairList.size(); mPersistentContactEventPairList.pushBack(firstDelayedSi); si->mReportPairIndex = mNextFramePersistentContactEventPairIndex; mPersistentContactEventPairList[mNextFramePersistentContactEventPairIndex] = si; } mNextFramePersistentContactEventPairIndex++; } void NPhaseCore::addToPersistentContactEventPairsDelayed(ShapeInteraction* si) { // Pairs which request events which do not get triggered by the sdk and thus need to be tested actively every frame. PX_ASSERT(si->getPairFlags() & (PxPairFlag::eNOTIFY_TOUCH_PERSISTS | ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS)); PX_ASSERT(si->mReportPairIndex == INVALID_REPORT_PAIR_ID); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST)); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST)); PX_ASSERT(si->hasTouch()); // only pairs which can from now on lose or keep contact should be in this list si->raiseFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST); si->mReportPairIndex = mPersistentContactEventPairList.size(); mPersistentContactEventPairList.pushBack(si); } void NPhaseCore::removeFromPersistentContactEventPairs(ShapeInteraction* si) { PX_ASSERT(si->getPairFlags() & (PxPairFlag::eNOTIFY_TOUCH_PERSISTS | ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS)); PX_ASSERT(si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST)); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST)); PX_ASSERT(si->hasTouch()); // only pairs which could lose or keep contact should be in this list PxU32 index = si->mReportPairIndex; PX_ASSERT(index != INVALID_REPORT_PAIR_ID); if(index < mNextFramePersistentContactEventPairIndex) { const PxU32 replaceIdx = mNextFramePersistentContactEventPairIndex - 1; if((mNextFramePersistentContactEventPairIndex < mPersistentContactEventPairList.size()) && (index != replaceIdx)) { // keep next frame persistent pairs at the back of the list ShapeInteraction* tmp = mPersistentContactEventPairList[replaceIdx]; mPersistentContactEventPairList[index] = tmp; tmp->mReportPairIndex = index; index = replaceIdx; } mNextFramePersistentContactEventPairIndex--; } si->clearFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST); si->mReportPairIndex = INVALID_REPORT_PAIR_ID; mPersistentContactEventPairList.replaceWithLast(index); if(index < mPersistentContactEventPairList.size()) // Only adjust the index if the removed SIP was not at the end of the list mPersistentContactEventPairList[index]->mReportPairIndex = index; } void NPhaseCore::addToForceThresholdContactEventPairs(ShapeInteraction* si) { PX_ASSERT(si->getPairFlags() & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS); PX_ASSERT(si->mReportPairIndex == INVALID_REPORT_PAIR_ID); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST)); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST)); PX_ASSERT(si->hasTouch()); si->raiseFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST); si->mReportPairIndex = mForceThresholdContactEventPairList.size(); mForceThresholdContactEventPairList.pushBack(si); } void NPhaseCore::removeFromForceThresholdContactEventPairs(ShapeInteraction* si) { PX_ASSERT(si->getPairFlags() & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS); PX_ASSERT(si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST)); PX_ASSERT(!si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST)); PX_ASSERT(si->hasTouch()); const PxU32 index = si->mReportPairIndex; PX_ASSERT(index != INVALID_REPORT_PAIR_ID); si->clearFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST); si->mReportPairIndex = INVALID_REPORT_PAIR_ID; mForceThresholdContactEventPairList.replaceWithLast(index); if(index < mForceThresholdContactEventPairList.size()) // Only adjust the index if the removed SIP was not at the end of the list mForceThresholdContactEventPairList[index]->mReportPairIndex = index; } PxU8* NPhaseCore::reserveContactReportPairData(PxU32 pairCount, PxU32 extraDataSize, PxU32& bufferIndex, ContactReportAllocationManager* alloc) { extraDataSize = ContactStreamManager::computeExtraDataBlockSize(extraDataSize); return alloc ? alloc->allocate(extraDataSize + (pairCount * sizeof(ContactShapePair)), bufferIndex) : mContactReportBuffer.allocateNotThreadSafe(extraDataSize + (pairCount * sizeof(ContactShapePair)), bufferIndex); } PxU8* NPhaseCore::resizeContactReportPairData(PxU32 pairCount, PxU32 extraDataSize, ContactStreamManager& csm) { PX_ASSERT((pairCount > csm.maxPairCount) || (extraDataSize > csm.getMaxExtraDataSize())); PX_ASSERT((csm.currentPairCount == csm.maxPairCount) || (extraDataSize > csm.getMaxExtraDataSize())); PX_ASSERT(extraDataSize >= csm.getMaxExtraDataSize()); // we do not support stealing memory from the extra data part when the memory for pair info runs out PxU32 bufferIndex; PxPrefetch(mContactReportBuffer.getData(csm.bufferIndex)); extraDataSize = ContactStreamManager::computeExtraDataBlockSize(extraDataSize); PxU8* stream = mContactReportBuffer.reallocateNotThreadSafe(extraDataSize + (pairCount * sizeof(ContactShapePair)), bufferIndex, 16, csm.bufferIndex); PxU8* oldStream = mContactReportBuffer.getData(csm.bufferIndex); if(stream) { const PxU32 maxExtraDataSize = csm.getMaxExtraDataSize(); if(csm.bufferIndex != bufferIndex) { if(extraDataSize <= maxExtraDataSize) PxMemCopy(stream, oldStream, maxExtraDataSize + (csm.currentPairCount * sizeof(ContactShapePair))); else { PxMemCopy(stream, oldStream, csm.extraDataSize); PxMemCopy(stream + extraDataSize, oldStream + maxExtraDataSize, csm.currentPairCount * sizeof(ContactShapePair)); } csm.bufferIndex = bufferIndex; } else if(extraDataSize > maxExtraDataSize) PxMemMove(stream + extraDataSize, oldStream + maxExtraDataSize, csm.currentPairCount * sizeof(ContactShapePair)); if(pairCount > csm.maxPairCount) csm.maxPairCount = PxTo16(pairCount); if(extraDataSize > maxExtraDataSize) csm.setMaxExtraDataSize(extraDataSize); } return stream; } ActorPairContactReportData* NPhaseCore::createActorPairContactReportData() { PxMutex::ScopedLock lock(mReportAllocLock); return mActorPairContactReportDataPool.construct(); } void NPhaseCore::releaseActorPairContactReportData(ActorPairContactReportData* data) { mActorPairContactReportDataPool.destroy(data); }
47,491
C++
36.045242
215
0.753806
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFiltering.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_FILTERING_H #define SC_FILTERING_H #include "PxFiltering.h" namespace physx { namespace Sc { struct FilterInfo { PX_FORCE_INLINE FilterInfo() : filterFlags(0), pairFlags(0), hasPairID(false) {} PX_FORCE_INLINE FilterInfo(PxFilterFlags filterFlags_) : filterFlags(filterFlags_), pairFlags(0), hasPairID(false) {} PxFilterFlags filterFlags; PxPairFlags pairFlags; bool hasPairID; }; } } #endif
2,130
C
40.784313
119
0.756338
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScCCD.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/PxProfileZone.h" #include "ScBodySim.h" #include "ScShapeSim.h" #include "ScArticulationSim.h" #include "ScScene.h" using namespace physx; using namespace Sc; /////////////////////////////////////////////////////////////////////////////// void BodySim::addToSpeculativeCCDMap() { if(mNodeIndex.isValid()) { if(isArticulationLink()) mScene.setSpeculativeCCDArticulationLink(mNodeIndex.index()); else mScene.setSpeculativeCCDRigidBody(mNodeIndex.index()); } } void BodySim::removeFromSpeculativeCCDMap() { if(mNodeIndex.isValid()) { if(isArticulationLink()) mScene.resetSpeculativeCCDArticulationLink(mNodeIndex.index()); else mScene.resetSpeculativeCCDRigidBody(mNodeIndex.index()); } } // PT: TODO: consider using a non-member function for this one void BodySim::updateContactDistance(PxReal* contactDistance, PxReal dt, const Bp::BoundsArray& boundsArray) { const PxsRigidBody& llBody = getLowLevelBody(); const PxRigidBodyFlags flags = llBody.getCore().mFlags; // PT: TODO: no need to test eENABLE_SPECULATIVE_CCD if we parsed mSpeculativeCCDRigidBodyBitMap initially if((flags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) && !(llBody.mInternalFlags & PxsRigidBody::eFROZEN)) { // PT: if both CCD flags are enabled we're in "hybrid mode" and we only use speculative contacts for the angular part const PxReal linearInflation = (flags & PxRigidBodyFlag::eENABLE_CCD) ? 0.0f : llBody.getLinearVelocity().magnitude() * dt; const float angVelMagTimesDt = llBody.getAngularVelocity().magnitude() * dt; PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while(nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); const PxU32 index = current->getElementID(); const PxBounds3& bounds = boundsArray.getBounds(index); const PxReal radius = bounds.getExtents().magnitude(); //Heuristic for angular velocity... const PxReal angularInflation = angVelMagTimesDt * radius; contactDistance[index] = linearInflation + current->getContactOffset() + angularInflation; } } } void Sc::ArticulationSim::updateContactDistance(PxReal* contactDistance, PxReal dt, const Bp::BoundsArray& boundsArray) { const PxU32 size = mBodies.size(); for(PxU32 i=0; i<size; i++) mBodies[i]->updateContactDistance(contactDistance, dt, boundsArray); } namespace { class SpeculativeCCDBaseTask : public Cm::Task { PX_NOCOPY(SpeculativeCCDBaseTask) public: const Bp::BoundsArray& mBoundsArray; float* mContactDistances; const float mDt; SpeculativeCCDBaseTask(PxU64 contextID, const Bp::BoundsArray& boundsArray, PxReal* contactDistances, PxReal dt) : Cm::Task (contextID), mBoundsArray (boundsArray), mContactDistances (contactDistances), mDt (dt) {} }; class SpeculativeCCDContactDistanceUpdateTask : public SpeculativeCCDBaseTask { public: static const PxU32 MaxBodies = 128; BodySim* mBodySims[MaxBodies]; PxU32 mNbBodies; SpeculativeCCDContactDistanceUpdateTask(PxU64 contextID, PxReal* contactDistances, PxReal dt, const Bp::BoundsArray& boundsArray) : SpeculativeCCDBaseTask (contextID, boundsArray, contactDistances, dt), mNbBodies (0) {} virtual void runInternal() { const PxU32 nb = mNbBodies; for(PxU32 i=0; i<nb; i++) mBodySims[i]->updateContactDistance(mContactDistances, mDt, mBoundsArray); } virtual const char* getName() const { return "SpeculativeCCDContactDistanceUpdateTask"; } private: PX_NOCOPY(SpeculativeCCDContactDistanceUpdateTask) }; class SpeculativeCCDContactDistanceArticulationUpdateTask : public SpeculativeCCDBaseTask { public: ArticulationSim* mArticulation; SpeculativeCCDContactDistanceArticulationUpdateTask(PxU64 contextID, PxReal* contactDistances, PxReal dt, const Bp::BoundsArray& boundsArray, ArticulationSim* sim) : SpeculativeCCDBaseTask (contextID, boundsArray, contactDistances, dt), mArticulation (sim) {} virtual void runInternal() { mArticulation->updateContactDistance(mContactDistances, mDt, mBoundsArray); } virtual const char* getName() const { return "SpeculativeCCDContactDistanceArticulationUpdateTask"; } private: PX_NOCOPY(SpeculativeCCDContactDistanceArticulationUpdateTask) }; } static SpeculativeCCDContactDistanceUpdateTask* createCCDTask(Cm::FlushPool& pool, PxU64 contextID, PxReal* contactDistances, PxReal dt, const Bp::BoundsArray& boundsArray) { return PX_PLACEMENT_NEW(pool.allocate(sizeof(SpeculativeCCDContactDistanceUpdateTask)), SpeculativeCCDContactDistanceUpdateTask)(contextID, contactDistances, dt, boundsArray); } void Sc::Scene::updateContactDistances(PxBaseTask* continuation) { PX_PROFILE_ZONE("Scene.updateContactDistances", mContextId); Cm::FlushPool& pool = mLLContext->getTaskPool(); IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); bool hasContactDistanceChanged = mHasContactDistanceChanged; // PT: TODO: it is quite unfortunate that we cannot shortcut parsing the bitmaps. Consider switching to arrays. // We remove sleeping bodies from the map but we never shrink it.... // PT: TODO: why do we need to involve the island manager here? // PT: TODO: why do we do that on sleeping bodies? Why don't we use mActiveBodies? // PxArray<BodyCore*> mActiveBodies; // Sorted: kinematic before dynamic // ===> because we remove bodies from the bitmap in BodySim::deactivate() //calculate contact distance for speculative CCD shapes if(1) { PxBitMap::Iterator speculativeCCDIter(mSpeculativeCCDRigidBodyBitMap); SpeculativeCCDContactDistanceUpdateTask* ccdTask = createCCDTask(pool, mContextId, mContactDistance->begin(), mDt, *mBoundsArray); PxBitMapPinned& changedMap = mAABBManager->getChangedAABBMgActorHandleMap(); const size_t bodyOffset = PX_OFFSET_OF_RT(BodySim, getLowLevelBody()); //printf("\n"); //PxU32 count = 0; PxU32 nbBodies = 0; PxU32 index; while((index = speculativeCCDIter.getNext()) != PxBitMap::Iterator::DONE) { PxsRigidBody* rigidBody = islandSim.getRigidBody(PxNodeIndex(index)); BodySim* bodySim = reinterpret_cast<BodySim*>(reinterpret_cast<PxU8*>(rigidBody)-bodyOffset); if(bodySim) { //printf("%d\n", bodySim->getActiveListIndex()); //printf("%d: %d\n", count++, bodySim->isActive()); hasContactDistanceChanged = true; ccdTask->mBodySims[nbBodies++] = bodySim; // PT: ### changedMap pattern #1 // PT: TODO: isn't there a problem here? The task function will only touch the shapes whose body has the // speculative flag and isn't frozen, but here we mark all shapes as changed no matter what. // // Also we test some bodySim data and one bit of each ShapeSim here, not great. PxU32 nbElems = bodySim->getNbElements(); ElementSim** elems = bodySim->getElements(); while(nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); if(sim->getFlags() & PxShapeFlag::eSIMULATION_SHAPE) changedMap.growAndSet(sim->getElementID()); } // PT: TODO: better load balancing? if(nbBodies == SpeculativeCCDContactDistanceUpdateTask::MaxBodies) { ccdTask->mNbBodies = nbBodies; nbBodies = 0; startTask(ccdTask, continuation); if(continuation) ccdTask = createCCDTask(pool, mContextId, mContactDistance->begin(), mDt, *mBoundsArray); else ccdTask->mNbBodies = 0; // PT: no need to create a new task in single-threaded mode } } } if(nbBodies) { ccdTask->mNbBodies = nbBodies; startTask(ccdTask, continuation); } } /* else { // PT: codepath without mSpeculativeCCDRigidBodyBitMap PxU32 nb = mActiveBodies.size(); BodyCore** bodies = mActiveBodies.begin(); while(nb--) { const BodyCore* current = *bodies++; BodySim* bodySim = current->getSim(); if(bodySim) { ... } } }*/ //calculate contact distance for articulation links { PxBitMap::Iterator articulateCCDIter(mSpeculativeCDDArticulationBitMap); PxU32 index; while((index = articulateCCDIter.getNext()) != PxBitMap::Iterator::DONE) { ArticulationSim* articulationSim = islandSim.getArticulationSim(PxNodeIndex(index)); if(articulationSim) { hasContactDistanceChanged = true; if(continuation) { SpeculativeCCDContactDistanceArticulationUpdateTask* articulationUpdateTask = PX_PLACEMENT_NEW(pool.allocate(sizeof(SpeculativeCCDContactDistanceArticulationUpdateTask)), SpeculativeCCDContactDistanceArticulationUpdateTask)(mContextId, mContactDistance->begin(), mDt, *mBoundsArray, articulationSim); articulationUpdateTask->setContinuation(continuation); articulationUpdateTask->removeReference(); } else { articulationSim->updateContactDistance(mContactDistance->begin(), mDt, *mBoundsArray); } } } } mHasContactDistanceChanged = hasContactDistanceChanged; } /////////////////////////////////////////////////////////////////////////////// #include "ScNPhaseCore.h" #include "ScShapeInteraction.h" #include "PxsCCD.h" #include "PxsSimulationController.h" #include "CmTransformUtils.h" void Sc::Scene::setCCDContactModifyCallback(PxCCDContactModifyCallback* callback) { mCCDContext->setCCDContactModifyCallback(callback); } PxCCDContactModifyCallback* Sc::Scene::getCCDContactModifyCallback() const { return mCCDContext->getCCDContactModifyCallback(); } void Sc::Scene::setCCDMaxPasses(PxU32 ccdMaxPasses) { mCCDContext->setCCDMaxPasses(ccdMaxPasses); } PxU32 Sc::Scene::getCCDMaxPasses() const { return mCCDContext->getCCDMaxPasses(); } void Sc::Scene::setCCDThreshold(PxReal t) { mCCDContext->setCCDThreshold(t); } PxReal Sc::Scene::getCCDThreshold() const { return mCCDContext->getCCDThreshold(); } void Sc::Scene::collectPostSolverVelocitiesBeforeCCD() { if(mContactReportsNeedPostSolverVelocity) { ActorPairReport*const* actorPairs = mNPhaseCore->getContactReportActorPairs(); PxU32 nbActorPairs = mNPhaseCore->getNbContactReportActorPairs(); for(PxU32 i=0; i < nbActorPairs; i++) { if(i < (nbActorPairs - 1)) PxPrefetchLine(actorPairs[i+1]); ActorPairReport* aPair = actorPairs[i]; ContactStreamManager& cs = aPair->getContactStreamManager(); PxU32 streamManagerFlag = cs.getFlags(); if(streamManagerFlag & ContactStreamManagerFlag::eINVALID_STREAM) continue; PxU8* stream = mNPhaseCore->getContactReportPairData(cs.bufferIndex); if(i + 1 < nbActorPairs) PxPrefetch(&(actorPairs[i+1]->getContactStreamManager())); if(!cs.extraDataSize) continue; else if (streamManagerFlag & ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY) cs.setContactReportPostSolverVelocity(stream, aPair->getActorA(), aPair->getActorB()); } } } void Sc::Scene::updateCCDMultiPass(PxBaseTask* parentContinuation) { getCcdBodies().forceSize_Unsafe(mSimulationControllerCallback->getNbCcdBodies()); // second run of the broadphase for making sure objects we have integrated did not tunnel. if(mPublicFlags & PxSceneFlag::eENABLE_CCD) { if(mContactReportsNeedPostSolverVelocity) { // the CCD code will overwrite the post solver body velocities, hence, we need to extract the info // first if any CCD enabled pair requested it. collectPostSolverVelocitiesBeforeCCD(); } //We use 2 CCD task chains to be able to chain together an arbitrary number of ccd passes if(mPostCCDPass.size() != 2) { mPostCCDPass.clear(); mUpdateCCDSinglePass.clear(); mCCDBroadPhase.clear(); mCCDBroadPhaseAABB.clear(); mPostCCDPass.reserve(2); mUpdateCCDSinglePass.reserve(2); mUpdateCCDSinglePass2.reserve(2); mUpdateCCDSinglePass3.reserve(2); mCCDBroadPhase.reserve(2); mCCDBroadPhaseAABB.reserve(2); for (int j = 0; j < 2; j++) { mPostCCDPass.pushBack(Cm::DelegateTask<Sc::Scene, &Sc::Scene::postCCDPass>(mContextId, this, "ScScene.postCCDPass")); mUpdateCCDSinglePass.pushBack(Cm::DelegateTask<Sc::Scene, &Sc::Scene::updateCCDSinglePass>(mContextId, this, "ScScene.updateCCDSinglePass")); mUpdateCCDSinglePass2.pushBack(Cm::DelegateTask<Sc::Scene, &Sc::Scene::updateCCDSinglePassStage2>(mContextId, this, "ScScene.updateCCDSinglePassStage2")); mUpdateCCDSinglePass3.pushBack(Cm::DelegateTask<Sc::Scene, &Sc::Scene::updateCCDSinglePassStage3>(mContextId, this, "ScScene.updateCCDSinglePassStage3")); mCCDBroadPhase.pushBack(Cm::DelegateTask<Sc::Scene, &Sc::Scene::ccdBroadPhase>(mContextId, this, "ScScene.ccdBroadPhase")); mCCDBroadPhaseAABB.pushBack(Cm::DelegateTask<Sc::Scene, &Sc::Scene::ccdBroadPhaseAABB>(mContextId, this, "ScScene.ccdBroadPhaseAABB")); } } //reset thread context in a place we know all tasks possibly accessing it, are in sync with. (see US6664) mLLContext->resetThreadContexts(); mCCDContext->updateCCDBegin(); mCCDBroadPhase[0].setContinuation(parentContinuation); mCCDBroadPhaseAABB[0].setContinuation(&mCCDBroadPhase[0]); mCCDBroadPhase[0].removeReference(); mCCDBroadPhaseAABB[0].removeReference(); } } namespace { class UpdateCCDBoundsTask : public Cm::Task { Bp::BoundsArray* mBoundArray; PxsTransformCache* mTransformCache; BodySim** mBodySims; PxU32 mNbToProcess; PxI32* mNumFastMovingShapes; public: static const PxU32 MaxPerTask = 256; UpdateCCDBoundsTask(PxU64 contextID, Bp::BoundsArray* boundsArray, PxsTransformCache* transformCache, BodySim** bodySims, PxU32 nbToProcess, PxI32* numFastMovingShapes) : Cm::Task (contextID), mBoundArray (boundsArray), mTransformCache (transformCache), mBodySims (bodySims), mNbToProcess (nbToProcess), mNumFastMovingShapes(numFastMovingShapes) { } virtual const char* getName() const { return "UpdateCCDBoundsTask";} PxIntBool updateSweptBounds(ShapeSim* sim, BodySim* body) { PX_ASSERT(body==sim->getBodySim()); const PxU32 elementID = sim->getElementID(); const ShapeCore& shapeCore = sim->getCore(); const PxTransform& endPose = mTransformCache->getTransformCache(elementID).transform; const PxGeometry& shapeGeom = shapeCore.getGeometry(); const PxsRigidBody& rigidBody = body->getLowLevelBody(); const PxsBodyCore& bodyCore = body->getBodyCore().getCore(); PX_ALIGN(16, PxTransform shape2World); Cm::getDynamicGlobalPoseAligned(rigidBody.mLastTransform, shapeCore.getShape2Actor(), bodyCore.getBody2Actor(), shape2World); const float ccdThreshold = computeCCDThreshold(shapeGeom); PxBounds3 bounds = Gu::computeBounds(shapeGeom, endPose); PxIntBool isFastMoving; if(1) { // PT: this alternative implementation avoids computing the start bounds for slow moving objects. isFastMoving = (shape2World.p - endPose.p).magnitudeSquared() >= ccdThreshold * ccdThreshold ? 1 : 0; if(isFastMoving) { const PxBounds3 startBounds = Gu::computeBounds(shapeGeom, shape2World); bounds.include(startBounds); } } else { const PxBounds3 startBounds = Gu::computeBounds(shapeGeom, shape2World); isFastMoving = (startBounds.getCenter() - bounds.getCenter()).magnitudeSquared() >= ccdThreshold * ccdThreshold ? 1 : 0; if(isFastMoving) bounds.include(startBounds); } PX_ASSERT(bounds.minimum.x <= bounds.maximum.x && bounds.minimum.y <= bounds.maximum.y && bounds.minimum.z <= bounds.maximum.z); mBoundArray->setBounds(bounds, elementID); return isFastMoving; } virtual void runInternal() { PxU32 activeShapes = 0; const PxU32 nb = mNbToProcess; for(PxU32 i=0; i<nb; i++) { PxU32 isFastMoving = 0; BodySim& bodySim = *mBodySims[i]; PxU32 nbElems = bodySim.getNbElements(); ElementSim** elems = bodySim.getElements(); while(nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); if(sim->getFlags() & PxU32(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) { const PxIntBool fastMovingShape = updateSweptBounds(sim, &bodySim); activeShapes += fastMovingShape; isFastMoving = isFastMoving | fastMovingShape; } } bodySim.getLowLevelBody().getCore().isFastMoving = isFastMoving!=0; } PxAtomicAdd(mNumFastMovingShapes, PxI32(activeShapes)); } }; } void Sc::Scene::ccdBroadPhaseAABB(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Sim.ccdBroadPhaseComplete", mContextId); PX_PROFILE_ZONE("Sim.ccdBroadPhaseAABB", mContextId); PX_UNUSED(continuation); PxU32 currentPass = mCCDContext->getCurrentCCDPass(); Cm::FlushPool& flushPool = mLLContext->getTaskPool(); mNumFastMovingShapes = 0; //If we are on the 1st pass or we had some sweep hits previous CCD pass, we need to run CCD again if(currentPass == 0 || mCCDContext->getNumSweepHits()) { PxsTransformCache& transformCache = getLowLevelContext()->getTransformCache(); for(PxU32 i = 0; i < mCcdBodies.size(); i+= UpdateCCDBoundsTask::MaxPerTask) { const PxU32 nbToProcess = PxMin(UpdateCCDBoundsTask::MaxPerTask, mCcdBodies.size() - i); UpdateCCDBoundsTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(UpdateCCDBoundsTask)), UpdateCCDBoundsTask)(mContextId, mBoundsArray, &transformCache, &mCcdBodies[i], nbToProcess, &mNumFastMovingShapes); task->setContinuation(continuation); task->removeReference(); } } } void Sc::Scene::ccdBroadPhase(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.ccdBroadPhase", mContextId); PxU32 currentPass = mCCDContext->getCurrentCCDPass(); const PxU32 ccdMaxPasses = mCCDContext->getCCDMaxPasses(); mCCDPass = currentPass+1; //If we are on the 1st pass or we had some sweep hits previous CCD pass, we need to run CCD again if( (currentPass == 0 || mCCDContext->getNumSweepHits()) && mNumFastMovingShapes != 0) { const PxU32 currIndex = currentPass & 1; const PxU32 nextIndex = 1 - currIndex; //Initialize the CCD task chain unless this is the final pass if(currentPass != (ccdMaxPasses - 1)) { mCCDBroadPhase[nextIndex].setContinuation(continuation); mCCDBroadPhaseAABB[nextIndex].setContinuation(&mCCDBroadPhase[nextIndex]); } mPostCCDPass[currIndex].setContinuation(currentPass == ccdMaxPasses-1 ? continuation : &mCCDBroadPhaseAABB[nextIndex]); mUpdateCCDSinglePass3[currIndex].setContinuation(&mPostCCDPass[currIndex]); mUpdateCCDSinglePass2[currIndex].setContinuation(&mUpdateCCDSinglePass3[currIndex]); mUpdateCCDSinglePass[currIndex].setContinuation(&mUpdateCCDSinglePass2[currIndex]); //Do the actual broad phase PxBaseTask* continuationTask = &mUpdateCCDSinglePass[currIndex]; // const PxU32 numCpuTasks = continuationTask->getTaskManager()->getCpuDispatcher()->getWorkerCount(); mCCDBp = true; mBpSecondPass.setContinuation(continuationTask); mBpFirstPass.setContinuation(&mBpSecondPass); mBpSecondPass.removeReference(); mBpFirstPass.removeReference(); //mAABBManager->updateAABBsAndBP(numCpuTasks, mLLContext->getTaskPool(), &mLLContext->getScratchAllocator(), false, continuationTask, NULL); //Allow the CCD task chain to continue mPostCCDPass[currIndex].removeReference(); mUpdateCCDSinglePass3[currIndex].removeReference(); mUpdateCCDSinglePass2[currIndex].removeReference(); mUpdateCCDSinglePass[currIndex].removeReference(); if(currentPass != (ccdMaxPasses - 1)) { mCCDBroadPhase[nextIndex].removeReference(); mCCDBroadPhaseAABB[nextIndex].removeReference(); } } else if (currentPass == 0) { PX_PROFILE_STOP_CROSSTHREAD("Sim.ccdBroadPhaseComplete", mContextId); mCCDContext->resetContactManagers(); } } void Sc::Scene::updateCCDSinglePass(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.updateCCDSinglePass", mContextId); mReportShapePairTimeStamp++; // This will makes sure that new report pairs will get created instead of re-using the existing ones. mAABBManager->postBroadPhase(NULL, *getFlushPool()); finishBroadPhase(continuation); const PxU32 currentPass = mCCDContext->getCurrentCCDPass() + 1; // 0 is reserved for discrete collision phase if(currentPass == 1) // reset the handle map so we only update CCD objects from here on { PxBitMapPinned& changedAABBMgrActorHandles = mAABBManager->getChangedAABBMgActorHandleMap(); //changedAABBMgrActorHandles.clear(); for(PxU32 i = 0; i < mCcdBodies.size();i++) { // PT: ### changedMap pattern #1 PxU32 nbElems = mCcdBodies[i]->getNbElements(); ElementSim** elems = mCcdBodies[i]->getElements(); while(nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); if(sim->getFlags()&PxU32(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) // TODO: need trigger shape here? changedAABBMgrActorHandles.growAndSet(sim->getElementID()); } } } } void Sc::Scene::updateCCDSinglePassStage2(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.updateCCDSinglePassStage2", mContextId); postBroadPhaseStage2(continuation); } void Sc::Scene::updateCCDSinglePassStage3(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.updateCCDSinglePassStage3", mContextId); mReportShapePairTimeStamp++; // This will makes sure that new report pairs will get created instead of re-using the existing ones. const PxU32 currentPass = mCCDContext->getCurrentCCDPass() + 1; // 0 is reserved for discrete collision phase finishBroadPhaseStage2(currentPass); PX_PROFILE_STOP_CROSSTHREAD("Sim.ccdBroadPhaseComplete", mContextId); //reset thread context in a place we know all tasks possibly accessing it, are in sync with. (see US6664) mLLContext->resetThreadContexts(); mCCDContext->updateCCD(mDt, continuation, mSimpleIslandManager->getAccurateIslandSim(), (mPublicFlags & PxSceneFlag::eDISABLE_CCD_RESWEEP), mNumFastMovingShapes); } static PX_FORCE_INLINE Sc::ShapeInteraction* getSI(PxvContactManagerTouchEvent& evt) { return reinterpret_cast<Sc::ShapeInteraction*>(evt.getCMTouchEventUserData()); } void Sc::Scene::postCCDPass(PxBaseTask* /*continuation*/) { // - Performs sleep check // - Updates touch flags PxU32 currentPass = mCCDContext->getCurrentCCDPass(); PX_ASSERT(currentPass > 0); // to make sure changes to the CCD pass counting get noticed. For contact reports, 0 means discrete collision phase. int newTouchCount, lostTouchCount, ccdTouchCount; mLLContext->getManagerTouchEventCount(&newTouchCount, &lostTouchCount, &ccdTouchCount); PX_ALLOCA(newTouches, PxvContactManagerTouchEvent, newTouchCount); PX_ALLOCA(lostTouches, PxvContactManagerTouchEvent, lostTouchCount); PX_ALLOCA(ccdTouches, PxvContactManagerTouchEvent, ccdTouchCount); PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); // Note: For contact notifications it is important that the new touch pairs get processed before the lost touch pairs. // This allows to know for sure if a pair of actors lost all touch (see eACTOR_PAIR_LOST_TOUCH). mLLContext->fillManagerTouchEvents(newTouches, newTouchCount, lostTouches, lostTouchCount, ccdTouches, ccdTouchCount); for(PxI32 i=0; i<newTouchCount; ++i) { ShapeInteraction* si = getSI(newTouches[i]); PX_ASSERT(si); mNPhaseCore->managerNewTouch(*si); si->managerNewTouch(currentPass, true, outputs); if (!si->readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) { mSimpleIslandManager->setEdgeConnected(si->getEdgeIndex(), IG::Edge::eCONTACT_MANAGER); } } for(PxI32 i=0; i<lostTouchCount; ++i) { ShapeInteraction* si = getSI(lostTouches[i]); PX_ASSERT(si); if (si->managerLostTouch(currentPass, true, outputs) && !si->readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) addToLostTouchList(si->getShape0().getActor(), si->getShape1().getActor()); mSimpleIslandManager->setEdgeDisconnected(si->getEdgeIndex()); } for(PxI32 i=0; i<ccdTouchCount; ++i) { ShapeInteraction* si = getSI(ccdTouches[i]); PX_ASSERT(si); si->sendCCDRetouch(currentPass, outputs); } checkForceThresholdContactEvents(currentPass); { PxBitMapPinned& changedAABBMgrActorHandles = mAABBManager->getChangedAABBMgActorHandleMap(); for (PxU32 i = 0, s = mCcdBodies.size(); i < s; i++) { BodySim*const body = mCcdBodies[i]; if(i+8 < s) PxPrefetch(mCcdBodies[i+8], 512); PX_ASSERT(body->getBody2World().p.isFinite()); PX_ASSERT(body->getBody2World().q.isFinite()); body->updateCached(&changedAABBMgrActorHandles); } ArticulationCore* const* articList = mArticulations.getEntries(); for(PxU32 i=0;i<mArticulations.size();i++) articList[i]->getSim()->updateCached(&changedAABBMgrActorHandles); } }
26,008
C++
34.924033
305
0.747309
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodyShapeSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScSoftBodyShapeSim.h" #include "ScNPhaseCore.h" #include "ScScene.h" #include "ScSoftBodySim.h" #include "PxsContext.h" #include "BpAABBManager.h" #include "geometry/PxTetrahedronMesh.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::SoftBodyShapeSim::SoftBodyShapeSim(SoftBodySim& softBody) : ShapeSimBase(softBody, NULL), initialTransform(PxVec3(0, 0, 0)), initialScale(1.0f) { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::SoftBodyShapeSim::~SoftBodyShapeSim() { if (isInBroadPhase()) destroyLowLevelVolume(); PX_ASSERT(!isInBroadPhase()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::SoftBodyShapeSim::attachShapeCore(const Sc::ShapeCore* shapeCore) { setCore(shapeCore); createLowLevelVolume(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::SoftBodyShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const { filterAttr = 0; setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eSOFTBODY); filterData = getBodySim().getCore().getSimulationFilterData(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::SoftBodyShapeSim::updateBounds() { Scene& scene = getScene(); PxBounds3 worldBounds = getWorldBounds(); worldBounds.fattenSafe(getContactOffset()); // fatten for fast moving colliders scene.getBoundsArray().setBounds(worldBounds, getElementID()); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); } void Sc::SoftBodyShapeSim::updateBoundsInAABBMgr() { Scene& scene = getScene(); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); scene.getAABBManager()->setGPUStateChanged(); } PxBounds3 Sc::SoftBodyShapeSim::getBounds() const { PxBounds3 bounds = getScene().getBoundsArray().getBounds(getElementID()); return bounds; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::SoftBodyShapeSim::createLowLevelVolume() { PX_ASSERT(getWorldBounds().isFinite()); const PxU32 index = getElementID(); getScene().getBoundsArray().setBounds(getWorldBounds(), index); { const PxU32 group = Bp::FilterGroup::eDYNAMICS_BASE + getActor().getActorID(); const PxU32 type = Bp::FilterType::SOFTBODY; addToAABBMgr(getCore().getContactOffset(), Bp::FilterGroup::Enum((group << BP_FILTERING_TYPE_SHIFT_BIT) | type), Bp::ElementType::eSHAPE); } // PT: TODO: what's the difference between "getContactOffset()" and "getCore().getContactOffset()" above? getScene().updateContactDistance(index, getContactOffset()); PxsTransformCache& cache = getScene().getLowLevelContext()->getTransformCache(); cache.initEntry(index); PxTransform idt(PxIdentity); cache.setTransformCache(idt, 0, index); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::SoftBodyShapeSim::destroyLowLevelVolume() { if (!isInBroadPhase()) return; Sc::Scene& scene = getScene(); PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs(); scene.getNPhaseCore()->onVolumeRemoved(this, PairReleaseFlag::eWAKE_ON_LOST_TOUCH, outputs); removeFromAABBMgr(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PxBounds3 Sc::SoftBodyShapeSim::getWorldBounds() const { const PxTetrahedronMeshGeometry& tetGeom = static_cast<const PxTetrahedronMeshGeometry&>(getCore().getGeometry()); PxTetrahedronMesh* tetMesh = tetGeom.tetrahedronMesh; PxBounds3 bounds = tetMesh->getLocalBounds(); bounds.minimum *= initialScale; bounds.maximum *= initialScale; bounds = PxBounds3::transformFast(initialTransform, bounds); return bounds; } Sc::SoftBodySim& Sc::SoftBodyShapeSim::getBodySim() const { return static_cast<SoftBodySim&>(getActor()); } #endif //PX_SUPPORT_GPU_PHYSX
6,622
C++
39.384146
199
0.581546
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemShapeSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SC_PARTICLESYSTEM_SHAPE_SIM_H #define SC_PARTICLESYSTEM_SHAPE_SIM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXConfig.h" #include "ScElementSim.h" #include "ScShapeSimBase.h" namespace physx { namespace Sc { class ParticleSystemSim; class ParticleSystemShapeCore; /** A collision detection primitive for soft body. */ class ParticleSystemShapeSim : public ShapeSimBase { ParticleSystemShapeSim& operator=(const ParticleSystemShapeSim &); public: ParticleSystemShapeSim(ParticleSystemSim& particleSystem, const ParticleSystemShapeCore* core); virtual ~ParticleSystemShapeSim(); // ElementSim implementation virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const; // ~ElementSim ParticleSystemSim& getBodySim() const; void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; void createLowLevelVolume(); void destroyLowLevelVolume(); }; } // namespace Sc } #endif #endif
2,680
C
34.746666
108
0.745896
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ELEMENT_SIM_H #define SC_ELEMENT_SIM_H #include "PxFiltering.h" #include "PxvConfig.h" #include "ScActorSim.h" #include "ScInteraction.h" #include "BpAABBManager.h" #include "ScObjectIDTracker.h" #include "ScScene.h" namespace physx { namespace Sc { class ElementSimInteraction; // A ElementSim is a part of a ActorSim. It contributes to the activation framework by adding its interactions to the actor. class ElementSim { PX_NOCOPY(ElementSim) public: class ElementInteractionIterator { public: PX_FORCE_INLINE ElementInteractionIterator(const ElementSim& e, PxU32 nbInteractions, Interaction** interactions) : mInteractions(interactions), mInteractionsLast(interactions + nbInteractions), mElement(&e) {} ElementSimInteraction* getNext(); private: Interaction** mInteractions; Interaction** mInteractionsLast; const ElementSim* mElement; }; class ElementInteractionReverseIterator { public: PX_FORCE_INLINE ElementInteractionReverseIterator(const ElementSim& e, PxU32 nbInteractions, Interaction** interactions) : mInteractions(interactions), mInteractionsLast(interactions + nbInteractions), mElement(&e) {} ElementSimInteraction* getNext(); private: Interaction** mInteractions; Interaction** mInteractionsLast; const ElementSim* mElement; }; ElementSim(ActorSim& actor); protected: ~ElementSim(); public: // Get an iterator to the interactions connected to the element // PT: this may seem strange at first glance since the "element interactions" appear to use the "actor interactions". The thing that makes this work is hidden // inside the iterator implementation: it does parse all the actor interactions indeed, but filters out the ones that do not contain "this", i.e. the desired element. // So this is inefficient (parsing potentially many more interactions than needed, imagine in a large compound) but it works, and the iterator has a point - it isn't // just the same as parsing the actor's array. PX_FORCE_INLINE ElementInteractionIterator getElemInteractions() const { return ElementInteractionIterator(*this, mActor.getActorInteractionCount(), mActor.getActorInteractions()); } PX_FORCE_INLINE ElementInteractionReverseIterator getElemInteractionsReverse() const { return ElementInteractionReverseIterator(*this, mActor.getActorInteractionCount(), mActor.getActorInteractions()); } PX_FORCE_INLINE ActorSim& getActor() const { return mActor; } PX_FORCE_INLINE Scene& getScene() const { return mActor.getScene(); } PX_FORCE_INLINE PxU32 getElementID() const { return mElementID; } PX_FORCE_INLINE bool isInBroadPhase() const { return mInBroadPhase; } void addToAABBMgr(PxReal contactDistance, Bp::FilterGroup::Enum group, Bp::ElementType::Enum type); bool removeFromAABBMgr(); PX_FORCE_INLINE void initID() { Scene& scene = getScene(); mElementID = scene.getElementIDPool().createID(); scene.getBoundsArray().initEntry(mElementID); } PX_FORCE_INLINE void releaseID() { getScene().getElementIDPool().releaseID(mElementID); } protected: ActorSim& mActor; PxU32 mElementID : 31; // PT: ID provided by Sc::Scene::mElementIDPool PxU32 mInBroadPhase : 1; public: PxU32 mShapeArrayIndex; }; PX_FORCE_INLINE void setFilterObjectAttributeType(PxFilterObjectAttributes& attr, PxFilterObjectType::Enum type) { PX_ASSERT((attr & (PxFilterObjectType::eMAX_TYPE_COUNT-1)) == 0); attr |= type; } } // namespace Sc } #endif
5,424
C
40.730769
205
0.727692
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationTendonCore.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 "ScArticulationTendonCore.h" #include "ScArticulationTendonSim.h" using namespace physx; void Sc::ArticulationSpatialTendonCore::setStiffness(const PxReal stiffness) { mStiffness = stiffness; if (mSim) mSim->setStiffness(stiffness); } PxReal Sc::ArticulationSpatialTendonCore::getStiffness() const { return mStiffness; } void Sc::ArticulationSpatialTendonCore::setDamping(const PxReal damping) { mDamping = damping; if (mSim) mSim->setDamping(damping); } PxReal Sc::ArticulationSpatialTendonCore::getDamping() const { return mDamping; } void Sc::ArticulationSpatialTendonCore::setLimitStiffness(const PxReal stiffness) { mLimitStiffness = stiffness; if (mSim) mSim->setLimitStiffness(stiffness); } PxReal Sc::ArticulationSpatialTendonCore::getLimitStiffness() const { return mLimitStiffness; } void Sc::ArticulationSpatialTendonCore::setOffset(const PxReal offset) { mOffset = offset; if (mSim) mSim->setOffset(offset); } PxReal Sc::ArticulationSpatialTendonCore::getOffset() const { return mOffset; } ///////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::ArticulationFixedTendonCore::setStiffness(const PxReal stiffness) { mStiffness = stiffness; if (mSim) mSim->setStiffness(stiffness); } PxReal Sc::ArticulationFixedTendonCore::getStiffness() const { return mStiffness; } void Sc::ArticulationFixedTendonCore::setDamping(const PxReal damping) { mDamping = damping; if (mSim) mSim->setDamping(damping); } PxReal Sc::ArticulationFixedTendonCore::getDamping() const { return mDamping; } void Sc::ArticulationFixedTendonCore::setLimitStiffness(const PxReal stiffness) { mLimitStiffness = stiffness; if (mSim) mSim->setLimitStiffness(stiffness); } PxReal Sc::ArticulationFixedTendonCore::getLimitStiffness() const { return mLimitStiffness; } void Sc::ArticulationFixedTendonCore::setSpringRestLength(const PxReal restLength) { mRestLength = restLength; if (mSim) mSim->setSpringRestLength(restLength); } PxReal Sc::ArticulationFixedTendonCore::getSpringRestLength() const { return mRestLength; } void Sc::ArticulationFixedTendonCore::setLimitRange(const PxReal lowLimit, const PxReal highLimit) { mLowLimit = lowLimit; mHighLimit = highLimit; if (mSim) mSim->setLimitRange(lowLimit, highLimit); } void Sc::ArticulationFixedTendonCore::getLimitRange(PxReal& lowLimit, PxReal& highLimit) const { lowLimit = mLowLimit; highLimit = mHighLimit; } void Sc::ArticulationFixedTendonCore::setOffset(const PxReal offset) { mOffset = offset; if (mSim) mSim->setOffset(offset); } PxReal Sc::ArticulationFixedTendonCore::getOffset() const { return mOffset; }
4,389
C++
25.768293
101
0.756209
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodySim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScSoftBodySim.h" #include "ScSoftBodyCore.h" #include "ScScene.h" #include "PxsSimulationController.h" using namespace physx; using namespace physx::Dy; Sc::SoftBodySim::SoftBodySim(SoftBodyCore& core, Scene& scene) : ActorSim(scene, core), mShapeSim(*this) { mLLSoftBody = scene.createLLSoftBody(this); mNodeIndex = scene.getSimpleIslandManager()->addSoftBody(mLLSoftBody, false); scene.getSimpleIslandManager()->activateNode(mNodeIndex); mLLSoftBody->setElementId(mShapeSim.getElementID()); } Sc::SoftBodySim::~SoftBodySim() { if (!mLLSoftBody) return; mScene.destroyLLSoftBody(*mLLSoftBody); mScene.getSimpleIslandManager()->removeNode(mNodeIndex); mCore.setSim(NULL); } void Sc::SoftBodySim::updateBounds() { mShapeSim.updateBounds(); } void Sc::SoftBodySim::updateBoundsInAABBMgr() { mShapeSim.updateBoundsInAABBMgr(); } PxBounds3 Sc::SoftBodySim::getBounds() const { return mShapeSim.getBounds(); } bool Sc::SoftBodySim::isSleeping() const { IG::IslandSim& sim = mScene.getSimpleIslandManager()->getAccurateIslandSim(); return sim.getActiveNodeIndex(mNodeIndex) == PX_INVALID_NODE; } void Sc::SoftBodySim::onSetWakeCounter() { getScene().getSimulationController()->setSoftBodyWakeCounter(mLLSoftBody); if (mLLSoftBody->getCore().wakeCounter > 0.f) getScene().getSimpleIslandManager()->activateNode(mNodeIndex); else getScene().getSimpleIslandManager()->deactivateNode(mNodeIndex); } void Sc::SoftBodySim::attachShapeCore(ShapeCore* core) { mShapeSim.attachShapeCore(core); PxsShapeCore* shapeCore = const_cast<PxsShapeCore*>(&core->getCore()); mLLSoftBody->setShapeCore(shapeCore); } void Sc::SoftBodySim::attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState) { mLLSoftBody->setSimShapeCore(simulationMesh, simulationState); } PxTetrahedronMesh* Sc::SoftBodySim::getSimulationMesh() { return mLLSoftBody->getSimulationMesh(); } PxSoftBodyAuxData* Sc::SoftBodySim::getSoftBodyAuxData() { return mLLSoftBody->getSoftBodyAuxData(); } PxTetrahedronMesh* Sc::SoftBodySim::getCollisionMesh() { return mLLSoftBody->getCollisionMesh(); } void Sc::SoftBodySim::enableSelfCollision() { if (isActive()) { getScene().getSimulationController()->activateSoftbodySelfCollision(mLLSoftBody); } } void Sc::SoftBodySim::disableSelfCollision() { if (isActive()) { getScene().getSimulationController()->deactivateSoftbodySelfCollision(mLLSoftBody); } } /*void Sc::SoftBodySim::activate() { // Activate body //{ // PX_ASSERT((!isKinematic()) || notInScene() || readInternalFlag(InternalFlags(BF_KINEMATIC_MOVED | BF_KINEMATIC_SURFACE_VELOCITY))); // kinematics should only get activated when a target is set. // // exception: object gets newly added, then the state change will happen later // if (!isArticulationLink()) // { // mLLBody.mInternalFlags &= (~PxsRigidBody::eFROZEN); // // Put in list of activated bodies. The list gets cleared at the end of a sim step after the sleep callbacks have been fired. // getScene().onBodyWakeUp(this); // } // BodyCore& core = getBodyCore(); // if (core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) // { // PX_ASSERT(!getScene().isInPosePreviewList(*this)); // getScene().addToPosePreviewList(*this); // } // createSqBounds(); //} activateInteractions(*this); } void Sc::SoftBodySim::deactivate() { deactivateInteractions(*this); // Deactivate body //{ // PX_ASSERT((!isKinematic()) || notInScene() || !readInternalFlag(BF_KINEMATIC_MOVED)); // kinematics should only get deactivated when no target is set. // // exception: object gets newly added, then the state change will happen later // BodyCore& core = getBodyCore(); // if (!readInternalFlag(BF_ON_DEATHROW)) // { // // Set velocity to 0. // // Note: this is also fine if the method gets called because the user puts something to sleep (this behavior is documented in the API) // PX_ASSERT(core.getWakeCounter() == 0.0f); // const PxVec3 zero(0.0f); // core.setLinearVelocityInternal(zero); // core.setAngularVelocityInternal(zero); // setForcesToDefaults(!(mLLBody.mInternalFlags & PxsRigidBody::eDISABLE_GRAVITY)); // } // if (!isArticulationLink()) // Articulations have their own sleep logic. // getScene().onBodySleep(this); // if (core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) // { // PX_ASSERT(getScene().isInPosePreviewList(*this)); // getScene().removeFromPosePreviewList(*this); // } // destroySqBounds(); //} }*/ PxU32 Sc::SoftBodySim::getGpuSoftBodyIndex() const { return mLLSoftBody->getGpuSoftBodyIndex(); } #endif //PX_SUPPORT_GPU_PHYSX
6,345
C++
30.415841
197
0.739007
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationJointCore.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 "ScArticulationJointCore.h" #include "ScArticulationCore.h" #include "ScArticulationSim.h" #include "ScArticulationJointSim.h" #include "ScBodyCore.h" #include "ScPhysics.h" using namespace physx; Sc::ArticulationJointCore::ArticulationJointCore(const PxTransform& parentFrame, const PxTransform& childFrame) : mCore (parentFrame, childFrame), mSim (NULL), mArticulation (NULL), mRootType (NULL), mLLLinkIndex (0xffffffff) { } Sc::ArticulationJointCore::~ArticulationJointCore() { PX_ASSERT(getSim() == 0); } void Sc::ArticulationJointCore::setSimDirty() { Sc::ArticulationJointSim* sim = getSim(); if(sim) sim->setDirty(); ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); llarticulation->mJcalcDirty = true; } } void Sc::ArticulationJointCore::setParentPose(const PxTransform& t) { // AD: we check if it changed at all to avoid marking the complete articulation dirty for a jcalc. // The jcalc internally checks these ArticulationJointCoreDirtyFlag again so we would skip most things // but we'd still check all the joints. The same is also true for the following functions. if (!(mCore.parentPose == t)) { mCore.parentPose = t; setDirty(Dy::ArticulationJointCoreDirtyFlag::eFRAME); } } void Sc::ArticulationJointCore::setChildPose(const PxTransform& t) { if (!(mCore.childPose == t)) { mCore.childPose = t; setDirty(Dy::ArticulationJointCoreDirtyFlag::eFRAME); } } void Sc::ArticulationJointCore::setTargetP(PxArticulationAxis::Enum axis, PxReal targetP) { // this sets the target position in the core. mCore.targetP[axis] = targetP; // this sets the target position in the ll articulation. This needs to happen immediately because we might // look up the value using the cache API again, and that one is reading directly from the llArticulation. ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); Dy::ArticulationData& data = llarticulation->getArticulationData(); Dy::ArticulationJointCoreData* jointData = data.getJointData(); Dy::ArticulationJointCoreData& jointDatum = jointData[mLLLinkIndex]; PxReal* jointTargetPositions = data.getJointTargetPositions(); PxReal* jTargetPosition = &jointTargetPositions[jointDatum.jointOffset]; const PxU32 dofId = mCore.invDofIds[axis]; if (dofId != 0xff) { jTargetPosition[dofId] = targetP; artiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_POS); } } // AD: does not need setDirty - we write directly into the llArticulation and the GPU part is // handled by setArticulationDirty. } void Sc::ArticulationJointCore::setTargetV(PxArticulationAxis::Enum axis, PxReal targetV) { // this sets the target velocity in the core. mCore.targetV[axis] = targetV; // this sets the target velocity in the ll articulation. This needs to happen immediately because we might // look up the value using the cache API again, and that one is reading directly from the llArticulation. ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); Dy::ArticulationData& data = llarticulation->getArticulationData(); Dy::ArticulationJointCoreData* jointData = data.getJointData(); Dy::ArticulationJointCoreData& jointDatum = jointData[mLLLinkIndex]; PxReal* jointTargetVelocities = data.getJointTargetVelocities(); PxReal* jTargetVelocity = &jointTargetVelocities[jointDatum.jointOffset]; const PxU32 dofId = mCore.invDofIds[axis]; if (dofId != 0xff) { jTargetVelocity[dofId] = targetV; artiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_VEL); } } // AD: does not need setDirty - we write directly into the llArticulation and the GPU part is // handled by setArticulationDirty. } void Sc::ArticulationJointCore::setArmature(PxArticulationAxis::Enum axis, PxReal armature) { if (mCore.armature[axis] != armature) { mCore.armature[axis] = armature; setDirty(Dy::ArticulationJointCoreDirtyFlag::eARMATURE); } } void Sc::ArticulationJointCore::setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) { // this sets the position in the core. mCore.jointPos[axis] = jointPos; // this sets the position in the ll articulation. This needs to happen immediately because we might // look up the value using the cache API again, and that one is reading directly from the llArticulation. ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); Dy::ArticulationData& data = llarticulation->getArticulationData(); Dy::ArticulationJointCoreData* jointData = data.getJointData(); Dy::ArticulationJointCoreData& jointDatum = jointData[mLLLinkIndex]; PxReal* jointPositions = data.getJointPositions(); PxReal* jPosition = &jointPositions[jointDatum.jointOffset]; const PxU32 dofId = mCore.invDofIds[axis]; if (dofId != 0xff) { jPosition[dofId] = jointPos; artiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_POSITIONS); } } } // AD: we need this indirection right now because we could have updated joint vel using the cache, so // the read from the joint core might be stale. PxReal Sc::ArticulationJointCore::getJointPosition(PxArticulationAxis::Enum axis) const { PxReal jointPos = mCore.jointPos[axis]; ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { const Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); const Dy::ArticulationData& data = llarticulation->getArticulationData(); const Dy::ArticulationJointCoreData* jointData = data.getJointData(); const Dy::ArticulationJointCoreData& jointDatum = jointData[mLLLinkIndex]; const PxReal* jointPositions = data.getJointPositions(); const PxReal* jPosition = &jointPositions[jointDatum.jointOffset]; const PxU32 dofId = mCore.invDofIds[axis]; if(dofId != 0xff) jointPos = jPosition[dofId]; } return jointPos; } void Sc::ArticulationJointCore::setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) { mCore.jointVel[axis] = jointVel; ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); Dy::ArticulationData& data = llarticulation->getArticulationData(); Dy::ArticulationJointCoreData* jointData = data.getJointData(); Dy::ArticulationJointCoreData& jointDatum = jointData[mLLLinkIndex]; PxReal* jointVelocities = data.getJointVelocities(); PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; const PxU32 dofId = mCore.invDofIds[axis]; if (dofId != 0xff) { jVelocity[dofId] = jointVel; artiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITIES); } } } // AD: we need this indirection right now because we could have updated joint vel using the cache, so // the read from the joint core might be stale. PxReal Sc::ArticulationJointCore::getJointVelocity(PxArticulationAxis::Enum axis) const { PxReal jointVel = mCore.jointVel[axis]; ArticulationSim* artiSim = mArticulation->getSim(); if (artiSim && artiSim->getLLArticulationInitialized()) { const Dy::FeatherstoneArticulation* llarticulation = artiSim->getLowLevelArticulation(); const Dy::ArticulationData& data = llarticulation->getArticulationData(); const Dy::ArticulationJointCoreData* jointData = data.getJointData(); const Dy::ArticulationJointCoreData& jointDatum = jointData[mLLLinkIndex]; const PxReal* jointVelocities = data.getJointVelocities(); const PxReal* jVelocities = &jointVelocities[jointDatum.jointOffset]; const PxU32 dofId = mCore.invDofIds[axis]; if (dofId != 0xff) jointVel = jVelocities[dofId]; } return jointVel; } void Sc::ArticulationJointCore::setLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit) { mCore.initLimit(axis, limit); setSimDirty(); } void Sc::ArticulationJointCore::setDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) { mCore.initDrive(axis, drive); setSimDirty(); }
10,269
C++
35.810036
113
0.765897
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSensorSim.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 "ScArticulationSensorSim.h" #include "ScArticulationSensor.h" #include "PxArticulationReducedCoordinate.h" #include "ScArticulationSim.h" #include "PxArticulationReducedCoordinate.h" namespace physx { Sc::ArticulationSensorSim::ArticulationSensorSim(ArticulationSensorCore& sensorCore, Scene& scene) : mScene(scene), mCore(sensorCore), mLLIndex(0xffffffff) { sensorCore.setSim(this); mLLSensor.mRelativePose = sensorCore.mRelativePose; mLLSensor.mFlags = sensorCore.mFlags; } Sc::ArticulationSensorSim::~ArticulationSensorSim() { mCore.setSim(NULL); } const PxSpatialForce& Sc::ArticulationSensorSim::getForces() const { return mArticulationSim->getSensorForce(mLLIndex); } void Sc::ArticulationSensorSim::setRelativePose(const PxTransform& relativePose) { mLLSensor.mRelativePose = relativePose; mArticulationSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_SENSOR); } void Sc::ArticulationSensorSim::setFlag(const PxU16 flag) { mLLSensor.mFlags = flag; mArticulationSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_SENSOR); } }
2,808
C++
36.959459
102
0.774573
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationTendonSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ARTICULATION_TENDON_SIM_H #define SC_ARTICULATION_TENDON_SIM_H #include "foundation/PxUserAllocated.h" #include "DyArticulationTendon.h" namespace physx { namespace Sc { class ArticulationFixedTendonCore; class ArticulationTendonJointCore; class ArticulationSpatialTendonCore; class ArticulationAttachmentCore; class Scene; class ArticulationJointCore; class ArticulationSim; class ArticulationSpatialTendonSim : public PxUserAllocated { PX_NOCOPY(ArticulationSpatialTendonSim) public: ArticulationSpatialTendonSim(ArticulationSpatialTendonCore& tendon, Scene& scene); virtual ~ArticulationSpatialTendonSim(); void setStiffness(const PxReal stiffness); PxReal getStiffness() const; void setDamping(const PxReal damping); PxReal getDamping() const; void setLimitStiffness(const PxReal stiffness); PxReal getLimitStiffness() const; void setOffset(const PxReal offset); PxReal getOffset() const; void setAttachmentCoefficient(ArticulationAttachmentCore& core, const PxReal coefficient); void setAttachmentRelativeOffset(ArticulationAttachmentCore& core, const PxVec3& offset); void setAttachmentLimits(ArticulationAttachmentCore& core, const PxReal lowLimit, const PxReal highLimit); void setAttachmentRestLength(ArticulationAttachmentCore& core, const PxReal restLength); void addAttachment(ArticulationAttachmentCore& core); void removeAttachment(ArticulationAttachmentCore& core); Dy::ArticulationSpatialTendon mLLTendon; ArticulationSpatialTendonCore& mTendonCore; ArticulationSim* mArtiSim; Scene& mScene; }; class ArticulationFixedTendonSim : public PxUserAllocated { PX_NOCOPY(ArticulationFixedTendonSim) public: ArticulationFixedTendonSim(ArticulationFixedTendonCore& tendon, Scene& scene); virtual ~ArticulationFixedTendonSim(); void setStiffness(const PxReal stiffness); PxReal getStiffness() const; void setDamping(const PxReal damping); PxReal getDamping() const; void setLimitStiffness(const PxReal stiffness); PxReal getLimitStiffness() const; void setOffset(const PxReal offset); PxReal getOffset() const; void setSpringRestLength(const PxReal restLength); PxReal getSpringRestLength() const; void setLimitRange(const PxReal lowLimit, const PxReal highLimit); void getLimitRange(PxReal& lowLimit, PxReal& highLimit) const; void addTendonJoint(ArticulationTendonJointCore& tendonJointCore); void removeTendonJoint(ArticulationTendonJointCore& core); void setTendonJointCoefficient(ArticulationTendonJointCore& core, const PxArticulationAxis::Enum axis, const float coefficient, const float recipCoefficient); Dy::ArticulationFixedTendon mLLTendon; ArticulationFixedTendonCore& mTendonCore; ArticulationSim* mArtiSim; Scene& mScene; }; }//namespace Sc }//namespace physx #endif
4,709
C
36.983871
166
0.763219
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScContactReportBuffer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_CONTACT_REPORT_BUFFER_H #define SC_CONTACT_REPORT_BUFFER_H #include "foundation/Px.h" #include "common/PxProfileZone.h" namespace physx { namespace Sc { class ContactReportBuffer { public: PX_FORCE_INLINE ContactReportBuffer(PxU32 initialSize, bool noResizeAllowed) : mBuffer(NULL) ,mCurrentBufferIndex(0) ,mCurrentBufferSize(initialSize) ,mDefaultBufferSize(initialSize) ,mLastBufferIndex(0) ,mAllocationLocked(noResizeAllowed) { mBuffer = allocateBuffer(initialSize); PX_ASSERT(mBuffer); } ~ContactReportBuffer() { PX_FREE(mBuffer); } PX_FORCE_INLINE void reset(); PX_FORCE_INLINE void flush(); PX_FORCE_INLINE PxU8* allocateNotThreadSafe(PxU32 size, PxU32& index, PxU32 alignment= 16); PX_FORCE_INLINE PxU8* reallocateNotThreadSafe(PxU32 size, PxU32& index, PxU32 alignment= 16, PxU32 lastIndex = 0xFFFFFFFF); PX_FORCE_INLINE PxU8* getData(const PxU32& index) const { return mBuffer+index; } PX_FORCE_INLINE PxU32 getDefaultBufferSize() const {return mDefaultBufferSize;} private: PX_FORCE_INLINE PxU8* allocateBuffer(PxU32 size); private: PxU8* mBuffer; PxU32 mCurrentBufferIndex; PxU32 mCurrentBufferSize; PxU32 mDefaultBufferSize; PxU32 mLastBufferIndex; bool mAllocationLocked; }; } // namespace Sc ////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void Sc::ContactReportBuffer::reset() { mCurrentBufferIndex = 0; mLastBufferIndex = 0xFFFFFFFF; } ////////////////////////////////////////////////////////////////////////// void Sc::ContactReportBuffer::flush() { mCurrentBufferIndex = 0; mLastBufferIndex = 0xFFFFFFFF; if(mCurrentBufferSize != mDefaultBufferSize) { PX_FREE(mBuffer); mBuffer = allocateBuffer(mDefaultBufferSize); PX_ASSERT(mBuffer); mCurrentBufferSize = mDefaultBufferSize; } } ////////////////////////////////////////////////////////////////////////// PxU8* Sc::ContactReportBuffer::allocateNotThreadSafe(PxU32 size, PxU32& index ,PxU32 alignment/* =16 */) { PX_ASSERT(PxIsPowerOfTwo(alignment)); // padding for alignment PxU32 pad = ((mCurrentBufferIndex+alignment-1)&~(alignment-1)) - mCurrentBufferIndex; index = mCurrentBufferIndex + pad; if (index + size > mCurrentBufferSize) { PX_PROFILE_ZONE("ContactReportBuffer::Resize", 0); if(mAllocationLocked) return NULL; PxU32 oldBufferSize = mCurrentBufferSize; while(index + size > mCurrentBufferSize) { mCurrentBufferSize *= 2; } PxU8* tempBuffer = allocateBuffer(mCurrentBufferSize); PxMemCopy(tempBuffer,mBuffer,oldBufferSize); PX_FREE(mBuffer); mBuffer = tempBuffer; } PxU8* ptr = mBuffer + index; mLastBufferIndex = index; PX_ASSERT((size_t(ptr)&(alignment-1)) == 0); mCurrentBufferIndex += size + pad; return ptr; } ////////////////////////////////////////////////////////////////////////// PxU8* Sc::ContactReportBuffer::reallocateNotThreadSafe(PxU32 size, PxU32& index ,PxU32 alignment/* =16 */, PxU32 lastIndex) { if(lastIndex != mLastBufferIndex) { return allocateNotThreadSafe(size,index,alignment); } else { mCurrentBufferIndex = mLastBufferIndex; return allocateNotThreadSafe(size,index,alignment); } } ////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE PxU8* Sc::ContactReportBuffer::allocateBuffer(PxU32 size) { return (static_cast<PxU8*>(PX_ALLOC(size, "ContactReportBuffer"))); } } // namespace physx #endif
5,321
C
29.586207
130
0.674685
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSimBase.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SC_SHAPESIM_BASE_H #define SC_SHAPESIM_BASE_H #include "ScElementSim.h" #include "ScShapeCore.h" #include "ScRigidSim.h" #include "PxsShapeSim.h" namespace physx { namespace Sc { PX_FORCE_INLINE PxU32 isBroadPhase(PxShapeFlags flags) { return PxU32(flags) & PxU32(PxShapeFlag::eTRIGGER_SHAPE | PxShapeFlag::eSIMULATION_SHAPE); } class ShapeCore; // PT: TODO: ShapeSimBase is bonkers: // PxU32 ElementSim::mElementID // PxU32 ElementSim::mShapeArrayIndex; // IG::NodeIndex mLLShape::mBodySimIndex; *** GPU only // PxU32 mLLShape::mElementIndex; *** GPU only, looks like a copy of ElementSim::mElementID // PxU32 mLLShape::mShapeIndex; *** GPU only, looks like a copy of ElementSim::mElementID // PxU32 ShapeSimBase::mId; // PxU32 ShapeSimBase::mSqBoundsId; // => do we really need 7 different IDs per shape? class ShapeSimBase : public ElementSim { PX_NOCOPY(ShapeSimBase) public: ShapeSimBase(ActorSim& owner, const ShapeCore* core) : ElementSim (owner), mSqBoundsId (PX_INVALID_U32), mPrunerIndex(PX_INVALID_U32) { setCore(core); } ~ShapeSimBase() { } PX_FORCE_INLINE void setCore(const ShapeCore* core); PX_FORCE_INLINE const ShapeCore& getCore() const; PX_FORCE_INLINE bool isPxsCoreValid() const { return mLLShape.mShapeCore != NULL; } PX_INLINE PxGeometryType::Enum getGeometryType() const { return getCore().getGeometryType(); } // This is just for getting a reference for the user, so we cast away const-ness PX_INLINE PxShape* getPxShape() const { return const_cast<PxShape*>(getCore().getPxShape()); } PX_FORCE_INLINE PxReal getRestOffset() const { return getCore().getRestOffset(); } PX_FORCE_INLINE PxReal getTorsionalPatchRadius() const { return getCore().getTorsionalPatchRadius(); } PX_FORCE_INLINE PxReal getMinTorsionalPatchRadius() const { return getCore().getMinTorsionalPatchRadius(); } PX_FORCE_INLINE PxU32 getFlags() const { return getCore().getFlags(); } PX_FORCE_INLINE PxReal getContactOffset() const { return getCore().getContactOffset(); } PX_FORCE_INLINE PxU32 getTransformCacheID() const { return getElementID(); } PX_FORCE_INLINE PxU32 getSqBoundsId() const { return mSqBoundsId; } PX_FORCE_INLINE void setSqBoundsId(PxU32 id) { mSqBoundsId = id; } PX_FORCE_INLINE PxU32 getSqPrunerIndex() const { return mPrunerIndex; } PX_FORCE_INLINE void setSqPrunerIndex(PxU32 index) { mPrunerIndex = index; } PX_FORCE_INLINE PxsShapeSim& getLLShapeSim() { return mLLShape; } void onFilterDataChange(); void onRestOffsetChange(); void onFlagChange(PxShapeFlags oldFlags); void onResetFiltering(); void onVolumeOrTransformChange(); void onMaterialChange(); // remove when material properties are gone from PxcNpWorkUnit void onContactOffsetChange(); void markBoundsForUpdate(); void reinsertBroadPhase(); void removeFromBroadPhase(bool wakeOnLostTouch); void getAbsPoseAligned(PxTransform* PX_RESTRICT globalPose) const; PX_FORCE_INLINE RigidSim& getRbSim() const { return static_cast<RigidSim&>(getActor()); } BodySim* getBodySim() const; PxsRigidCore& getPxsRigidCore() const; void createSqBounds(); void destroySqBounds(); void updateCached(PxU32 transformCacheFlags, PxBitMapPinned* shapeChangedMap); void updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray); void updateBPGroup(); protected: PX_FORCE_INLINE void internalAddToBroadPhase(); PX_FORCE_INLINE bool internalRemoveFromBroadPhase(bool wakeOnLostTouch = true); void initSubsystemsDependingOnElementID(); PxsShapeSim mLLShape; PxU32 mSqBoundsId; PxU32 mPrunerIndex; }; #if PX_P64_FAMILY // PT: to compensate for the padding I removed in PxsShapeSim PX_COMPILE_TIME_ASSERT((sizeof(ShapeSimBase) - sizeof(PxsShapeSim))>=12); #else // PX_COMPILE_TIME_ASSERT(32==sizeof(Sc::ShapeSim)); // after removing bounds from shapes // PX_COMPILE_TIME_ASSERT((sizeof(Sc::ShapeSim) % 16) == 0); // aligned mem bounds are better for prefetching #endif PX_FORCE_INLINE void ShapeSimBase::setCore(const ShapeCore* core) { mLLShape.mShapeCore = core ? const_cast<PxsShapeCore*>(&core->getCore()) : NULL; } PX_FORCE_INLINE const ShapeCore& ShapeSimBase::getCore() const { return Sc::ShapeCore::getCore(*mLLShape.mShapeCore); } } // namespace Sc } #endif
6,400
C
43.144827
151
0.69125
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScPipeline.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. // PT: this file contains most Scene functions called during the simulate() call, i.e. the "pipeline" functions. // Ideally they should be listed in the order in which they are called in the single-threaded version, to help // understanding and following the pipeline. #include "ScScene.h" #include "BpBroadPhase.h" #include "ScArticulationSim.h" #include "ScSimStats.h" #include "PxsCCD.h" #if defined(__APPLE__) && defined(__POWERPC__) #include <ppc_intrinsics.h> #endif #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXGpu.h" #include "PxsKernelWrangler.h" #include "PxsHeapMemoryAllocator.h" #include "cudamanager/PxCudaContextManager.h" #endif #include "ScShapeInteraction.h" #include "ScElementInteractionMarker.h" #if PX_SUPPORT_GPU_PHYSX #include "PxSoftBody.h" #include "ScSoftBodySim.h" #include "DySoftBody.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxFEMCloth.h" #include "PxHairSystem.h" #endif #include "ScFEMClothSim.h" #include "DyFEMCloth.h" #include "ScParticleSystemSim.h" #include "DyParticleSystem.h" #include "ScHairSystemSim.h" #include "DyHairSystem.h" #endif using namespace physx; using namespace physx::Cm; using namespace physx::Dy; using namespace Sc; PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// void PxcClearContactCacheStats(); void Sc::Scene::stepSetupCollide(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.stepSetupCollide", mContextId); { PX_PROFILE_ZONE("Sim.prepareCollide", mContextId); mReportShapePairTimeStamp++; // deleted actors/shapes should get separate pair entries in contact reports mContactReportsNeedPostSolverVelocity = false; getRenderBuffer().clear(); // Clear broken constraint list: clearBrokenConstraintBuffer(); visualizeStartStep(); PxcClearContactCacheStats(); } kinematicsSetup(continuation); PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); // Update all dirty interactions mNPhaseCore->updateDirtyInteractions(outputs); mInternalFlags &= ~(SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_DOMINANCE | SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_VISUALIZATION); } void Sc::Scene::simulate(PxReal timeStep, PxBaseTask* continuation) { if(timeStep != 0.0f) { setElapsedTime(timeStep); mDynamicsContext->setDt(timeStep); mAdvanceStep.setContinuation(continuation); stepSetupCollide(&mAdvanceStep); mCollideStep.setContinuation(&mAdvanceStep); mAdvanceStep.removeReference(); mCollideStep.removeReference(); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::collideStep(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.collideQueueTasks", mContextId); PX_PROFILE_START_CROSSTHREAD("Basic.collision", mContextId); mStats->simStart(); mLLContext->beginUpdate(); mPostNarrowPhase.setTaskManager(*continuation->getTaskManager()); mPostNarrowPhase.addReference(); mFinalizationPhase.setTaskManager(*continuation->getTaskManager()); mFinalizationPhase.addReference(); mRigidBodyNarrowPhase.setContinuation(continuation); mPreRigidBodyNarrowPhase.setContinuation(&mRigidBodyNarrowPhase); mUpdateShapes.setContinuation(&mPreRigidBodyNarrowPhase); mRigidBodyNarrowPhase.removeReference(); mPreRigidBodyNarrowPhase.removeReference(); mUpdateShapes.removeReference(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::updateShapes(PxBaseTask* continuation) { //dma shapes data to gpu mSimulationController->updateShapes(continuation); } /////////////////////////////////////////////////////////////////////////////// namespace { class DirtyShapeUpdatesTask : public Cm::Task { public: static const PxU32 MaxShapes = 256; PxsTransformCache& mCache; Bp::BoundsArray& mBoundsArray; ShapeSim* mShapes[MaxShapes]; PxU32 mNbShapes; DirtyShapeUpdatesTask(PxU64 contextID, PxsTransformCache& cache, Bp::BoundsArray& boundsArray) : Cm::Task (contextID), mCache (cache), mBoundsArray(boundsArray), mNbShapes (0) { } virtual void runInternal() { for (PxU32 a = 0; a < mNbShapes; ++a) mShapes[a]->updateCached(mCache, mBoundsArray); } virtual const char* getName() const { return "DirtyShapeUpdatesTask"; } private: PX_NOCOPY(DirtyShapeUpdatesTask) }; } static DirtyShapeUpdatesTask* createDirtyShapeUpdateTask(Cm::FlushPool& pool, PxU64 contextID, PxsTransformCache& cache, Bp::BoundsArray& boundsArray) { return PX_PLACEMENT_NEW(pool.allocate(sizeof(DirtyShapeUpdatesTask)), DirtyShapeUpdatesTask)(contextID, cache, boundsArray); } void Sc::Scene::updateDirtyShapes(PxBaseTask* continuation) { PX_PROFILE_ZONE("Scene.updateDirtyShapes", mContextId); // PT: it is quite unfortunate that we cannot shortcut parsing the bitmaps. We should consider switching to arrays. //Process dirty shapeSims... PxBitMap::Iterator dirtyShapeIter(mDirtyShapeSimMap); PxsTransformCache& cache = mLLContext->getTransformCache(); Bp::BoundsArray& boundsArray = mAABBManager->getBoundsArray(); Cm::FlushPool& pool = mLLContext->getTaskPool(); PxBitMapPinned& changedMap = mAABBManager->getChangedAABBMgActorHandleMap(); DirtyShapeUpdatesTask* task = createDirtyShapeUpdateTask(pool, mContextId, cache, boundsArray); // PT: TASK-CREATION TAG bool hasDirtyShapes = false; PxU32 nbDirtyShapes = 0; PxU32 index; while((index = dirtyShapeIter.getNext()) != PxBitMap::Iterator::DONE) { ShapeSim* shapeSim = reinterpret_cast<ShapeSim*>(mAABBManager->getUserData(index)); if(shapeSim) { hasDirtyShapes = true; changedMap.growAndSet(index); task->mShapes[nbDirtyShapes++] = shapeSim; // PT: consider better load balancing? if(nbDirtyShapes == DirtyShapeUpdatesTask::MaxShapes) { task->mNbShapes = nbDirtyShapes; nbDirtyShapes = 0; startTask(task, continuation); task = createDirtyShapeUpdateTask(pool, mContextId, cache, boundsArray); } } } if(hasDirtyShapes) { //Setting the boundsArray and transform cache as dirty so that they get DMAd to GPU if GPU dynamics and BP are being used respectively. //These bits are no longer set when we update the cached state for actors due to an optimization avoiding setting these dirty bits multiple times. getBoundsArray().setChangedState(); getLowLevelContext()->getTransformCache().setChangedState(); } if(nbDirtyShapes) { task->mNbShapes = nbDirtyShapes; startTask(task, continuation); } // PT: we clear the map but we don't shrink it, bad because we always parse it above mDirtyShapeSimMap.clear(); } void Sc::Scene::preRigidBodyNarrowPhase(PxBaseTask* continuation) { PX_PROFILE_ZONE("Scene.preNarrowPhase", mContextId); updateContactDistances(continuation); updateDirtyShapes(continuation); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::rigidBodyNarrowPhase(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.narrowPhase", mContextId); mCCDPass = 0; mPostBroadPhase3.addDependent(*continuation); mPostBroadPhase2.setContinuation(&mPostBroadPhase3); mPostBroadPhaseCont.setContinuation(&mPostBroadPhase2); mPostBroadPhase.setContinuation(&mPostBroadPhaseCont); mBroadPhase.setContinuation(&mPostBroadPhase); mRigidBodyNPhaseUnlock.setContinuation(continuation); mRigidBodyNPhaseUnlock.addReference(); mUpdateBoundAndShapeTask.addDependent(mBroadPhase); mLLContext->resetThreadContexts(); mLLContext->updateContactManager(mDt, mHasContactDistanceChanged, continuation, &mRigidBodyNPhaseUnlock, &mUpdateBoundAndShapeTask); // Starts update of contact managers mPostBroadPhase3.removeReference(); mPostBroadPhase2.removeReference(); mPostBroadPhaseCont.removeReference(); mPostBroadPhase.removeReference(); mBroadPhase.removeReference(); mUpdateBoundAndShapeTask.removeReference(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::updateBoundsAndShapes(PxBaseTask* /*continuation*/) { //if the scene doesn't use gpu dynamic and gpu broad phase and the user enables the direct API, //the sdk will refuse to create the scene. mSimulationController->updateBoundsAndShapes(*mAABBManager, isDirectGPUAPIInitialized()); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::broadPhase(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.broadPhase", mContextId); /*mProcessLostPatchesTask.setContinuation(&mPostNarrowPhase); mProcessLostPatchesTask.removeReference();*/ #if PX_SUPPORT_GPU_PHYSX gpu_updateBounds(); #endif mCCDBp = false; mBpSecondPass.setContinuation(continuation); mBpFirstPass.setContinuation(&mBpSecondPass); mBpSecondPass.removeReference(); mBpFirstPass.removeReference(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processFoundSolverPatches(PxBaseTask* /*continuation*/) { PxvNphaseImplementationContext* nphase = mLLContext->getNphaseImplementationContext(); mDynamicsContext->processFoundPatches(*mSimpleIslandManager, nphase->getFoundPatchManagers(), nphase->getNbFoundPatchManagers(), nphase->getFoundPatchOutputCounts()); } void Sc::Scene::processLostSolverPatches(PxBaseTask* /*continuation*/) { PxvNphaseImplementationContext* nphase = mLLContext->getNphaseImplementationContext(); mDynamicsContext->processLostPatches(*mSimpleIslandManager, nphase->getFoundPatchManagers(), nphase->getNbFoundPatchManagers(), nphase->getFoundPatchOutputCounts()); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::broadPhaseFirstPass(PxBaseTask* continuation) { PX_PROFILE_ZONE("Basic.broadPhaseFirstPass", mContextId); const PxU32 numCpuTasks = continuation->getTaskManager()->getCpuDispatcher()->getWorkerCount(); mAABBManager->updateBPFirstPass(numCpuTasks, mLLContext->getTaskPool(), mHasContactDistanceChanged, continuation); // AD: we already update the aggregate bounds above, but because we just update all the aggregates all the time, // this should be fine here. The important thing is that we don't mix normal and aggregate bounds in the normal BP. if (isDirectGPUAPIInitialized()) { mSimulationController->mergeChangedAABBMgHandle(); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::broadPhaseSecondPass(PxBaseTask* continuation) { PX_PROFILE_ZONE("Basic.broadPhaseSecondPass", mContextId); mBpUpdate.setContinuation(continuation); mPreIntegrate.setContinuation(&mBpUpdate); mPreIntegrate.removeReference(); mBpUpdate.removeReference(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::preIntegrate(PxBaseTask* continuation) { PX_PROFILE_ZONE("Basic.preIntegrate", mContextId); if (!mCCDBp && isUsingGpuDynamicsOrBp()) mSimulationController->preIntegrateAndUpdateBound(continuation, mGravity, mDt); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::updateBroadPhase(PxBaseTask* continuation) { PX_PROFILE_ZONE("Basic.updateBroadPhase", mContextId); PxBaseTask* rigidBodyNPhaseUnlock = mCCDPass ? NULL : &mRigidBodyNPhaseUnlock; mAABBManager->updateBPSecondPass(&mLLContext->getScratchAllocator(), continuation); // PT: decoupling: I moved this back from updateBPSecondPass //if this is mCCDPass, narrowPhaseUnlockTask will be NULL if(rigidBodyNPhaseUnlock) rigidBodyNPhaseUnlock->removeReference(); if(!mCCDBp && isUsingGpuDynamicsOrBp()) mSimulationController->updateParticleSystemsAndSoftBodies(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::unblockNarrowPhase(PxBaseTask*) { /*if (!mCCDBp && mUseGpuRigidBodies) mSimulationController->updateParticleSystemsAndSoftBodies();*/ // mLLContext->getNphaseImplementationContext()->startNarrowPhaseTasks(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::postBroadPhase(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.postBroadPhase", mContextId); //Notify narrow phase that broad phase has completed mLLContext->getNphaseImplementationContext()->postBroadPhaseUpdateContactManager(continuation); mAABBManager->postBroadPhase(continuation, *getFlushPool()); } /////////////////////////////////////////////////////////////////////////////// class OverlapFilterTask : public Cm::Task { public: static const PxU32 MaxPairs = 512; NPhaseCore* mNPhaseCore; const Bp::AABBOverlap* mPairs; PxU32 mNbToProcess; PxU32 mKeepMap[MaxPairs/32]; FilterInfo* mFinfo; PxU32 mNbToKeep; PxU32 mNbToSuppress; OverlapFilterTask* mNext; OverlapFilterTask(PxU64 contextID, NPhaseCore* nPhaseCore, FilterInfo* fInfo, const Bp::AABBOverlap* pairs, PxU32 nbToProcess) : Cm::Task (contextID), mNPhaseCore (nPhaseCore), mPairs (pairs), mNbToProcess (nbToProcess), mFinfo (fInfo), mNbToKeep (0), mNbToSuppress (0), mNext (NULL) { PxMemZero(mKeepMap, sizeof(mKeepMap)); } virtual void runInternal() { mNPhaseCore->runOverlapFilters( mNbToProcess, mPairs, mFinfo, mNbToKeep, mNbToSuppress, mKeepMap); } virtual const char* getName() const { return "OverlapFilterTask"; } }; void Sc::Scene::finishBroadPhase(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sc::Scene::finishBroadPhase", mContextId); { PX_PROFILE_ZONE("Sim.processNewOverlaps", mContextId); // PT: we process "trigger pairs" immediately, sequentially. Both the filtering and the creation of trigger // interactions happen at the same time in onTriggerOverlapCreated. // PT: could we drop trigger interactions or parallelize this? I am not sure why Kier decided to treat trigger // interactions differently here, in my eyes it is pretty much the same as regular interactions, and they // could have been kept in the same multithreaded pipeline. Regular shape interactions also call "registerInActors" // by default, so the below comment is not very convincing - we worked around this for ShapeInteraction, we // could have worked around this as well for TriggerInteraction. { //KS - these functions call "registerInActors", while OverlapFilterTask reads the list of interactions //in an actor. This could lead to a race condition and a crash if they occur at the same time, so we //serialize these operations PX_PROFILE_ZONE("Sim.processNewOverlaps.createOverlapsNoShapeInteractions", mContextId); { PxU32 createdOverlapCount; const Bp::AABBOverlap* PX_RESTRICT p = mAABBManager->getCreatedOverlaps(Bp::ElementType::eTRIGGER, createdOverlapCount); if(createdOverlapCount) { mLLContext->getSimStats().mNbNewPairs += createdOverlapCount; mNPhaseCore->onTriggerOverlapCreated(p, createdOverlapCount); } } } // PT: for regular shapes the code has been multithreaded and split into different parts, making it harder to follow. // Basically this is the same code as the above for triggers, but scattered over multiple Sc::Scene functions and // tasks. As far as I can tell the steps are: // - "first stage" filtering (right here below) // - "second stage" filtering and creation of ShapeInteractions in preallocateContactManagers // - some cleanup in postBroadPhaseStage2 { PxU32 createdOverlapCount; const Bp::AABBOverlap* PX_RESTRICT p = mAABBManager->getCreatedOverlaps(Bp::ElementType::eSHAPE, createdOverlapCount); // PT: removed this because it's pointless at this stage? if(0) { //We allocate at least 1 element in this array to ensure that the onOverlapCreated functions don't go bang! mPreallocatedContactManagers.reserve(1); mPreallocatedShapeInteractions.reserve(1); mPreallocatedInteractionMarkers.reserve(1); mPreallocatedContactManagers.forceSize_Unsafe(1); mPreallocatedShapeInteractions.forceSize_Unsafe(1); mPreallocatedInteractionMarkers.forceSize_Unsafe(1); } mPreallocateContactManagers.setContinuation(continuation); // PT: this is a temporary member value used to pass the OverlapFilterTasks to the next stage of the pipeline (preallocateContactManagers). // It ideally shouldn't be a class member but just a user-data passed from one task to the next. The task manager doesn't support that though (AFAIK), // so instead it just lies there in Sc::Scene as a class member. It's only used in finishBroadPhase & preallocateContactManagers though. mOverlapFilterTaskHead = NULL; if(createdOverlapCount) { mLLContext->getSimStats().mNbNewPairs += createdOverlapCount; Cm::FlushPool& flushPool = mLLContext->getTaskPool(); // PT: temporary data, similar to mOverlapFilterTaskHead. Will be filled with filter info for each pair by the OverlapFilterTask. mFilterInfo.forceSize_Unsafe(0); mFilterInfo.reserve(createdOverlapCount); mFilterInfo.forceSize_Unsafe(createdOverlapCount); // PT: TASK-CREATION TAG const PxU32 nbPairsPerTask = OverlapFilterTask::MaxPairs; OverlapFilterTask* previousTask = NULL; for(PxU32 a=0; a<createdOverlapCount; a+=nbPairsPerTask) { const PxU32 nbToProcess = PxMin(createdOverlapCount - a, nbPairsPerTask); OverlapFilterTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(OverlapFilterTask)), OverlapFilterTask)(mContextId, mNPhaseCore, mFilterInfo.begin() + a, p + a, nbToProcess); task->setContinuation(&mPreallocateContactManagers); task->removeReference(); // PT: setup a linked-list of OverlapFilterTasks, will be parsed in preallocateContactManagers if(previousTask) previousTask->mNext = task; else mOverlapFilterTaskHead = task; previousTask = task; } } } mPreallocateContactManagers.removeReference(); } } void Sc::Scene::postBroadPhaseContinuation(PxBaseTask* continuation) { mAABBManager->getChangedAABBMgActorHandleMap().clear(); // - Finishes broadphase update // - Adds new interactions (and thereby contact managers if needed) finishBroadPhase(continuation); } /////////////////////////////////////////////////////////////////////////////// template<class T> static PX_FORCE_INLINE T* markPointerAsUsed(T* ptr) { return reinterpret_cast<T*>(size_t(ptr) | 1); } static PX_FORCE_INLINE size_t isPointerMarkedAsUsed(void* ptr) { return size_t(ptr) & 1; } template<class T> static PX_FORCE_INLINE T* getUsedPointer(T* ptr) { const size_t address = size_t(ptr); return address & 1 ? reinterpret_cast<T*>(address & size_t(~1)) : NULL; } namespace { class OnOverlapCreatedTask : public Cm::Task { public: NPhaseCore* mNPhaseCore; const Bp::AABBOverlap* mPairs; const FilterInfo* mFinfo; PxsContactManager** mContactManagers; ShapeInteraction** mShapeInteractions; ElementInteractionMarker** mInteractionMarkers; PxU32 mNbToProcess; OnOverlapCreatedTask(PxU64 contextID, NPhaseCore* nPhaseCore, const Bp::AABBOverlap* pairs, const FilterInfo* fInfo, PxsContactManager** contactManagers, ShapeInteraction** shapeInteractions, ElementInteractionMarker** interactionMarkers, PxU32 nbToProcess) : Cm::Task (contextID), mNPhaseCore (nPhaseCore), mPairs (pairs), mFinfo (fInfo), mContactManagers (contactManagers), mShapeInteractions (shapeInteractions), mInteractionMarkers (interactionMarkers), mNbToProcess (nbToProcess) { } virtual void runInternal() { PxsContactManager** currentCm = mContactManagers; ShapeInteraction** currentSI = mShapeInteractions; ElementInteractionMarker** currentEI = mInteractionMarkers; for(PxU32 i=0; i<mNbToProcess; i++) { const Bp::AABBOverlap& pair = mPairs[i]; ShapeSimBase* s0 = reinterpret_cast<ShapeSimBase*>(pair.mUserData1); ShapeSimBase* s1 = reinterpret_cast<ShapeSimBase*>(pair.mUserData0); ElementSimInteraction* interaction = mNPhaseCore->createRbElementInteraction(mFinfo[i], *s0, *s1, *currentCm, *currentSI, *currentEI, false); if(interaction) { const InteractionType::Enum type = interaction->getType(); if(type == InteractionType::eOVERLAP) { PX_ASSERT(interaction==*currentSI); *currentSI = markPointerAsUsed(*currentSI); currentSI++; if(static_cast<ShapeInteraction*>(interaction)->getContactManager()) { PX_ASSERT(static_cast<ShapeInteraction*>(interaction)->getContactManager()==*currentCm); *currentCm = markPointerAsUsed(*currentCm); currentCm++; } } else if(type == InteractionType::eMARKER) { *currentEI = markPointerAsUsed(*currentEI); currentEI++; } } } } virtual const char* getName() const { return "OnOverlapCreatedTask"; } }; } void Sc::Scene::preallocateContactManagers(PxBaseTask* continuation) { //Iterate over all filter tasks and work out how many pairs we need... PxU32 totalCreatedPairs = 0; PxU32 totalSuppressPairs = 0; OverlapFilterTask* task = mOverlapFilterTaskHead; while(task) { totalCreatedPairs += task->mNbToKeep; totalSuppressPairs += task->mNbToSuppress; task = task->mNext; } { //We allocate at least 1 element in this array to ensure that the onOverlapCreated functions don't go bang! // PT: this has to do with the way we dereference currentCm, currentSI and currentEI in OnOverlapCreatedTask // before we know which type of interaction will be created. That is, we need room for at least one of each type // even if no interaction of that type will be created. // PT: don't we preallocate 2 to 3 times as much memory as needed here then? // PT: also doesn't it mean we're going to allocate & deallocate ALL the interaction markers most of the time? mPreallocatedContactManagers.forceSize_Unsafe(0); mPreallocatedShapeInteractions.forceSize_Unsafe(0); mPreallocatedInteractionMarkers.forceSize_Unsafe(0); mPreallocatedContactManagers.reserve(totalCreatedPairs+1); mPreallocatedShapeInteractions.reserve(totalCreatedPairs+1); mPreallocatedInteractionMarkers.reserve(totalSuppressPairs+1); mPreallocatedContactManagers.forceSize_Unsafe(totalCreatedPairs); mPreallocatedShapeInteractions.forceSize_Unsafe(totalCreatedPairs); mPreallocatedInteractionMarkers.forceSize_Unsafe(totalSuppressPairs); } PxU32 overlapCount; Bp::AABBOverlap* PX_RESTRICT p = mAABBManager->getCreatedOverlaps(Bp::ElementType::eSHAPE, overlapCount); if(!overlapCount) return; struct Local { static void processBatch(const PxU32 createdCurrIdx, PxU32& createdStartIdx, const PxU32 suppressedCurrIdx, PxU32& suppressedStartIdx, const PxU32 batchSize, PxsContext* const context, NPhaseCore* const core, OnOverlapCreatedTask* const createTask, PxBaseTask* const continuation_, PxsContactManager** const cms_, ShapeInteraction** const shapeInter_, ElementInteractionMarker** const markerIter_) { const PxU32 nbToCreate = createdCurrIdx - createdStartIdx; const PxU32 nbToSuppress = suppressedCurrIdx - suppressedStartIdx; context->getContactManagerPool().preallocate(nbToCreate, cms_ + createdStartIdx); for (PxU32 i = 0; i < nbToCreate; ++i) shapeInter_[createdStartIdx + i] = core->mShapeInteractionPool.allocate(); for (PxU32 i = 0; i < nbToSuppress; ++i) markerIter_[suppressedStartIdx + i] = core->mInteractionMarkerPool.allocate(); createdStartIdx = createdCurrIdx; suppressedStartIdx = suppressedCurrIdx; createTask->mNbToProcess = batchSize; startTask(createTask, continuation_); } }; const PxU32 nbPairsPerTask = 256; PxsContactManager** cms = mPreallocatedContactManagers.begin(); ShapeInteraction** shapeInter = mPreallocatedShapeInteractions.begin(); ElementInteractionMarker** markerIter = mPreallocatedInteractionMarkers.begin(); Cm::FlushPool& flushPool = mLLContext->getTaskPool(); FilterInfo* fInfo = mFilterInfo.begin(); // PT: TODO: why do we create the task immediately? Why not create it only when a batch is full? // PT: it's the same pattern as for CCD, kinematics, etc OnOverlapCreatedTask* createTask = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(OnOverlapCreatedTask)), OnOverlapCreatedTask)(mContextId, mNPhaseCore, p, fInfo, cms, shapeInter, markerIter, 0); PxU32 batchSize = 0; PxU32 suppressedStartIdx = 0; PxU32 createdStartIdx = 0; PxU32 suppressedCurrIdx = 0; PxU32 createdCurrIdx = 0; PxU32 currentReadIdx = 0; PxU32 createdOverlapCount = 0; // PT: TASK-CREATION TAG task = mOverlapFilterTaskHead; while(task) { if(task->mNbToKeep || task->mNbToSuppress) { for(PxU32 w = 0; w < (OverlapFilterTask::MaxPairs/32); ++w) { for(PxU32 b = task->mKeepMap[w]; b; b &= b-1) { const PxU32 index = (w<<5) + PxLowestSetBit(b); if(createdOverlapCount < (index + currentReadIdx)) { p[createdOverlapCount] = task->mPairs[index]; fInfo[createdOverlapCount] = task->mFinfo[index]; } createdOverlapCount++; batchSize++; } } suppressedCurrIdx += task->mNbToSuppress; createdCurrIdx += task->mNbToKeep; if(batchSize >= nbPairsPerTask) { Local::processBatch(createdCurrIdx, createdStartIdx, suppressedCurrIdx, suppressedStartIdx, batchSize, mLLContext, mNPhaseCore, createTask, continuation, cms, shapeInter, markerIter); createTask = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(OnOverlapCreatedTask)), OnOverlapCreatedTask)(mContextId, mNPhaseCore, p + createdOverlapCount, fInfo + createdOverlapCount, cms + createdStartIdx, shapeInter + createdStartIdx, markerIter + suppressedStartIdx, 0); batchSize = 0; } } currentReadIdx += OverlapFilterTask::MaxPairs; task = task->mNext; } if(batchSize) Local::processBatch(createdCurrIdx, createdStartIdx, suppressedCurrIdx, suppressedStartIdx, batchSize, mLLContext, mNPhaseCore, createTask, continuation, cms, shapeInter, markerIter); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processLostTouchPairs() { PX_PROFILE_ZONE("Sc::Scene::processLostTouchPairs", mContextId); const PxU32 nb = mLostTouchPairs.size(); const SimpleBodyPair* pairs = mLostTouchPairs.begin(); for(PxU32 i=0; i<nb; ++i) { ActorSim* body1 = pairs[i].body1; ActorSim* body2 = pairs[i].body2; // If one has been deleted, we wake the other one const PxIntBool deletedBody1 = mLostTouchPairsDeletedBodyIDs.boundedTest(pairs[i].body1ID); const PxIntBool deletedBody2 = mLostTouchPairsDeletedBodyIDs.boundedTest(pairs[i].body2ID); if(deletedBody1 || deletedBody2) { if(!deletedBody1) body1->internalWakeUp(); if(!deletedBody2) body2->internalWakeUp(); continue; } const bool b1Active = body1->isActive(); const bool b2Active = body2->isActive(); // If both are sleeping, we let them sleep // (for example, two sleeping objects touch and the user teleports one (without waking it up)) if(!b1Active && !b2Active) continue; // If only one has fallen asleep, we wake them both if(!b1Active || !b2Active) { body1->internalWakeUp(); body2->internalWakeUp(); } } mLostTouchPairs.clear(); mLostTouchPairsDeletedBodyIDs.clear(); } void Sc::Scene::postBroadPhaseStage2(PxBaseTask* continuation) { // - Wakes actors that lost touch if appropriate processLostTouchPairs(); mIslandInsertion.setContinuation(continuation); mRegisterContactManagers.setContinuation(continuation); mRegisterInteractions.setContinuation(continuation); mRegisterSceneInteractions.setContinuation(continuation); mIslandInsertion.removeReference(); mRegisterContactManagers.removeReference(); mRegisterInteractions.removeReference(); mRegisterSceneInteractions.removeReference(); //Release unused Cms back to the pool (later, this needs to be done in a thread-safe way from multiple worker threads { PX_PROFILE_ZONE("Sim.processNewOverlaps.release", mContextId); { PxU32 nb = mPreallocatedContactManagers.size(); PxsContactManager** managers = mPreallocatedContactManagers.begin(); Cm::PoolList<PxsContactManager, PxsContext>& pool = mLLContext->getContactManagerPool(); while(nb--) { PxsContactManager* current = *managers++; if(!isPointerMarkedAsUsed(current)) pool.put(current); } } { PxU32 nb = mPreallocatedShapeInteractions.size(); ShapeInteraction** interactions = mPreallocatedShapeInteractions.begin(); PxPool<ShapeInteraction>& pool = mNPhaseCore->mShapeInteractionPool; while(nb--) { ShapeInteraction* current = *interactions++; if(!isPointerMarkedAsUsed(current)) pool.deallocate(current); } } { PxU32 nb = mPreallocatedInteractionMarkers.size(); ElementInteractionMarker** interactions = mPreallocatedInteractionMarkers.begin(); PxPool<ElementInteractionMarker>& pool = mNPhaseCore->mInteractionMarkerPool; while(nb--) { ElementInteractionMarker* current = *interactions++; if(!isPointerMarkedAsUsed(current)) pool.deallocate(current); } } } } /////////////////////////////////////////////////////////////////////////////// // PT: islandInsertion / registerContactManagers / registerInteractions / registerSceneInteractions run in parallel void Sc::Scene::islandInsertion(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sim.processNewOverlaps.islandInsertion", mContextId); const PxU32 nbShapeIdxCreated = mPreallocatedShapeInteractions.size(); for(PxU32 a = 0; a < nbShapeIdxCreated; ++a) { ShapeInteraction* interaction = getUsedPointer(mPreallocatedShapeInteractions[a]); if(interaction) { PxsContactManager* contactManager = const_cast<PxsContactManager*>(interaction->getContactManager()); const ActorSim& bs0 = interaction->getShape0().getActor(); const ActorSim& bs1 = interaction->getShape1().getActor(); const PxActorType::Enum actorTypeLargest = PxMax(bs0.getActorType(), bs1.getActorType()); PxNodeIndex nodeIndexB; if (!bs1.isStaticRigid()) nodeIndexB = bs1.getNodeIndex(); IG::Edge::EdgeType type = IG::Edge::eCONTACT_MANAGER; #if PX_SUPPORT_GPU_PHYSX if(actorTypeLargest == PxActorType::eSOFTBODY) type = IG::Edge::eSOFT_BODY_CONTACT; else if (actorTypeLargest == PxActorType::eFEMCLOTH) type = IG::Edge::eFEM_CLOTH_CONTACT; else if(isParticleSystem(actorTypeLargest)) type = IG::Edge::ePARTICLE_SYSTEM_CONTACT; else if (actorTypeLargest == PxActorType::eHAIRSYSTEM) type = IG::Edge::eHAIR_SYSTEM_CONTACT; #endif IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(contactManager, bs0.getNodeIndex(), nodeIndexB, interaction, type); interaction->mEdgeIndex = edgeIdx; if(contactManager) contactManager->getWorkUnit().mEdgeIndex = edgeIdx; //If it is a soft body or particle overlap, treat it as a contact for now (we can hook up touch found/lost events later maybe) if(actorTypeLargest > PxActorType::eARTICULATION_LINK) mSimpleIslandManager->setEdgeConnected(edgeIdx, type); } } // - Wakes actors that lost touch if appropriate //processLostTouchPairs(); if(mCCDPass == 0) mSimpleIslandManager->firstPassIslandGen(); } /////////////////////////////////////////////////////////////////////////////// // PT: islandInsertion / registerContactManagers / registerInteractions / registerSceneInteractions run in parallel void Sc::Scene::registerContactManagers(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sim.processNewOverlaps.registerCms", mContextId); // PT: we sometimes iterate over this array in vain (all ptrs are unused). Would be better // to store used pointers maybe in the overlap created tasks, and reuse these tasks here to // process only used pointers. PxvNphaseImplementationContext* nphaseContext = mLLContext->getNphaseImplementationContext(); nphaseContext->lock(); //nphaseContext->registerContactManagers(mPreallocatedContactManagers.begin(), mPreallocatedContactManagers.size(), mLLContext->getContactManagerPool().getMaxUsedIndex()); const PxU32 nbCmsCreated = mPreallocatedContactManagers.size(); for(PxU32 a = 0; a < nbCmsCreated; ++a) { PxsContactManager* cm = getUsedPointer(mPreallocatedContactManagers[a]); if(cm) { ShapeInteraction* interaction = getUsedPointer(mPreallocatedShapeInteractions[a]); nphaseContext->registerContactManager(cm, interaction, 0, 0); } } nphaseContext->unlock(); } /////////////////////////////////////////////////////////////////////////////// // PT: islandInsertion / registerContactManagers / registerInteractions / registerSceneInteractions run in parallel void Sc::Scene::registerInteractions(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sim.processNewOverlaps.registerInteractions", mContextId); const PxU32 nbShapeIdxCreated = mPreallocatedShapeInteractions.size(); for(PxU32 a = 0; a < nbShapeIdxCreated; ++a) { ShapeInteraction* interaction = getUsedPointer(mPreallocatedShapeInteractions[a]); if(interaction) { // PT: this is similar to interaction->registerInActors(), which is usually called from // interaction ctors. ActorSim& actorSim0 = interaction->getActorSim0(); ActorSim& actorSim1 = interaction->getActorSim1(); actorSim0.registerInteractionInActor(interaction); actorSim1.registerInteractionInActor(interaction); // PT: the number of counted interactions is used for the sleeping system if(actorSim0.isDynamicRigid()) static_cast<BodySim*>(&actorSim0)->registerCountedInteraction(); if(actorSim1.isDynamicRigid()) static_cast<BodySim*>(&actorSim1)->registerCountedInteraction(); } } const PxU32 nbMarkersCreated = mPreallocatedInteractionMarkers.size(); for(PxU32 a = 0; a < nbMarkersCreated; ++a) { ElementInteractionMarker* interaction = getUsedPointer(mPreallocatedInteractionMarkers[a]); if(interaction) { // PT: no call to "interaction->onActivate()" here because it doesn't do anything interaction->registerInActors(); } } } /////////////////////////////////////////////////////////////////////////////// // PT: islandInsertion / registerContactManagers / registerInteractions / registerSceneInteractions run in parallel void Sc::Scene::registerSceneInteractions(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sim.processNewOverlaps.registerInteractionsScene", mContextId); const PxU32 nbShapeIdxCreated = mPreallocatedShapeInteractions.size(); for(PxU32 a = 0; a < nbShapeIdxCreated; ++a) { ShapeInteraction* interaction = getUsedPointer(mPreallocatedShapeInteractions[a]); if(interaction) { registerInteraction(interaction, interaction->getContactManager() != NULL); const PxsContactManager* cm = interaction->getContactManager(); if(cm) mLLContext->setActiveContactManager(cm, cm->getCCD()); } } const PxU32 nbInteractionMarkers = mPreallocatedInteractionMarkers.size(); for(PxU32 a = 0; a < nbInteractionMarkers; ++a) { ElementInteractionMarker* interaction = getUsedPointer(mPreallocatedInteractionMarkers[a]); if(interaction) registerInteraction(interaction, false); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::finishBroadPhaseStage2(PxU32 ccdPass) { PX_PROFILE_ZONE("Sc::Scene::finishBroadPhase2", mContextId); Bp::AABBManagerBase* aabbMgr = mAABBManager; PxU32 nbLostPairs = 0; for(PxU32 i=0; i<Bp::ElementType::eCOUNT; i++) { PxU32 destroyedOverlapCount; aabbMgr->getDestroyedOverlaps(Bp::ElementType::Enum(i), destroyedOverlapCount); nbLostPairs += destroyedOverlapCount; } mLLContext->getSimStats().mNbLostPairs += nbLostPairs; // PT: TODO: move this to ccd file? //KS - we need to defer processing lost overlaps until later! if (ccdPass) { PX_PROFILE_ZONE("Sim.processLostOverlaps", mContextId); PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); PxU32 destroyedOverlapCount; // PT: for regular shapes { Bp::AABBOverlap* PX_RESTRICT p = aabbMgr->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { ElementSim* volume0 = reinterpret_cast<ElementSim*>(p->mUserData0); ElementSim* volume1 = reinterpret_cast<ElementSim*>(p->mUserData1); //KS - this is a bit ugly. We split the "onOverlapRemoved" for shape interactions to parallelize it and that means //that we have to call each of the individual stages of the remove here. //First, we have to get the interaction pointer... ElementSimInteraction* interaction = mNPhaseCore->findInteraction(volume0, volume1); p->mPairUserData = interaction; if(interaction) { if(interaction->getType() == InteractionType::eOVERLAP || interaction->getType() == InteractionType::eMARKER) { //If it's a standard "overlap" interaction, we have to send a lost touch report, unregister it, and destroy its manager and island gen data. if(interaction->getType() == InteractionType::eOVERLAP) { ShapeInteraction* si = static_cast<ShapeInteraction*>(interaction); mNPhaseCore->lostTouchReports(si, PxU32(PairReleaseFlag::eWAKE_ON_LOST_TOUCH), NULL, 0, outputs); //We must check to see if we have a contact manager here. There is an edge case where actors could be put to //sleep after discrete simulation, prior to CCD, causing their contactManager() to be destroyed. If their bounds //also ceased overlapping, then this code will try to destroy the manager again. if(si->getContactManager()) si->destroyManager(); si->clearIslandGenData(); } unregisterInteraction(interaction); } //Then call "onOverlapRemoved" to actually free the interaction mNPhaseCore->onOverlapRemoved(volume0, volume1, ccdPass, interaction, outputs); } p++; } } // PT: for triggers { Bp::AABBOverlap* PX_RESTRICT p = aabbMgr->getDestroyedOverlaps(Bp::ElementType::eTRIGGER, destroyedOverlapCount); while(destroyedOverlapCount--) { ElementSim* volume0 = reinterpret_cast<ElementSim*>(p->mUserData0); ElementSim* volume1 = reinterpret_cast<ElementSim*>(p->mUserData1); p->mPairUserData = NULL; //KS - this is a bit ugly. mNPhaseCore->onOverlapRemoved(volume0, volume1, ccdPass, NULL, outputs); p++; } } } // - Wakes actors that lost touch if appropriate processLostTouchPairs(); if (ccdPass) aabbMgr->freeBuffers(); } void Sc::Scene::postBroadPhaseStage3(PxBaseTask* /*continuation*/) { finishBroadPhaseStage2(0); PX_PROFILE_STOP_CROSSTHREAD("Basic.postBroadPhase", mContextId); PX_PROFILE_STOP_CROSSTHREAD("Basic.broadPhase", mContextId); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::advanceStep(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.solveQueueTasks", mContextId); if(mDt != 0.0f) { mFinalizationPhase.addDependent(*continuation); mFinalizationPhase.removeReference(); if(mPublicFlags & PxSceneFlag::eENABLE_CCD) { mUpdateCCDMultiPass.setContinuation(&mFinalizationPhase); mAfterIntegration.setContinuation(&mUpdateCCDMultiPass); mUpdateCCDMultiPass.removeReference(); } else { mAfterIntegration.setContinuation(&mFinalizationPhase); } mPostSolver.setContinuation(&mAfterIntegration); mUpdateSimulationController.setContinuation(&mPostSolver); mUpdateDynamics.setContinuation(&mUpdateSimulationController); mUpdateBodies.setContinuation(&mUpdateDynamics); mSolver.setContinuation(&mUpdateBodies); mPostIslandGen.setContinuation(&mSolver); mIslandGen.setContinuation(&mPostIslandGen); mPostNarrowPhase.addDependent(mIslandGen); mPostNarrowPhase.removeReference(); mSecondPassNarrowPhase.setContinuation(&mPostNarrowPhase); mFinalizationPhase.removeReference(); mAfterIntegration.removeReference(); mPostSolver.removeReference(); mUpdateSimulationController.removeReference(); mUpdateDynamics.removeReference(); mUpdateBodies.removeReference(); mSolver.removeReference(); mPostIslandGen.removeReference(); mIslandGen.removeReference(); mPostNarrowPhase.removeReference(); mSecondPassNarrowPhase.removeReference(); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::activateEdgesInternal(const IG::EdgeIndex* activatingEdges, const PxU32 nbActivatingEdges) { const IG::IslandSim& speculativeSim = mSimpleIslandManager->getSpeculativeIslandSim(); for(PxU32 i = 0; i < nbActivatingEdges; ++i) { Interaction* interaction = mSimpleIslandManager->getInteraction(activatingEdges[i]); if(interaction && !interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)) { if(speculativeSim.getEdge(activatingEdges[i]).isActive()) { const bool proceed = activateInteraction(interaction, NULL); if(proceed && (interaction->getType() < InteractionType::eTRACKED_IN_SCENE_COUNT)) notifyInteractionActivated(interaction); } } } } void Sc::Scene::secondPassNarrowPhase(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sim.secondPassNarrowPhase", mContextId); { PX_PROFILE_ZONE("Sim.postIslandGen", mContextId); mSimpleIslandManager->additionalSpeculativeActivation(); // wake interactions { PX_PROFILE_ZONE("ScScene.wakeInteractions", mContextId); const IG::IslandSim& speculativeSim = mSimpleIslandManager->getSpeculativeIslandSim(); //KS - only wake contact managers based on speculative state to trigger contact gen. Waking actors based on accurate state //should activate and joints. { //Wake speculatively based on rigid contacts, soft contacts and particle contacts activateEdgesInternal(speculativeSim.getActivatedEdges(IG::Edge::eCONTACT_MANAGER), speculativeSim.getNbActivatedEdges(IG::Edge::eCONTACT_MANAGER)); #if PX_SUPPORT_GPU_PHYSX activateEdgesInternal(speculativeSim.getActivatedEdges(IG::Edge::eSOFT_BODY_CONTACT), speculativeSim.getNbActivatedEdges(IG::Edge::eSOFT_BODY_CONTACT)); activateEdgesInternal(speculativeSim.getActivatedEdges(IG::Edge::eFEM_CLOTH_CONTACT), speculativeSim.getNbActivatedEdges(IG::Edge::eFEM_CLOTH_CONTACT)); activateEdgesInternal(speculativeSim.getActivatedEdges(IG::Edge::ePARTICLE_SYSTEM_CONTACT), speculativeSim.getNbActivatedEdges(IG::Edge::ePARTICLE_SYSTEM_CONTACT)); activateEdgesInternal(speculativeSim.getActivatedEdges(IG::Edge::eHAIR_SYSTEM_CONTACT), speculativeSim.getNbActivatedEdges(IG::Edge::eHAIR_SYSTEM_CONTACT)); #endif } } } mLLContext->secondPassUpdateContactManager(mDt, &mPostNarrowPhase); // Starts update of contact managers } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::releaseConstraints(bool endOfScene) { PX_ASSERT(mLLContext); if(mEnableStabilization) { //If stabilization is enabled, we're caching contacts for next frame if(!endOfScene) { //So we only clear memory (flip buffers) when not at the end-of-scene. //This means we clear after narrow phase completed so we can //release the previous frame's contact buffers before we enter the solve phase. mLLContext->getNpMemBlockPool().releaseContacts(); } } else if(endOfScene) { //We now have a double-buffered pool of mem blocks so we must //release both pools (which actually triggers the memory used this //frame to be released mLLContext->getNpMemBlockPool().releaseContacts(); mLLContext->getNpMemBlockPool().releaseContacts(); } } void Sc::Scene::postNarrowPhase(PxBaseTask* /*continuation*/) { setCollisionPhaseToInactive(); mHasContactDistanceChanged = false; mLLContext->fetchUpdateContactManager(); //Sync on contact gen results! if(!mCCDBp && isUsingGpuDynamicsOrBp()) mSimulationController->sortContacts(); releaseConstraints(false); PX_PROFILE_STOP_CROSSTHREAD("Basic.narrowPhase", mContextId); PX_PROFILE_STOP_CROSSTHREAD("Basic.collision", mContextId); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processNarrowPhaseTouchEvents() { PX_PROFILE_ZONE("Sim.preIslandGen", mContextId); PxsContext* context = mLLContext; // Update touch states from LL PxU32 newTouchCount, lostTouchCount; PxU32 ccdTouchCount = 0; { PX_PROFILE_ZONE("Sim.preIslandGen.managerTouchEvents", mContextId); context->getManagerTouchEventCount(reinterpret_cast<PxI32*>(&newTouchCount), reinterpret_cast<PxI32*>(&lostTouchCount), NULL); //PX_ALLOCA(newTouches, PxvContactManagerTouchEvent, newTouchCount); //PX_ALLOCA(lostTouches, PxvContactManagerTouchEvent, lostTouchCount); mTouchFoundEvents.forceSize_Unsafe(0); mTouchFoundEvents.reserve(newTouchCount); mTouchFoundEvents.forceSize_Unsafe(newTouchCount); mTouchLostEvents.forceSize_Unsafe(0); mTouchLostEvents.reserve(lostTouchCount); mTouchLostEvents.forceSize_Unsafe(lostTouchCount); context->fillManagerTouchEvents(mTouchFoundEvents.begin(), reinterpret_cast<PxI32&>(newTouchCount), mTouchLostEvents.begin(), reinterpret_cast<PxI32&>(lostTouchCount), NULL, reinterpret_cast<PxI32&>(ccdTouchCount)); mTouchFoundEvents.forceSize_Unsafe(newTouchCount); mTouchLostEvents.forceSize_Unsafe(lostTouchCount); } context->getSimStats().mNbNewTouches = newTouchCount; context->getSimStats().mNbLostTouches = lostTouchCount; } void Sc::Scene::islandGen(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sc::Scene::islandGen", mContextId); //mLLContext->runModifiableContactManagers(); //KS - moved here so that we can get up-to-date touch found/lost events in IG processNarrowPhaseTouchEvents(); // PT: could we merge processNarrowPhaseTouchEventsStage2 with processNarrowPhaseTouchEvents ? mProcessFoundPatchesTask.setContinuation(continuation); mProcessLostPatchesTask.setContinuation(&mProcessFoundPatchesTask); mProcessLostPatchesTask.removeReference(); mProcessFoundPatchesTask.removeReference(); // extracting information for the contact callbacks must happen before the solver writes the post-solve // velocities and positions into the solver bodies processNarrowPhaseTouchEventsStage2(&mUpdateDynamics); } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE ShapeInteraction* getSI(PxvContactManagerTouchEvent& evt) { return reinterpret_cast<ShapeInteraction*>(evt.getCMTouchEventUserData()); } namespace { class InteractionNewTouchTask : public Cm::Task { PxvContactManagerTouchEvent* mEvents; const PxU32 mNbEvents; PxsContactManagerOutputIterator mOutputs; NPhaseCore* mNphaseCore; public: InteractionNewTouchTask(PxU64 contextID, PxvContactManagerTouchEvent* events, PxU32 nbEvents, PxsContactManagerOutputIterator& outputs, NPhaseCore* nPhaseCore) : Cm::Task (contextID), mEvents (events), mNbEvents (nbEvents), mOutputs (outputs), mNphaseCore (nPhaseCore) { } virtual const char* getName() const { return "InteractionNewTouchTask"; } virtual void runInternal() { mNphaseCore->lockReports(); for(PxU32 i = 0; i < mNbEvents; ++i) { ShapeInteraction* si = getSI(mEvents[i]); PX_ASSERT(si); mNphaseCore->managerNewTouch(*si); si->managerNewTouch(0, true, mOutputs); } mNphaseCore->unlockReports(); } private: PX_NOCOPY(InteractionNewTouchTask) }; } void Sc::Scene::processNarrowPhaseTouchEventsStage2(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sc::Scene::processNarrowPhaseTouchEventsStage2", mContextId); PxvNphaseImplementationContext* ctx = mLLContext->getNphaseImplementationContext(); PxsContactManagerOutputIterator outputs = ctx->getContactManagerOutputs(); const PxU32 newTouchCount = mTouchFoundEvents.size(); { Cm::FlushPool& flushPool = mLLContext->getTaskPool(); // PT: why not a delegate task here? We seem to be creating a single InteractionNewTouchTask ? InteractionNewTouchTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(InteractionNewTouchTask)), InteractionNewTouchTask)(mContextId, mTouchFoundEvents.begin(), newTouchCount, outputs, mNPhaseCore); startTask(task, continuation); } /*{ PX_PROFILE_ZONE("Sim.preIslandGen.newTouchesInteraction", mContextId); for (PxU32 i = 0; i < newTouchCount; ++i) { ShapeInteraction* si = reinterpret_cast<ShapeInteraction*>(mTouchFoundEvents[i].userData); PX_ASSERT(si); mNPhaseCore->managerNewTouch(*si); si->managerNewTouch(0, true, outputs, useAdaptiveForce); } }*/ } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::postIslandGen(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.postIslandGen", mContextId); // // Trigger overlap processing (1) shall run in parallel with some parts of island // management (2) (connecting edges, running second island gen pass, object activation...) // For this to work without clashes, the work has to be split into pieces. Things to // keep in mind: // // (1) can deactivate trigger pairs while (2) can activate trigger pairs (both might // happen for the same pair). The active interaction tracking arrays are not thread safe // (Sc::Scene::notifyInteractionDeactivated, ::notifyInteractionActivated) plus the // natural order is to process activation first (deactivation should be based on the // state after activation). Thus, (1) is split into a part (1a) that does the overlap checks // and a part (1b) that checks if trigger pairs can be deactivated. (1a) will run in parallel // with (2). (1b) will run after (2). // Leaves the question of what happens to the trigger pairs activated in (2)? Should those // not get overlap processing too? The rational for why this does not seem necessary is: // If a trigger interaction is activated, then it was inactive before. If inactive, the // overlap state can not have changed since the end of last sim step, unless: // - the user changed the position of one of the invovled actors or shapes // - the user changed the geometry of one of the involved shapes // - the pair is new // However, for all these cases, the trigger interaction is marked in a way that enforces // processing and the interaction gets activated too. // PxBaseTask* setEdgesConnectedContinuationTask = continuation; PxBaseTask* concludingTriggerTask = mNPhaseCore->prepareForTriggerInteractionProcessing(continuation); if (concludingTriggerTask) { setEdgesConnectedContinuationTask = concludingTriggerTask; } mSetEdgesConnectedTask.setContinuation(setEdgesConnectedContinuationTask); mSetEdgesConnectedTask.removeReference(); // - Performs collision detection for trigger interactions if (concludingTriggerTask) { mNPhaseCore->processTriggerInteractions(*concludingTriggerTask); concludingTriggerTask->removeReference(); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::setEdgesConnected(PxBaseTask*) { PX_PROFILE_ZONE("Sim.preIslandGen.islandTouches", mContextId); { PX_PROFILE_ZONE("Sim.preIslandGen.setEdgesConnected", mContextId); const PxU32 newTouchCount = mTouchFoundEvents.size(); for(PxU32 i = 0; i < newTouchCount; ++i) { ShapeInteraction* si = getSI(mTouchFoundEvents[i]); // jcarius: defensive coding for OM-99507. If this assert hits, you maybe hit the same issue, please report! if(si == NULL || si->getEdgeIndex() == IG_INVALID_EDGE) { outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "Sc::Scene::setEdgesConnected: adding an invalid edge. Skipping."); PX_ALWAYS_ASSERT(); continue; } if(!si->readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) mSimpleIslandManager->setEdgeConnected(si->getEdgeIndex(), IG::Edge::eCONTACT_MANAGER); } } mSimpleIslandManager->secondPassIslandGen(); wakeObjectsUp(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::solver(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.rigidBodySolver", mContextId); //Update forces per body in parallel. This can overlap with the other work in this phase. beforeSolver(continuation); PX_PROFILE_ZONE("Sim.postNarrowPhaseSecondPass", mContextId); //Narrowphase is completely finished so the streams can be swapped. mLLContext->swapStreams(); //PxsContactManagerOutputIterator outputs = this->mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); //mNPhaseCore->processPersistentContactEvents(outputs, continuation); } /////////////////////////////////////////////////////////////////////////////// namespace { class ScBeforeSolverTask : public Cm::Task { public: static const PxU32 MaxBodiesPerTask = 256; PxNodeIndex mBodies[MaxBodiesPerTask]; PxU32 mNumBodies; const PxReal mDt; IG::SimpleIslandManager* mIslandManager; PxsSimulationController* mSimulationController; public: ScBeforeSolverTask(PxReal dt, IG::SimpleIslandManager* islandManager, PxsSimulationController* simulationController, PxU64 contextID) : Cm::Task (contextID), mDt (dt), mIslandManager (islandManager), mSimulationController (simulationController) { } virtual void runInternal() { PX_PROFILE_ZONE("Sim.ScBeforeSolverTask", mContextID); const IG::IslandSim& islandSim = mIslandManager->getAccurateIslandSim(); const PxU32 rigidBodyOffset = BodySim::getRigidBodyOffset(); PxsRigidBody* updatedBodySims[MaxBodiesPerTask]; PxU32 updatedBodyNodeIndices[MaxBodiesPerTask]; PxU32 nbUpdatedBodySims = 0; PxU32 nb = mNumBodies; const PxNodeIndex* bodies = mBodies; while(nb--) { const PxNodeIndex index = *bodies++; if(islandSim.getActiveNodeIndex(index) != PX_INVALID_NODE) { if(islandSim.getNode(index).mType == IG::Node::eRIGID_BODY_TYPE) { PxsRigidBody* body = islandSim.getRigidBody(index); BodySim* bodySim = reinterpret_cast<BodySim*>(reinterpret_cast<PxU8*>(body) - rigidBodyOffset); bodySim->updateForces(mDt, updatedBodySims, updatedBodyNodeIndices, nbUpdatedBodySims, NULL); } } } if(nbUpdatedBodySims) mSimulationController->updateBodies(updatedBodySims, updatedBodyNodeIndices, nbUpdatedBodySims); } virtual const char* getName() const { return "ScScene.beforeSolver"; } private: PX_NOCOPY(ScBeforeSolverTask) }; class ScArticBeforeSolverTask : public Cm::Task { public: ArticulationSim* const* mArticSims; const PxU32 mNumArticulations; const PxReal mDt; IG::SimpleIslandManager* mIslandManager; public: ScArticBeforeSolverTask(ArticulationSim* const* articSims, PxU32 nbArtics, PxReal dt, IG::SimpleIslandManager* islandManager, PxU64 contextID) : Cm::Task(contextID), mArticSims(articSims), mNumArticulations(nbArtics), mDt(dt), mIslandManager(islandManager) { } virtual void runInternal() { PX_PROFILE_ZONE("Sim.ScArticBeforeSolverTask", mContextID); //const IG::IslandSim& islandSim = mIslandManager->getAccurateIslandSim(); for(PxU32 a = 0; a < mNumArticulations; ++a) { ArticulationSim* PX_RESTRICT articSim = mArticSims[a]; //articSim->checkResize(); articSim->updateForces(mDt); articSim->setDirtyFlag(ArticulationSimDirtyFlag::eNONE); } } virtual const char* getName() const { return "ScScene.ScArticBeforeSolverTask"; } private: PX_NOCOPY(ScArticBeforeSolverTask) }; class ScArticBeforeSolverCCDTask : public Cm::Task { public: const PxNodeIndex* const mArticIndices; const PxU32 mNumArticulations; const PxReal mDt; IG::SimpleIslandManager* mIslandManager; public: ScArticBeforeSolverCCDTask(const PxNodeIndex* const articIndices, PxU32 nbArtics, PxReal dt, IG::SimpleIslandManager* islandManager, PxU64 contextID) : Cm::Task(contextID), mArticIndices(articIndices), mNumArticulations(nbArtics), mDt(dt), mIslandManager(islandManager) { } virtual void runInternal() { PX_PROFILE_ZONE("Sim.ScArticBeforeSolverCCDTask", mContextID); const IG::IslandSim& islandSim = mIslandManager->getAccurateIslandSim(); for(PxU32 a = 0; a < mNumArticulations; ++a) { ArticulationSim* articSim = islandSim.getArticulationSim(mArticIndices[a]); articSim->saveLastCCDTransform(); } } virtual const char* getName() const { return "ScScene.ScArticBeforeSolverCCDTask"; } private: PX_NOCOPY(ScArticBeforeSolverCCDTask) }; } void Sc::Scene::beforeSolver(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.updateForces", mContextId); // Note: For contact notifications it is important that force threshold checks are done after new/lost touches have been processed // because pairs might get added to the list processed below // Atoms that passed contact force threshold ThresholdStream& thresholdStream = mDynamicsContext->getThresholdStream(); thresholdStream.clear(); const IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); const PxU32 nbActiveBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); mNumDeactivatingNodes[IG::Node::eRIGID_BODY_TYPE] = 0;//islandSim.getNbNodesToDeactivate(IG::Node::eRIGID_BODY_TYPE); mNumDeactivatingNodes[IG::Node::eARTICULATION_TYPE] = 0;//islandSim.getNbNodesToDeactivate(IG::Node::eARTICULATION_TYPE); //#if PX_SUPPORT_GPU_PHYSX mNumDeactivatingNodes[IG::Node::eSOFTBODY_TYPE] = 0; mNumDeactivatingNodes[IG::Node::eFEMCLOTH_TYPE] = 0; mNumDeactivatingNodes[IG::Node::ePARTICLESYSTEM_TYPE] = 0; mNumDeactivatingNodes[IG::Node::eHAIRSYSTEM_TYPE] = 0; //#endif const PxU32 MaxBodiesPerTask = ScBeforeSolverTask::MaxBodiesPerTask; Cm::FlushPool& flushPool = mLLContext->getTaskPool(); mSimulationController->reserve(nbActiveBodies); { PxBitMap::Iterator iter(mVelocityModifyMap); // PT: TASK-CREATION TAG for (PxU32 i = iter.getNext(); i != PxBitMap::Iterator::DONE; /*i = iter.getNext()*/) { ScBeforeSolverTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScBeforeSolverTask)), ScBeforeSolverTask(mDt, mSimpleIslandManager, mSimulationController, mContextId)); PxU32 count = 0; for(; count < MaxBodiesPerTask && i != PxBitMap::Iterator::DONE; i = iter.getNext()) { PxsRigidBody* body = islandSim.getRigidBody(PxNodeIndex(i)); bool retainsAccelerations = false; if(body) { task->mBodies[count++] = PxNodeIndex(i); retainsAccelerations = (body->mCore->mFlags & PxRigidBodyFlag::eRETAIN_ACCELERATIONS); } if(!retainsAccelerations) mVelocityModifyMap.reset(i); } task->mNumBodies = count; startTask(task, continuation); } } // PT: TASK-CREATION TAG const PxU32 nbArticsPerTask = 32; const PxU32 nbDirtyArticulations = mDirtyArticulationSims.size(); ArticulationSim* const* artiSim = mDirtyArticulationSims.getEntries(); for(PxU32 a = 0; a < nbDirtyArticulations; a += nbArticsPerTask) { const PxU32 nbToProcess = PxMin(PxU32(nbDirtyArticulations - a), nbArticsPerTask); ScArticBeforeSolverTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScArticBeforeSolverTask)), ScArticBeforeSolverTask(artiSim + a, nbToProcess, mDt, mSimpleIslandManager, mContextId)); startTask(task, continuation); } //if the scene has ccd flag on, we should call ScArticBeforeSolverCCDTask to copy the last transform to the current transform if(mPublicFlags & PxSceneFlag::eENABLE_CCD) { //CCD const PxU32 nbActiveArticulations = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE); const PxNodeIndex* const articIndices = islandSim.getActiveNodes(IG::Node::eARTICULATION_TYPE); // PT: TASK-CREATION TAG for(PxU32 a = 0; a < nbActiveArticulations; a += nbArticsPerTask) { const PxU32 nbToProcess = PxMin(PxU32(nbActiveArticulations - a), nbArticsPerTask); ScArticBeforeSolverCCDTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScArticBeforeSolverCCDTask)), ScArticBeforeSolverCCDTask(articIndices + a, nbToProcess, mDt, mSimpleIslandManager, mContextId)); startTask(task, continuation); } } // AD: need to raise dirty flags serially because the PxgBodySimManager::updateArticulation() is not thread-safe. for (PxU32 a = 0; a < nbDirtyArticulations; ++a) { if (artiSim[a]->getLowLevelArticulation()->mGPUDirtyFlags & (Dy::ArticulationDirtyFlag::eDIRTY_EXT_ACCEL)) { mSimulationController->updateArticulationExtAccel(artiSim[a]->getLowLevelArticulation(), artiSim[a]->getIslandNodeIndex()); } } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::updateBodies(PxBaseTask* continuation) { //dma bodies and articulation data to gpu mSimulationController->updateBodies(continuation); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::updateDynamics(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.dynamics", mContextId); //Allow processLostContactsTask to run until after 2nd pass of solver completes (update bodies, run sleeping logic etc.) mProcessLostContactsTask3.setContinuation(static_cast<PxLightCpuTask*>(continuation)->getContinuation()); mProcessLostContactsTask2.setContinuation(&mProcessLostContactsTask3); mProcessLostContactsTask.setContinuation(&mProcessLostContactsTask2); ////dma bodies and shapes data to gpu //mSimulationController->updateBodiesAndShapes(); mLLContext->getNpMemBlockPool().acquireConstraintMemory(); const PxU32 maxPatchCount = mLLContext->getMaxPatchCount(); mAABBManager->reallocateChangedAABBMgActorHandleMap(getElementIDPool().getMaxID()); //mNPhaseCore->processPersistentContactEvents(outputs, continuation); PxvNphaseImplementationContext* nphase = mLLContext->getNphaseImplementationContext(); mDynamicsContext->update(*mSimpleIslandManager, continuation, &mProcessLostContactsTask, nphase, maxPatchCount, mMaxNbArticulationLinks, mDt, mGravity, mAABBManager->getChangedAABBMgActorHandleMap()); mSimpleIslandManager->clearDestroyedEdges(); mProcessLostContactsTask3.removeReference(); mProcessLostContactsTask2.removeReference(); mProcessLostContactsTask.removeReference(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processLostContacts(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sc::Scene::processLostContacts", mContextId); mProcessNarrowPhaseLostTouchTasks.setContinuation(continuation); mProcessNarrowPhaseLostTouchTasks.removeReference(); //mLostTouchReportsTask.setContinuation(&mProcessLostContactsTask3); mProcessNPLostTouchEvents.setContinuation(continuation); mProcessNPLostTouchEvents.removeReference(); { PX_PROFILE_ZONE("Sim.findInteractionsPtrs", mContextId); Bp::AABBManagerBase* aabbMgr = mAABBManager; PxU32 destroyedOverlapCount; Bp::AABBOverlap* PX_RESTRICT p = aabbMgr->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { ElementSim* volume0 = reinterpret_cast<ElementSim*>(p->mUserData0); ElementSim* volume1 = reinterpret_cast<ElementSim*>(p->mUserData1); // PT: this looks useless on lost pairs but it is used in processLostContacts2 and processLostContacts3 // PT: it seems very questionable to store this within the BP structures at this point. If anything // we should have stored that there when the overlap was created, and we wouldn't have to look for the // interaction here. p->mPairUserData = mNPhaseCore->findInteraction(volume0, volume1); p++; } } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processNarrowPhaseLostTouchEventsIslands(PxBaseTask*) { PX_PROFILE_ZONE("Sc::Scene.islandLostTouches", mContextId); const PxU32 count = mTouchLostEvents.size(); for(PxU32 i=0; i <count; ++i) { ShapeInteraction* si = getSI(mTouchLostEvents[i]); mSimpleIslandManager->setEdgeDisconnected(si->getEdgeIndex()); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::addToLostTouchList(ActorSim& body1, ActorSim& body2) { PX_ASSERT(!body1.isStaticRigid()); PX_ASSERT(!body2.isStaticRigid()); SimpleBodyPair p = { &body1, &body2, body1.getActorID(), body2.getActorID() }; mLostTouchPairs.pushBack(p); } void Sc::Scene::processNarrowPhaseLostTouchEvents(PxBaseTask*) { PX_PROFILE_ZONE("Sc::Scene.processNarrowPhaseLostTouchEvents", mContextId); PxvNphaseImplementationContext* ctx = mLLContext->getNphaseImplementationContext(); PxsContactManagerOutputIterator outputs = ctx->getContactManagerOutputs(); const PxU32 count = mTouchLostEvents.size(); for(PxU32 i=0; i<count; ++i) { ShapeInteraction* si = getSI(mTouchLostEvents[i]); PX_ASSERT(si); if(si->managerLostTouch(0, true, outputs) && !si->readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) addToLostTouchList(si->getShape0().getActor(), si->getShape1().getActor()); } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processLostContacts2(PxBaseTask* continuation) { mDestroyManagersTask.setContinuation(continuation); mLostTouchReportsTask.setContinuation(&mDestroyManagersTask); mLostTouchReportsTask.removeReference(); mUnregisterInteractionsTask.setContinuation(continuation); mUnregisterInteractionsTask.removeReference(); { PX_PROFILE_ZONE("Sim.clearIslandData", mContextId); Bp::AABBManagerBase* aabbMgr = mAABBManager; PxU32 destroyedOverlapCount; { Bp::AABBOverlap* PX_RESTRICT p = aabbMgr->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { ElementSimInteraction* pair = reinterpret_cast<ElementSimInteraction*>(p->mPairUserData); if(pair) { if(pair->getType() == InteractionType::eOVERLAP) { ShapeInteraction* si = static_cast<ShapeInteraction*>(pair); si->clearIslandGenData(); } } p++; } } } mDestroyManagersTask.removeReference(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::lostTouchReports(PxBaseTask*) { PX_PROFILE_ZONE("Sim.lostTouchReports", mContextId); PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); mNPhaseCore->lockReports(); { PxU32 destroyedOverlapCount; const Bp::AABBOverlap* PX_RESTRICT p = mAABBManager->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { if(p->mPairUserData) { ElementSimInteraction* elemInteraction = reinterpret_cast<ElementSimInteraction*>(p->mPairUserData); if(elemInteraction->getType() == InteractionType::eOVERLAP) mNPhaseCore->lostTouchReports(static_cast<ShapeInteraction*>(elemInteraction), PxU32(PairReleaseFlag::eWAKE_ON_LOST_TOUCH), NULL, 0, outputs); } p++; } } mNPhaseCore->unlockReports(); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::unregisterInteractions(PxBaseTask*) { PX_PROFILE_ZONE("Sim.unregisterInteractions", mContextId); PxU32 destroyedOverlapCount; const Bp::AABBOverlap* PX_RESTRICT p = mAABBManager->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { if(p->mPairUserData) { ElementSimInteraction* elemInteraction = reinterpret_cast<ElementSimInteraction*>(p->mPairUserData); if(elemInteraction->getType() == InteractionType::eOVERLAP || elemInteraction->getType() == InteractionType::eMARKER) unregisterInteraction(elemInteraction); } p++; } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::destroyManagers(PxBaseTask*) { PX_PROFILE_ZONE("Sim.destroyManagers", mContextId); mPostThirdPassIslandGenTask.setContinuation(mProcessLostContactsTask3.getContinuation()); mSimpleIslandManager->thirdPassIslandGen(&mPostThirdPassIslandGenTask); PxU32 destroyedOverlapCount; const Bp::AABBOverlap* PX_RESTRICT p = mAABBManager->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { if(p->mPairUserData) { ElementSimInteraction* elemInteraction = reinterpret_cast<ElementSimInteraction*>(p->mPairUserData); if(elemInteraction->getType() == InteractionType::eOVERLAP) { ShapeInteraction* si = static_cast<ShapeInteraction*>(elemInteraction); if(si->getContactManager()) si->destroyManager(); } } p++; } } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::processLostContacts3(PxBaseTask* /*continuation*/) { { PX_PROFILE_ZONE("Sim.processLostOverlapsStage2", mContextId); PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); Bp::AABBManagerBase* aabbMgr = mAABBManager; PxU32 destroyedOverlapCount; // PT: for regular shapes { const Bp::AABBOverlap* PX_RESTRICT p = aabbMgr->getDestroyedOverlaps(Bp::ElementType::eSHAPE, destroyedOverlapCount); while(destroyedOverlapCount--) { ElementSim* volume0 = reinterpret_cast<ElementSim*>(p->mUserData0); ElementSim* volume1 = reinterpret_cast<ElementSim*>(p->mUserData1); mNPhaseCore->onOverlapRemoved(volume0, volume1, false, p->mPairUserData, outputs); p++; } } // PT: for triggers { const Bp::AABBOverlap* PX_RESTRICT p = aabbMgr->getDestroyedOverlaps(Bp::ElementType::eTRIGGER, destroyedOverlapCount); while(destroyedOverlapCount--) { ElementSim* volume0 = reinterpret_cast<ElementSim*>(p->mUserData0); ElementSim* volume1 = reinterpret_cast<ElementSim*>(p->mUserData1); mNPhaseCore->onOverlapRemoved(volume0, volume1, false, NULL, outputs); p++; } } aabbMgr->freeBuffers(); } mPostThirdPassIslandGenTask.removeReference(); } /////////////////////////////////////////////////////////////////////////////// /*static*/ bool deactivateInteraction(Interaction* interaction, const InteractionType::Enum type); void Sc::Scene::postThirdPassIslandGen(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sc::Scene::postThirdPassIslandGen", mContextId); putObjectsToSleep(); { PX_PROFILE_ZONE("Sc::Scene::putInteractionsToSleep", mContextId); const IG::IslandSim& islandSim = mSimpleIslandManager->getSpeculativeIslandSim(); //KS - only deactivate contact managers based on speculative state to trigger contact gen. When the actors were deactivated based on accurate state //joints should have been deactivated. const PxU32 NbTypes = 5; const IG::Edge::EdgeType types[NbTypes] = { IG::Edge::eCONTACT_MANAGER, IG::Edge::eSOFT_BODY_CONTACT, IG::Edge::eFEM_CLOTH_CONTACT, IG::Edge::ePARTICLE_SYSTEM_CONTACT, IG::Edge::eHAIR_SYSTEM_CONTACT }; for(PxU32 t = 0; t < NbTypes; ++t) { const PxU32 nbDeactivatingEdges = islandSim.getNbDeactivatingEdges(types[t]); const IG::EdgeIndex* deactivatingEdgeIds = islandSim.getDeactivatingEdges(types[t]); for(PxU32 i = 0; i < nbDeactivatingEdges; ++i) { Interaction* interaction = mSimpleIslandManager->getInteraction(deactivatingEdgeIds[i]); if(interaction && interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)) { if(!islandSim.getEdge(deactivatingEdgeIds[i]).isActive()) { const InteractionType::Enum type = interaction->getType(); const bool proceed = deactivateInteraction(interaction, type); if(proceed && (type < InteractionType::eTRACKED_IN_SCENE_COUNT)) notifyInteractionDeactivated(interaction); } } } } } PxvNphaseImplementationContext* implCtx = mLLContext->getNphaseImplementationContext(); PxsContactManagerOutputIterator outputs = implCtx->getContactManagerOutputs(); mNPhaseCore->processPersistentContactEvents(outputs); } /////////////////////////////////////////////////////////////////////////////// //This is called after solver finish void Sc::Scene::updateSimulationController(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.updateSimulationController", mContextId); PxsTransformCache& cache = getLowLevelContext()->getTransformCache(); Bp::BoundsArray& boundArray = getBoundsArray(); PxBitMapPinned& changedAABBMgrActorHandles = mAABBManager->getChangedAABBMgActorHandleMap(); mSimulationController->gpuDmabackData(cache, boundArray, changedAABBMgrActorHandles, mPublicFlags & PxSceneFlag::eENABLE_DIRECT_GPU_API); //for pxgdynamicscontext: copy solver body data to body core { PX_PROFILE_ZONE("Sim.updateBodyCore", mContextId); mDynamicsContext->updateBodyCore(continuation); } //mSimulationController->update(cache, boundArray, changedAABBMgrActorHandles); /*mProcessLostPatchesTask.setContinuation(&mFinalizationPhase); mProcessLostPatchesTask.removeReference();*/ } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::postSolver(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sc::Scene::postSolver", mContextId); PxcNpMemBlockPool& blockPool = mLLContext->getNpMemBlockPool(); //Merge... mDynamicsContext->mergeResults(); blockPool.releaseConstraintMemory(); //Swap friction! blockPool.swapFrictionStreams(); mCcdBodies.clear(); #if PX_ENABLE_SIM_STATS mLLContext->getSimStats().mPeakConstraintBlockAllocations = blockPool.getPeakConstraintBlockCount(); #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif integrateKinematicPose(); { const PxU32 size = mDirtyArticulationSims.size(); ArticulationSim* const* articSims = mDirtyArticulationSims.getEntries(); //clear the acceleration term for articulation if the application raised PxForceMode::eIMPULSE in addForce function. This change //will make sure articulation and rigid body behave the same const float dt = mDt; for(PxU32 i=0; i<size; ++i) articSims[i]->clearAcceleration(dt); //clear the dirty articulation list mDirtyArticulationSims.clear(); } //afterIntegration(continuation); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::constraintProjection(PxBaseTask* /*continuation*/) { } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::checkForceThresholdContactEvents(PxU32 ccdPass) { PX_PROFILE_ZONE("Sim.checkForceThresholdContactEvents", mContextId); // Note: For contact notifications it is important that force threshold checks are done after new/lost touches have been processed // because pairs might get added to the list processed below // Bodies that passed contact force threshold PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); ThresholdStream& thresholdStream = mDynamicsContext->getForceChangedThresholdStream(); const PxU32 nbThresholdElements = thresholdStream.size(); for(PxU32 i = 0; i< nbThresholdElements; ++i) { ThresholdStreamElement& elem = thresholdStream[i]; ShapeInteraction* si = elem.shapeInteraction; //If there is a shapeInteraction and the shapeInteraction points to a contactManager (i.e. the CM was not destroyed in parallel with the solver) if(si) { PxU32 pairFlags = si->getPairFlags(); if(pairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS) { si->swapAndClearForceThresholdExceeded(); if(elem.accumulatedForce > elem.threshold * mDt) { si->raiseFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_NOW); PX_ASSERT(si->hasTouch()); //If the accumulatedForce is large than the threshold in the current frame and the accumulatedForce is less than the threshold in the previous frame, //and the user request notify for found event, we will raise eNOTIFY_THRESHOLD_FORCE_FOUND if((!si->readFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_BEFORE)) && (pairFlags & PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND)) si->processUserNotification(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND, 0, false, ccdPass, false, outputs); else if(si->readFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_BEFORE) && (pairFlags & PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS)) si->processUserNotification(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS, 0, false, ccdPass, false, outputs); } else { //If the accumulatedForce is less than the threshold in the current frame and the accumulatedForce is large than the threshold in the previous frame, //and the user request notify for found event, we will raise eNOTIFY_THRESHOLD_FORCE_LOST if(si->readFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_BEFORE) && (pairFlags & PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST)) si->processUserNotification(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST, 0, false, ccdPass, false, outputs); } } } } } void Sc::Scene::afterIntegration(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sc::Scene::afterIntegration", mContextId); mLLContext->getTransformCache().resetChangedState(); //Reset the changed state. If anything outside of the GPU kernels updates any shape's transforms, this will be raised again getBoundsArray().resetChangedState(); PxsTransformCache& cache = getLowLevelContext()->getTransformCache(); Bp::BoundsArray& boundArray = getBoundsArray(); { PX_PROFILE_ZONE("AfterIntegration::lockStage", mContextId); mLLContext->getLock().lock(); { PX_PROFILE_ZONE("SimController", mContextId); mSimulationController->updateScBodyAndShapeSim(cache, boundArray, continuation); } const IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); const PxU32 rigidBodyOffset = BodySim::getRigidBodyOffset(); const PxU32 numBodiesToDeactivate = islandSim.getNbNodesToDeactivate(IG::Node::eRIGID_BODY_TYPE); const PxNodeIndex*const deactivatingIndices = islandSim.getNodesToDeactivate(IG::Node::eRIGID_BODY_TYPE); PxU32 previousNumBodiesToDeactivate = mNumDeactivatingNodes[IG::Node::eRIGID_BODY_TYPE]; { PX_PROFILE_ZONE("AfterIntegration::deactivateStage", mContextId); PxBitMapPinned& changedAABBMgrActorHandles = mAABBManager->getChangedAABBMgActorHandleMap(); for(PxU32 i = previousNumBodiesToDeactivate; i < numBodiesToDeactivate; i++) { PxsRigidBody* rigid = islandSim.getRigidBody(deactivatingIndices[i]); BodySim* bodySim = reinterpret_cast<BodySim*>(reinterpret_cast<PxU8*>(rigid) - rigidBodyOffset); //we need to set the rigid body back to the previous pose for the deactivated objects. This emulates the previous behavior where island gen ran before the solver, ensuring //that bodies that should be deactivated this frame never reach the solver. We now run the solver in parallel with island gen, so objects that should be deactivated this frame //still reach the solver and are integrated. However, on the frame when they should be deactivated, we roll back to their state at the beginning of the frame to ensure that the //user perceives the same behavior as before. PxsBodyCore& bodyCore = bodySim->getBodyCore().getCore(); //if(!islandSim.getNode(bodySim->getNodeIndex()).isActive()) rigid->setPose(rigid->getLastCCDTransform()); bodySim->updateCached(&changedAABBMgrActorHandles); updateBodySim(*bodySim); //solver is running in parallel with IG(so solver might solving the body which IG identify as deactivatedNodes). After we moved sleepCheck into the solver after integration, sleepChecks //might have processed bodies that are now considered deactivated. This could have resulted in either freezing or unfreezing one of these bodies this frame, so we need to process those //events to ensure that the SqManager's bounds arrays are consistently maintained. Also, we need to clear the frame flags for these bodies. if(rigid->isFreezeThisFrame()) bodySim->freezeTransforms(&mAABBManager->getChangedAABBMgActorHandleMap()); //KS - the IG deactivates bodies in parallel with the solver. It appears that under certain circumstances, the solver's integration (which performs //sleep checks) could decide that the body is no longer a candidate for sleeping on the same frame that the island gen decides to deactivate the island //that the body is contained in. This is a rare occurrence but the behavior we want to emulate is that of IG running before solver so we should therefore //permit the IG to make the authoritative decision over whether the body should be active or inactive. bodyCore.wakeCounter = 0.0f; bodyCore.linearVelocity = PxVec3(0.0f); bodyCore.angularVelocity = PxVec3(0.0f); rigid->clearAllFrameFlags(); } } updateKinematicCached(continuation); mLLContext->getLock().unlock(); } IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); const PxU32 nbActiveArticulations = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE); if(nbActiveArticulations) mSimulationController->updateArticulationAfterIntegration(mLLContext, mAABBManager, mCcdBodies, continuation, islandSim, mDt); const PxU32 numArticsToDeactivate = islandSim.getNbNodesToDeactivate(IG::Node::eARTICULATION_TYPE); const PxNodeIndex*const deactivatingArticIndices = islandSim.getNodesToDeactivate(IG::Node::eARTICULATION_TYPE); PxU32 previousNumArticsToDeactivate = mNumDeactivatingNodes[IG::Node::eARTICULATION_TYPE]; for(PxU32 i = previousNumArticsToDeactivate; i < numArticsToDeactivate; ++i) { ArticulationSim* artic = islandSim.getArticulationSim(deactivatingArticIndices[i]); artic->putToSleep(); } //PxU32 previousNumClothToDeactivate = mNumDeactivatingNodes[IG::Node::eFEMCLOTH_TYPE]; //const PxU32 numClothToDeactivate = islandSim.getNbNodesToDeactivate(IG::Node::eFEMCLOTH_TYPE); //const IG::NodeIndex*const deactivatingClothIndices = islandSim.getNodesToDeactivate(IG::Node::eFEMCLOTH_TYPE); //for (PxU32 i = previousNumClothToDeactivate; i < numClothToDeactivate; ++i) //{ // FEMCloth* cloth = islandSim.getLLFEMCloth(deactivatingClothIndices[i]); // mSimulationController->deactivateCloth(cloth); //} //PxU32 previousNumSoftBodiesToDeactivate = mNumDeactivatingNodes[IG::Node::eSOFTBODY_TYPE]; //const PxU32 numSoftBodiesToDeactivate = islandSim.getNbNodesToDeactivate(IG::Node::eSOFTBODY_TYPE); //const IG::NodeIndex*const deactivatingSoftBodiesIndices = islandSim.getNodesToDeactivate(IG::Node::eSOFTBODY_TYPE); //for (PxU32 i = previousNumSoftBodiesToDeactivate; i < numSoftBodiesToDeactivate; ++i) //{ // Dy::SoftBody* softbody = islandSim.getLLSoftBody(deactivatingSoftBodiesIndices[i]); // printf("after Integration: Deactivating soft body %i\n", softbody->getGpuRemapId()); // //mSimulationController->deactivateSoftbody(softbody); // softbody->getSoftBodySim()->setActive(false, 0); //} PX_PROFILE_STOP_CROSSTHREAD("Basic.dynamics", mContextId); checkForceThresholdContactEvents(0); } /////////////////////////////////////////////////////////////////////////////// void Sc::Scene::fireOnAdvanceCallback() { if(!mSimulationEventCallback) return; const PxU32 nbPosePreviews = mPosePreviewBodies.size(); if(!nbPosePreviews) return; mClientPosePreviewBodies.clear(); mClientPosePreviewBodies.reserve(nbPosePreviews); mClientPosePreviewBuffer.clear(); mClientPosePreviewBuffer.reserve(nbPosePreviews); const BodySim*const* PX_RESTRICT posePreviewBodies = mPosePreviewBodies.getEntries(); for(PxU32 i=0; i<nbPosePreviews; i++) { const BodySim& b = *posePreviewBodies[i]; if(!b.isFrozen()) { PxsBodyCore& c = b.getBodyCore().getCore(); mClientPosePreviewBodies.pushBack(static_cast<const PxRigidBody*>(b.getPxActor())); // PT:: tag: scalar transform*transform mClientPosePreviewBuffer.pushBack(c.body2World * c.getBody2Actor().getInverse()); } } const PxU32 bodyCount = mClientPosePreviewBodies.size(); if(bodyCount) mSimulationEventCallback->onAdvance(mClientPosePreviewBodies.begin(), mClientPosePreviewBuffer.begin(), bodyCount); } void Sc::Scene::finalizationPhase(PxBaseTask* /*continuation*/) { PX_PROFILE_ZONE("Sim.sceneFinalization", mContextId); if(mCCDContext) { if(mSimulationController->mGPU) // PT: skip this on CPU, see empty CPU function called in updateBodySim { //KS - force simulation controller to update any bodies updated by the CCD. When running GPU simulation, this would be required //to ensure that cached body states are updated const PxU32 nbUpdatedBodies = mCCDContext->getNumUpdatedBodies(); PxsRigidBody*const* updatedBodies = mCCDContext->getUpdatedBodies(); const PxU32 rigidBodyOffset = BodySim::getRigidBodyOffset(); for(PxU32 a=0; a<nbUpdatedBodies; ++a) { BodySim* bodySim = reinterpret_cast<BodySim*>(reinterpret_cast<PxU8*>(updatedBodies[a]) - rigidBodyOffset); updateBodySim(*bodySim); } } mCCDContext->clearUpdatedBodies(); } fireOnAdvanceCallback(); // placed here because it needs to be done after sleep check and after potential CCD passes checkConstraintBreakage(); // Performs breakage tests on breakable constraints PX_PROFILE_STOP_CROSSTHREAD("Basic.rigidBodySolver", mContextId); mTaskPool.clear(); mReportShapePairTimeStamp++; // important to do this before fetchResults() is called to make sure that delayed deleted actors/shapes get // separate pair entries in contact reports // AD: WIP, will be gone once we removed the warm-start with sim step. if (mPublicFlags & PxSceneFlag::eENABLE_DIRECT_GPU_API) setDirectGPUAPIInitialized(); } ///////////////////////////////////////////////////////////////////////////////
87,155
C++
35.074503
205
0.726522
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeCore.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/PxErrorCallback.h" #include "ScShapeSim.h" #include "ScPhysics.h" #include "GuConvexMesh.h" #include "GuTriangleMesh.h" #include "GuHeightField.h" #include "GuTetrahedronMesh.h" using namespace physx; using namespace Gu; using namespace Cm; using namespace Sc; static PX_FORCE_INLINE Gu::ConvexMesh& getConvexMesh(PxConvexMesh* pxcm) { return *static_cast<Gu::ConvexMesh*>(pxcm); } // PT: TODO: optimize all these data copies void GeometryUnion::set(const PxGeometry& g) { // PT: preserve this field that can be used by higher-level code to store useful data const float saved = reinterpret_cast<const PxGeometry&>(mGeometry).mTypePadding; switch(g.getType()) { case PxGeometryType::eBOX: { reinterpret_cast<PxBoxGeometry&>(mGeometry) = static_cast<const PxBoxGeometry&>(g); } break; case PxGeometryType::eCAPSULE: { reinterpret_cast<PxCapsuleGeometry&>(mGeometry) = static_cast<const PxCapsuleGeometry&>(g); } break; case PxGeometryType::eSPHERE: { reinterpret_cast<PxSphereGeometry&>(mGeometry) = static_cast<const PxSphereGeometry&>(g); reinterpret_cast<PxCapsuleGeometry&>(mGeometry).halfHeight = 0.0f; //AM: make sphere geometry also castable as a zero height capsule. } break; case PxGeometryType::ePLANE: { reinterpret_cast<PxPlaneGeometry&>(mGeometry) = static_cast<const PxPlaneGeometry&>(g); } break; case PxGeometryType::eCONVEXMESH: { reinterpret_cast<PxConvexMeshGeometry&>(mGeometry) = static_cast<const PxConvexMeshGeometry&>(g); reinterpret_cast<PxConvexMeshGeometryLL&>(mGeometry).gpuCompatible = ::getConvexMesh(get<PxConvexMeshGeometryLL>().convexMesh).isGpuCompatible(); } break; case PxGeometryType::ePARTICLESYSTEM: { reinterpret_cast<PxParticleSystemGeometry&>(mGeometry) = static_cast<const PxParticleSystemGeometry&>(g); reinterpret_cast<PxParticleSystemGeometryLL&>(mGeometry).materialsLL = MaterialIndicesStruct(); } break; case PxGeometryType::eTRIANGLEMESH: { reinterpret_cast<PxTriangleMeshGeometry&>(mGeometry) = static_cast<const PxTriangleMeshGeometry&>(g); reinterpret_cast<PxTriangleMeshGeometryLL&>(mGeometry).materialsLL = MaterialIndicesStruct(); } break; case PxGeometryType::eTETRAHEDRONMESH: { reinterpret_cast<PxTetrahedronMeshGeometry&>(mGeometry) = static_cast<const PxTetrahedronMeshGeometry&>(g); reinterpret_cast<PxTetrahedronMeshGeometryLL&>(mGeometry).materialsLL = MaterialIndicesStruct(); } break; case PxGeometryType::eHEIGHTFIELD: { reinterpret_cast<PxHeightFieldGeometry&>(mGeometry) = static_cast<const PxHeightFieldGeometry&>(g); reinterpret_cast<PxHeightFieldGeometryLL&>(mGeometry).materialsLL = MaterialIndicesStruct(); } break; case PxGeometryType::eHAIRSYSTEM: { reinterpret_cast<PxHairSystemGeometry&>(mGeometry) = static_cast<const PxHairSystemGeometry&>(g); } break; case PxGeometryType::eCUSTOM: { reinterpret_cast<PxCustomGeometry&>(mGeometry) = static_cast<const PxCustomGeometry&>(g); } break; case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: PX_ALWAYS_ASSERT_MESSAGE("geometry type not handled"); break; } reinterpret_cast<PxGeometry&>(mGeometry).mTypePadding = saved; } static PxConvexMeshGeometryLL extendForLL(const PxConvexMeshGeometry& hlGeom) { PxConvexMeshGeometryLL llGeom; static_cast<PxConvexMeshGeometry&>(llGeom) = hlGeom; llGeom.gpuCompatible = hlGeom.convexMesh->isGpuCompatible(); return llGeom; } static PxTriangleMeshGeometryLL extendForLL(const PxTriangleMeshGeometry& hlGeom) { PxTriangleMeshGeometryLL llGeom; static_cast<PxTriangleMeshGeometry&>(llGeom) = hlGeom; llGeom.materialsLL = static_cast<const PxTriangleMeshGeometryLL&>(hlGeom).materialsLL; return llGeom; } static PxHeightFieldGeometryLL extendForLL(const PxHeightFieldGeometry& hlGeom) { PxHeightFieldGeometryLL llGeom; static_cast<PxHeightFieldGeometry&>(llGeom) = hlGeom; llGeom.materialsLL = static_cast<const PxHeightFieldGeometryLL&>(hlGeom).materialsLL; return llGeom; } ShapeCore::ShapeCore(const PxGeometry& geometry, PxShapeFlags shapeFlags, const PxU16* materialIndices, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum softOrClothFlags) : mExclusiveSim(NULL) { mCore.mShapeCoreFlags |= PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY; if(isExclusive) mCore.mShapeCoreFlags |= PxShapeCoreFlag::eIS_EXCLUSIVE; mCore.mShapeCoreFlags |= softOrClothFlags; PX_ASSERT(materialCount > 0); const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); mCore.mGeometry.set(geometry); mCore.setTransform(PxTransform(PxIdentity)); mCore.mContactOffset = 0.02f * scale.length; mCore.mRestOffset = 0.0f; mCore.mTorsionalRadius = 0.0f; mCore.mMinTorsionalPatchRadius = 0.0f; mCore.mShapeFlags = shapeFlags; setMaterialIndices(materialIndices, materialCount); } // PX_SERIALIZATION ShapeCore::ShapeCore(const PxEMPTY) : mSimulationFilterData (PxEmpty), mCore (PxEmpty), mExclusiveSim (NULL) { mCore.mShapeCoreFlags.clear(PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY); } //~PX_SERIALIZATION static PX_FORCE_INLINE const MaterialIndicesStruct* getMaterials(const GeometryUnion& gu) { const PxGeometryType::Enum type = gu.getType(); if(type == PxGeometryType::eTRIANGLEMESH) return &gu.get<PxTriangleMeshGeometryLL>().materialsLL; else if(type == PxGeometryType::eHEIGHTFIELD) return &gu.get<PxHeightFieldGeometryLL>().materialsLL; else if(type == PxGeometryType::eTETRAHEDRONMESH) return &gu.get<PxTetrahedronMeshGeometryLL>().materialsLL; else if(type == PxGeometryType::ePARTICLESYSTEM) return &gu.get<PxParticleSystemGeometryLL>().materialsLL; else return NULL; } ShapeCore::~ShapeCore() { if(mCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY)) { MaterialIndicesStruct* materialsLL = const_cast<MaterialIndicesStruct*>(getMaterials(mCore.mGeometry)); if(materialsLL) materialsLL->deallocate(); } } PxU16 Sc::ShapeCore::getNbMaterialIndices() const { const MaterialIndicesStruct* materialsLL = getMaterials(mCore.mGeometry); return materialsLL ? materialsLL->numIndices : 1; } const PxU16* Sc::ShapeCore::getMaterialIndices() const { const MaterialIndicesStruct* materialsLL = getMaterials(mCore.mGeometry); return materialsLL ? materialsLL->indices : &mCore.mMaterialIndex; } PX_FORCE_INLINE void setMaterialsHelper(MaterialIndicesStruct& materials, const PxU16* materialIndices, PxU16 materialIndexCount, PxShapeCoreFlags& shapeCoreFlags) { if(materials.numIndices < materialIndexCount) { if(materials.indices && shapeCoreFlags.isSet(PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY)) materials.deallocate(); materials.allocate(materialIndexCount); shapeCoreFlags |= PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY; } PxMemCopy(materials.indices, materialIndices, sizeof(PxU16)*materialIndexCount); materials.numIndices = materialIndexCount; } void ShapeCore::setMaterialIndices(const PxU16* materialIndices, PxU16 materialIndexCount) { mCore.mMaterialIndex = materialIndices[0]; MaterialIndicesStruct* materialsLL = const_cast<MaterialIndicesStruct*>(getMaterials(mCore.mGeometry)); if(materialsLL) setMaterialsHelper(*materialsLL, materialIndices, materialIndexCount, mCore.mShapeCoreFlags); } void ShapeCore::setGeometry(const PxGeometry& geom) { const PxGeometryType::Enum newGeomType = geom.getType(); // copy material related data to restore it after the new geometry has been set MaterialIndicesStruct materials; PX_ASSERT(materials.numIndices == 0); const MaterialIndicesStruct* materialsLL = getMaterials(mCore.mGeometry); if(materialsLL) materials = *materialsLL; mCore.mGeometry.set(geom); if((newGeomType == PxGeometryType::eTRIANGLEMESH) || (newGeomType == PxGeometryType::eHEIGHTFIELD) || (newGeomType == PxGeometryType::eTETRAHEDRONMESH)|| (newGeomType == PxGeometryType::ePARTICLESYSTEM)) { MaterialIndicesStruct* newMaterials = const_cast<MaterialIndicesStruct*>(getMaterials(mCore.mGeometry)); PX_ASSERT(newMaterials); if(materials.numIndices != 0) // old type was mesh type *newMaterials = materials; else { // old type was non-mesh type newMaterials->allocate(1); *newMaterials->indices = mCore.mMaterialIndex; mCore.mShapeCoreFlags |= PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY; } } else if((materials.numIndices != 0) && mCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY)) { // geometry changed to non-mesh type materials.deallocate(); } } PxShape* ShapeCore::getPxShape() { return Sc::gOffsetTable.convertScShape2Px(this); } const PxShape* ShapeCore::getPxShape() const { return Sc::gOffsetTable.convertScShape2Px(this); } void ShapeCore::setContactOffset(const PxReal offset) { mCore.mContactOffset = offset; ShapeSim* exclusiveSim = getExclusiveSim(); if (exclusiveSim) { exclusiveSim->getScene().updateContactDistance(exclusiveSim->getElementID(), offset); } } // PX_SERIALIZATION PX_FORCE_INLINE void exportExtraDataMaterials(PxSerializationContext& stream, const MaterialIndicesStruct& materials) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(materials.indices, sizeof(PxU16)*materials.numIndices); } void ShapeCore::exportExtraData(PxSerializationContext& stream) { const MaterialIndicesStruct* materialsLL = getMaterials(mCore.mGeometry); if(materialsLL) exportExtraDataMaterials(stream, *materialsLL); } void ShapeCore::importExtraData(PxDeserializationContext& context) { MaterialIndicesStruct* materialsLL = const_cast<MaterialIndicesStruct*>(getMaterials(mCore.mGeometry)); if(materialsLL) materialsLL->indices = context.readExtraData<PxU16, PX_SERIAL_ALIGN>(materialsLL->numIndices); } void ShapeCore::resolveMaterialReference(PxU32 materialTableIndex, PxU16 materialIndex) { if(materialTableIndex == 0) mCore.mMaterialIndex = materialIndex; MaterialIndicesStruct* materialsLL = const_cast<MaterialIndicesStruct*>(getMaterials(mCore.mGeometry)); if(materialsLL) materialsLL->indices[materialTableIndex] = materialIndex; } void ShapeCore::resolveReferences(PxDeserializationContext& context) { // Resolve geometry pointers if needed PxGeometry& geom = const_cast<PxGeometry&>(mCore.mGeometry.getGeometry()); switch(geom.getType()) { case PxGeometryType::eCONVEXMESH: { PxConvexMeshGeometryLL& convexGeom = static_cast<PxConvexMeshGeometryLL&>(geom); context.translatePxBase(convexGeom.convexMesh); // update the hullData pointer static_cast<PxConvexMeshGeometryLL&>(geom) = extendForLL(convexGeom); } break; case PxGeometryType::eHEIGHTFIELD: { PxHeightFieldGeometryLL& hfGeom = static_cast<PxHeightFieldGeometryLL&>(geom); context.translatePxBase(hfGeom.heightField); // update hf pointers static_cast<PxHeightFieldGeometryLL&>(geom) = extendForLL(hfGeom); } break; case PxGeometryType::eTRIANGLEMESH: { PxTriangleMeshGeometryLL& meshGeom = static_cast<PxTriangleMeshGeometryLL&>(geom); context.translatePxBase(meshGeom.triangleMesh); // update mesh pointers static_cast<PxTriangleMeshGeometryLL&>(geom) = extendForLL(meshGeom); } break; case PxGeometryType::eTETRAHEDRONMESH: case PxGeometryType::ePARTICLESYSTEM: case PxGeometryType::eHAIRSYSTEM: case PxGeometryType::eCUSTOM: { // implement PX_ASSERT(0); } break; case PxGeometryType::eSPHERE: case PxGeometryType::ePLANE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eGEOMETRY_COUNT: case PxGeometryType::eINVALID: break; } } PxU32 ShapeCore::getInternalShapeIndex(PxsSimulationController& simulationController) const { return simulationController.getInternalShapeIndex(getCore()); } //~PX_SERIALIZATION
13,438
C++
31.858191
163
0.776678
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemShapeCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxErrorCallback.h" #include "ScParticleSystemShapeCore.h" #include "ScParticleSystemShapeSim.h" #include "ScPhysics.h" #include "PxvGlobals.h" #include "PxPhysXGpu.h" #include "cudamanager/PxCudaContextManager.h" #include "CmVisualization.h" using namespace physx; using namespace Sc; ParticleSystemShapeCore::ParticleSystemShapeCore() : ShapeCore(PxEmpty) , mGpuMemStat(0) { mSimulationFilterData = PxFilterData(); mCore = PxsShapeCore(); mCore.mShapeCoreFlags |= PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY; const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); mCore.setTransform(PxTransform(PxIdentity)); mCore.mContactOffset = 0.01f * scale.length; mCore.mShapeFlags = 0; mCore.mMaterialIndex = 0; mCore.mMinTorsionalPatchRadius = 0.f; mCore.mTorsionalRadius = 0.f; mLLCore.sleepThreshold = 5e-5f * scale.speed * scale.speed; mLLCore.wakeCounter = Physics::sWakeCounterOnCreation; mLLCore.freezeThreshold = 5e-6f * scale.speed * scale.speed; //TODO, make this dependend on scale? //also set contact offset accordingly mLLCore.restOffset = 0.1f; const PxReal contactOffset = mLLCore.restOffset + 0.001f; setContactOffset(contactOffset); mLLCore.particleContactOffset = contactOffset; mLLCore.solidRestOffset = mLLCore.restOffset; mLLCore.fluidRestOffset = mLLCore.restOffset * 0.6f; mLLCore.particleContactOffset_prev = FLT_MIN; mLLCore.fluidRestOffset_prev = FLT_MIN; mLLCore.fluidBoundaryDensityScale = 0.0f; mLLCore.gridSizeX = 128; mLLCore.gridSizeY = 128; mLLCore.gridSizeZ = 128; mLLCore.mFlags = PxParticleFlags(0); mLLCore.solverIterationCounts = (1 << 8) | 4; mLLCore.mWind = PxVec3(0.f); //mLLCore.mNumUpdateSprings = 0; mLLCore.solverType = PxParticleSolverType::ePBD; // Sparse grid specific mLLCore.sparseGridParams.setToDefault(); mLLCore.sparseGridParams.gridSpacing = 2.0f * mLLCore.particleContactOffset; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION // FLIP specific mLLCore.flipParams.setToDefault(); // MPM specific mLLCore.mpmParams.setToDefault(); #endif } // PX_SERIALIZATION ParticleSystemShapeCore::ParticleSystemShapeCore(const PxEMPTY) : ShapeCore(PxEmpty) { } ParticleSystemShapeCore::~ParticleSystemShapeCore() { } void ParticleSystemShapeCore::addParticleBuffer(PxParticleBuffer* particleBuffer) { mLLCore.addParticleBuffer(particleBuffer); } void ParticleSystemShapeCore::removeParticleBuffer(PxParticleBuffer* particleBuffer) { mLLCore.removeParticleBuffer(particleBuffer); } void ParticleSystemShapeCore::initializeLLCoreData(PxU32 maxNeighborhood) { const PxTolerancesScale& scale = Sc::Physics::getInstance().getTolerancesScale(); mLLCore.mMaxNeighborhood = maxNeighborhood; mLLCore.maxDepenetrationVelocity = 50.f * scale.length; mLLCore.maxVelocity = 1e+6f; } #endif // PX_SUPPORT_GPU_PHYSX
4,481
C++
31.014285
84
0.77929
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScMetaData.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxIO.h" #include "ScActorCore.h" #include "ScActorSim.h" #include "ScBodyCore.h" #include "ScStaticCore.h" #include "ScConstraintCore.h" #include "ScShapeCore.h" #include "ScArticulationCore.h" #include "ScArticulationJointCore.h" #include "ScArticulationSensor.h" #include "ScArticulationTendonCore.h" #include "ScArticulationAttachmentCore.h" #include "ScArticulationTendonJointCore.h" using namespace physx; using namespace Cm; using namespace Sc; /////////////////////////////////////////////////////////////////////////////// template <typename T> class PxMetaDataArray : public physx::PxArray<T> { public: static PX_FORCE_INLINE physx::PxU32 getDataOffset() { return PX_OFFSET_OF(PxMetaDataArray<T>, mData); } static PX_FORCE_INLINE physx::PxU32 getDataSize() { return PX_SIZE_OF(PxMetaDataArray<T>, mData); } static PX_FORCE_INLINE physx::PxU32 getSizeOffset() { return PX_OFFSET_OF(PxMetaDataArray<T>, mSize); } static PX_FORCE_INLINE physx::PxU32 getSizeSize() { return PX_SIZE_OF(PxMetaDataArray<T>, mSize); } static PX_FORCE_INLINE physx::PxU32 getCapacityOffset() { return PX_OFFSET_OF(PxMetaDataArray<T>, mCapacity); } static PX_FORCE_INLINE physx::PxU32 getCapacitySize() { return PX_SIZE_OF(PxMetaDataArray<T>, mCapacity); } }; void Sc::ActorCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxActorFlags, PxU8) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxDominanceGroup, PxU8) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxClientID, PxU8) PX_DEF_BIN_METADATA_CLASS(stream, Sc::ActorCore) PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, ActorSim, mSim, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxU32, mAggregateIDOwnerClient, 0) PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxActorFlags, mActorFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxU8, mActorType, 0) PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxU8, mDominanceGroup, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PxsRigidCore(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxsRigidCore) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxTransform, body2World, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxRigidBodyFlags, mFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxU16, solverIterationCounts, 0) } namespace { class ShadowPxsBodyCore : public PxsBodyCore { public: static void getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ShadowPxsBodyCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, ShadowPxsBodyCore, PxsRigidCore) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxTransform, body2Actor, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, ccdAdvanceCoefficient, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxVec3, linearVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxPenBias, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxVec3, angularVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, contactReportThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxAngularVelocitySq, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxLinearVelocitySq, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, linearDamping, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, angularDamping, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxVec3, inverseInertia, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, inverseMass, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxContactImpulse, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, sleepThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, freezeThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, wakeCounter, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, solverWakeCounter, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU32, numCountedInteractions, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, offsetSlop, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, isFastMoving, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, disableGravity, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, lockFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, fixedBaseLink, 0) } }; } static void getBinaryMetaData_PxsBodyCore(PxOutputStream& stream) { getBinaryMetaData_PxsRigidCore(stream); /* PX_DEF_BIN_METADATA_CLASS(stream, PxsBodyCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxsBodyCore, PxsRigidCore) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxTransform, body2Actor, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, ccdAdvanceCoefficient, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxVec3, linearVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxPenBias, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxVec3, angularVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, contactReportThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxAngularVelocitySq, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxLinearVelocitySq, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, linearDamping, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, angularDamping, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxVec3, inverseInertia, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, inverseMass, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxContactImpulse, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, sleepThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, freezeThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, wakeCounter, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, solverWakeCounter, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxU32, numCountedInteractions, 0)*/ ShadowPxsBodyCore::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxsBodyCore, ShadowPxsBodyCore) } /* We need to fix the header deps by moving the API out of PhysXCore and into its own dir where other code can get to it. [25.08.2010 18:34:57] Dilip Sequeira: In the meantime, I think it's Ok to include PxSDK.h, but you're right, we need to be very careful about include deps in that direction. [25.08.2010 18:38:15] Dilip Sequeira: On the memory thing... PxsBodyCore has 28 bytes of padding at the end, for no reason. In addition, it has two words of padding after the velocity fields, to facilitate SIMD loads. But in fact, Vec3FromVec4 is fast enough such that unless you were using it in an inner loop (which we never are with PxsBodyCore) that padding isn't worth it. [25.08.2010 18:38:58] Dilip Sequeira: So, we should drop the end-padding, and move the damping values to replace the velocity padding. This probably requires a bit of fixup in the places where we do SIMD writes to the velocity. [25.08.2010 18:39:18] Dilip Sequeira: Then we're down to 92 bytes of data, and 4 bytes of padding I think. [25.08.2010 18:50:41] Dilip Sequeira: The reason we don't want to put the sleep data there explicitly is that it isn't LL data so I'd rather not have it in an LL interface struct. [25.08.2010 19:04:53] Gordon Yeoman nvidia: simd loads are faster when they are 16-byte aligned. I think the padding might be to ensure the second vector is also 16-byte aligned. We could drop the second 4-byte pad but dropping the 1st 4-byte pad will likely have performance implications. [25.08.2010 19:06:22] Dilip Sequeira: We should still align the vec3s, as now - but we shouldn't use padding to do it, since there are a boatload of scalar data fields floating around in that struct too. */ void Sc::BodyCore::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_PxsBodyCore(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxRigidBodyFlags, PxU16) PX_DEF_BIN_METADATA_CLASS(stream, Sc::BodyCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, Sc::BodyCore, Sc::RigidCore) PX_DEF_BIN_METADATA_ITEM(stream, Sc::BodyCore, PxsBodyCore, mCore, 0) } /////////////////////////////////////////////////////////////////////////////// void Sc::ConstraintCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxConstraintFlags, PxU16) PX_DEF_BIN_METADATA_CLASS(stream, ConstraintCore) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintFlags, mFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxU8, mIsDirty, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, ConstraintCore, PxU8, mPadding, PxMetaDataFlag::ePADDING) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxVec3, mAppliedForce, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxVec3, mAppliedTorque, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintConnector, mConnector, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintSolverPrep, mSolverPrep, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintVisualize, mVisualize, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxU32, mDataSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxReal, mLinearBreakForce, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxReal, mAngularBreakForce, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxReal, mMinResponseThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, ConstraintSim, mSim, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void Sc::RigidCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, Sc::RigidCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, Sc::RigidCore, Sc::ActorCore) } /////////////////////////////////////////////////////////////////////////////// void Sc::StaticCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, Sc::StaticCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, Sc::StaticCore, Sc::RigidCore) PX_DEF_BIN_METADATA_ITEM(stream, Sc::StaticCore, PxsRigidCore, mCore, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PxFilterData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxFilterData) PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word1, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word2, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word3, 0) } namespace { class ShadowPxsShapeCore : public PxsShapeCore { public: static void getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ShadowPxsShapeCore) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxTransform, mTransform, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, GeometryUnion, mGeometry, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mContactOffset, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxShapeFlags, mShapeFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxShapeCoreFlags, mShapeCoreFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mRestOffset, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mTorsionalRadius, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mMinTorsionalPatchRadius, 0) } }; } static void getBinaryMetaData_PxsShapeCore(PxOutputStream& stream) { ShadowPxsShapeCore::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxsShapeCore, ShadowPxsShapeCore) } void Sc::ShapeCore::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_PxFilterData(stream); getBinaryMetaData_PxsShapeCore(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxShapeFlags, PxU8) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxShapeCoreFlags, PxU8) PX_DEF_BIN_METADATA_CLASS(stream, ShapeCore) PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, PxFilterData, mSimulationFilterData, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, PxsShapeCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, ShapeSim, mExclusiveSim, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, ShapeCore, mName, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_ArticulationCore(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, Dy::ArticulationCore) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxArticulationFlags, PxU8) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxU16, solverIterationCounts, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxArticulationFlags, flags, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, sleepThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, freezeThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, wakeCounter, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, gpuRemapIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, maxLinearVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, maxAngularVelocity, 0) } void Sc::ArticulationCore::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_ArticulationCore(stream); PX_DEF_BIN_METADATA_CLASS(stream, ArticulationCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationCore, ArticulationSim, mSim, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationCore, Dy::ArticulationCore, mCore, 0) } void Sc::ArticulationSensorCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ArticulationSensorCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSensorCore, ArticulationSensorSim, mSim, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSensorCore, PxTransform, mRelativePose, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSensorCore, PxU16, mFlags, 0) } void Sc::ArticulationAttachmentCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ArticulationAttachmentCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxVec3, mRelativeOffset, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, ArticulationAttachmentCore, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mLowLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mHighLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mRestLength, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mCoefficient, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxU32, mLLLinkIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxU32, mAttachmentIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, ArticulationSpatialTendonSim, mTendonSim, PxMetaDataFlag::ePTR) } void Sc::ArticulationTendonCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ArticulationTendonCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mStiffness, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mDamping, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mOffset, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mLimitStiffness, 0) } void Sc::ArticulationSpatialTendonCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ArticulationSpatialTendonCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, ArticulationSpatialTendonCore, ArticulationTendonCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSpatialTendonCore, ArticulationSpatialTendonSim, mSim, PxMetaDataFlag::ePTR) } void Sc::ArticulationFixedTendonCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ArticulationFixedTendonCore) PX_DEF_BIN_METADATA_BASE_CLASS(stream, ArticulationFixedTendonCore, ArticulationTendonCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, PxReal, mLowLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, PxReal, mHighLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, PxReal, mRestLength, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, ArticulationFixedTendonSim, mSim, PxMetaDataFlag::ePTR) } void Sc::ArticulationTendonJointCore::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxArticulationAxis, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, ArticulationTendonJointCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxArticulationAxis, axis, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxReal, coefficient, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxReal, recipCoefficient, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxU32, mLLLinkIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, ArticulationTendonJointCore, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxU32, mLLTendonJointIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, ArticulationFixedTendonSim, mTendonSim, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_ArticulationLimit(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxArticulationLimit) PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationLimit, PxReal, low, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationLimit, PxReal, high, 0) } static void getBinaryMetaData_ArticulationDrive(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxArticulationDriveType::Enum, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, PxArticulationDrive) PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxReal, stiffness, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxReal, damping, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxReal, maxForce, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxArticulationDriveType::Enum, driveType, 0) } static void getBinaryMetaData_ArticulationJointCore(PxOutputStream& stream) { getBinaryMetaData_ArticulationLimit(stream); getBinaryMetaData_ArticulationDrive(stream); PX_DEF_BIN_METADATA_CLASS(stream, Dy::ArticulationJointCore) PX_DEF_BIN_METADATA_TYPEDEF(stream, ArticulationJointCoreDirtyFlags, PxU8) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxTransform, parentPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxTransform, childPose, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxArticulationLimit, limits, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxArticulationDrive, drives, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, targetP, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, targetV, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, armature, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, jointPos, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, jointVel, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxReal, frictionCoefficient, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxU8, dofIds, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxU8, motion, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxU8, invDofIds, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxReal, maxJointVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, ArticulationJointCoreDirtyFlags, jointDirtyFlag, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxU32, jointOffset, 0) PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxU8, jointType, 0) } // //static void getBinaryMetaData_ArticulationJointCore(PxOutputStream& stream) //{ // getBinaryMetaData_ArticulationJointCoreBase(stream); // PX_DEF_BIN_METADATA_CLASS(stream, Dy::ArticulationJointCore) // PX_DEF_BIN_METADATA_BASE_CLASS(stream, Dy::ArticulationJointCore, Dy::ArticulationJointCoreBase) //} void Sc::ArticulationJointCore::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_ArticulationJointCore(stream); PX_DEF_BIN_METADATA_CLASS(stream, ArticulationJointCore) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, ArticulationJointSim, mSim, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, Dy::ArticulationJointCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, Dy::ArticulationCore, mArticulation, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, PxArticulationJointReducedCoordinate, mRootType, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, PxU32, mLLLinkIndex, 0) } /////////////////////////////////////////////////////////////////////////////// /* #define PX_DEF_BIN_METADATA_ARRAY(stream, Class, type, array) \ { PxMetaDataEntry tmp = {"void", #array".mData", PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getDataOffset(), PxMetaDataArray<type>::getDataSize(), 1, 0, PxMetaDataFlag::ePTR, 0}; PX_STORE_METADATA(stream, tmp); } \ { PxMetaDataEntry tmp = {"PxU32", #array".mSize", PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getSizeOffset(), PxMetaDataArray<type>::getSizeSize(), 1, 0, 0, 0}; PX_STORE_METADATA(stream, tmp); } \ { PxMetaDataEntry tmp = {"PxU32", #array".mCapacity", PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getCapacityOffset(), PxMetaDataArray<type>::getCapacitySize(), 1, 0, PxMetaDataFlag::eCOUNT_MASK_MSB, 0}; PX_STORE_METADATA(stream, tmp); } \ { PxMetaDataEntry tmp = {#type, 0, PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getSizeOffset(), PxMetaDataArray<type>::getSizeSize(), 0, 0, PxMetaDataFlag::eEXTRA_DATA, 0}; PX_STORE_METADATA(stream, tmp); } */ /////////////////////////////////////////////////////////////////////////////// void MaterialIndicesStruct::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, MaterialIndicesStruct) PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU16, indices, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU16, numIndices, 0) PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU16, pad, PxMetaDataFlag::ePADDING) PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU32, gpuRemapId, 0) //------ Extra-data ------ // indices PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, MaterialIndicesStruct, PxU16, indices, numIndices, PxMetaDataFlag::eHANDLE, PX_SERIAL_ALIGN) } /////////////////////////////////////////////////////////////////////////////// void GeometryUnion::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxGeometryType::Enum, PxU32) // The various PxGeometry classes are all public, so I can't really put the meta-data function in there. And then // I can't access their protected members. So we use the same trick as for the ShapeContainer class ShadowConvexMeshGeometry : public PxConvexMeshGeometryLL { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_TYPEDEF(stream_, PxConvexMeshGeometryFlags, PxU8) PX_DEF_BIN_METADATA_CLASS(stream_, ShadowConvexMeshGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, float, mTypePadding, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxMeshScale, scale, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxConvexMesh, convexMesh, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxConvexMeshGeometryFlags, meshFlags, 0) PX_DEF_BIN_METADATA_ITEMS(stream_, ShadowConvexMeshGeometry, PxU8, paddingFromFlags, PxMetaDataFlag::ePADDING, 3) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, bool, gpuCompatible, 0) } }; ShadowConvexMeshGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxConvexMeshGeometryLL, ShadowConvexMeshGeometry) ///////////////// class ShadowTriangleMeshGeometry : public PxTriangleMeshGeometryLL { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_TYPEDEF(stream_, PxMeshGeometryFlags, PxU8) PX_DEF_BIN_METADATA_CLASS(stream_, ShadowTriangleMeshGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, float, mTypePadding, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxMeshScale, scale, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxMeshGeometryFlags, meshFlags, 0) PX_DEF_BIN_METADATA_ITEMS(stream_, ShadowTriangleMeshGeometry, PxU8, paddingFromFlags, PxMetaDataFlag::ePADDING, 3) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxTriangleMesh, triangleMesh, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, MaterialIndicesStruct, materialsLL, 0) } }; ShadowTriangleMeshGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream,PxTriangleMeshGeometryLL, ShadowTriangleMeshGeometry) ///////////////// class ShadowHeightFieldGeometry : public PxHeightFieldGeometryLL { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowHeightFieldGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, float, mTypePadding, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxHeightField, heightField, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxReal, heightScale, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxReal, rowScale, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxReal, columnScale, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxMeshGeometryFlags, heightFieldFlags, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream_, ShadowHeightFieldGeometry, PxU8, paddingFromFlags, PxMetaDataFlag::ePADDING) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, MaterialIndicesStruct, materialsLL, 0) } }; ShadowHeightFieldGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream,PxHeightFieldGeometryLL, ShadowHeightFieldGeometry) ///////////////// class ShadowPlaneGeometry : public PxPlaneGeometry { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowPlaneGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowPlaneGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowPlaneGeometry, float, mTypePadding, 0) } }; ShadowPlaneGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream,PxPlaneGeometry, ShadowPlaneGeometry) ///////////////// class ShadowSphereGeometry : public PxSphereGeometry { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowSphereGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowSphereGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowSphereGeometry, float, mTypePadding, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowSphereGeometry, PxReal, radius, 0) } }; ShadowSphereGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxSphereGeometry, ShadowSphereGeometry) ///////////////// class ShadowCapsuleGeometry : public PxCapsuleGeometry { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowCapsuleGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, float, mTypePadding, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, PxReal, radius, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, PxReal, halfHeight, 0) } }; ShadowCapsuleGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxCapsuleGeometry, ShadowCapsuleGeometry) ///////////////// class ShadowBoxGeometry : public PxBoxGeometry { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowBoxGeometry) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBoxGeometry, PxGeometryType::Enum, mType, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBoxGeometry, float, mTypePadding, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBoxGeometry, PxVec3, halfExtents, 0) } }; ShadowBoxGeometry::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, PxBoxGeometry, ShadowBoxGeometry) /* - geom union offset & size - control type offset & size - type-to-class mapping */ PX_DEF_BIN_METADATA_CLASS(stream, GeometryUnion) PX_DEF_BIN_METADATA_UNION(stream, GeometryUnion, mGeometry) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxSphereGeometry, PxGeometryType::eSPHERE) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxPlaneGeometry, PxGeometryType::ePLANE) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxCapsuleGeometry, PxGeometryType::eCAPSULE) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxBoxGeometry, PxGeometryType::eBOX) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxConvexMeshGeometryLL, PxGeometryType::eCONVEXMESH) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxTriangleMeshGeometryLL,PxGeometryType::eTRIANGLEMESH) PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxHeightFieldGeometryLL, PxGeometryType::eHEIGHTFIELD) }
32,907
C++
51.6528
377
0.751664
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SC_PARTICLESYSTEM_SIM_H #define SC_PARTICLESYSTEM_SIM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxUserAllocated.h" #include "ScActorSim.h" #include "ScParticleSystemCore.h" #include "ScParticleSystemShapeSim.h" namespace physx { namespace Sc { class Scene; class ParticleSystemSim : public ActorSim { PX_NOCOPY(ParticleSystemSim) public: ParticleSystemSim(ParticleSystemCore& core, Scene& scene); ~ParticleSystemSim(); PX_INLINE Dy::ParticleSystem* getLowLevelParticleSystem() const { return mLLParticleSystem; } PX_INLINE ParticleSystemCore& getCore() const { return static_cast<ParticleSystemCore&>(mCore); } virtual PxActor* getPxActor() const { return getCore().getPxActor(); } void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; bool isSleeping() const; bool isActive() const { return true; } void sleepCheck(PxReal dt); void setActive(bool active, bool asPartOfCreation=false); const ParticleSystemShapeSim& getShapeSim() const { return mShapeSim; } ParticleSystemShapeSim& getShapeSim() { return mShapeSim; } private: Dy::ParticleSystem* mLLParticleSystem; ParticleSystemShapeSim mShapeSim; // PT: as far as I can tell these are never actually called // void activate(); // void deactivate(); }; } // namespace Sc } #endif #endif
3,052
C
35.783132
101
0.73329
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScRigidSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_RIGID_SIM_H #define SC_RIGID_SIM_H #include "ScActorSim.h" #include "ScRigidCore.h" namespace physx { namespace Sc { class Scene; class RigidSim : public ActorSim { public: RigidSim(Scene&, RigidCore&); virtual ~RigidSim(); PX_FORCE_INLINE RigidCore& getRigidCore() const { return static_cast<RigidCore&>(mCore); } void notifyShapesOfTransformChange(); void setBodyNodeIndex(const PxNodeIndex nodeIndex); virtual PxActor* getPxActor() const { return getRigidCore().getPxActor(); } }; } // namespace Sc } #endif
2,271
C
36.245901
92
0.747248
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScVisualize.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScScene.h" #include "ScNPhaseCore.h" #include "ScShapeInteraction.h" #include "ScConstraintSim.h" #include "ScConstraintCore.h" #include "CmVisualization.h" using namespace physx; using namespace Sc; // PT: Sc-level visualization code has been moved to this dedicated file (like we did in NpDebugViz.cpp) static void visualize(const ConstraintSim& sim, Cm::ConstraintImmediateVisualizer& viz, PxU32 flags, const PxTransform& idt) { ConstraintCore& core = sim.getCore(); if(!(core.getFlags() & PxConstraintFlag::eVISUALIZATION)) return; const Dy::Constraint& llc = sim.getLowLevelConstraint(); PxsRigidBody* b0 = llc.body0; PxsRigidBody* b1 = llc.body1; const PxTransform& t0 = b0 ? b0->getPose() : idt; const PxTransform& t1 = b1 ? b1->getPose() : idt; core.getVisualize()(viz, llc.constantBlock, t0, t1, flags); } void Sc::ShapeInteraction::visualize(PxRenderOutput& out, PxsContactManagerOutputIterator& outputs, float scale, float param_contactForce, float param_contactNormal, float param_contactError, float param_contactPoint) { if(mManager) // sleeping pairs have no contact points -> do not visualize { Sc::ActorSim* actorSim0 = &getShape0().getActor(); Sc::ActorSim* actorSim1 = &getShape1().getActor(); if(!actorSim0->isNonRigid() && !actorSim1->isNonRigid()) { PxU32 offset; PxU32 nextOffset = 0; do { const void* contactPatches; const void* contactPoints; PxU32 contactDataSize; PxU32 contactPointCount; PxU32 contactPatchCount; const PxReal* impulses; offset = nextOffset; nextOffset = getContactPointData(contactPatches, contactPoints, contactDataSize, contactPointCount, contactPatchCount, impulses, offset, outputs); const PxU32* faceIndices = reinterpret_cast<const PxU32*>(impulses + contactPointCount); PxContactStreamIterator iter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(contactPoints), faceIndices, contactPatchCount, contactPointCount); PxU32 i = 0; while(iter.hasNextPatch()) { iter.nextPatch(); while(iter.hasNextContact()) { iter.nextContact(); if((param_contactForce != 0.0f) && impulses) { out << PxU32(PxDebugColor::eARGB_RED); out.outputSegment(iter.getContactPoint(), iter.getContactPoint() + iter.getContactNormal() * (scale * param_contactForce * impulses[i])); } else if(param_contactNormal != 0.0f) { out << PxU32(PxDebugColor::eARGB_BLUE); out.outputSegment(iter.getContactPoint(), iter.getContactPoint() + iter.getContactNormal() * (scale * param_contactNormal)); } else if(param_contactError != 0.0f) { out << PxU32(PxDebugColor::eARGB_YELLOW); out.outputSegment(iter.getContactPoint(), iter.getContactPoint() + iter.getContactNormal() * PxAbs(scale * param_contactError * PxMin(0.f, iter.getSeparation()))); } if(param_contactPoint != 0.0f) { const PxReal s = scale * 0.1f; const PxVec3& point = iter.getContactPoint(); //if (0) //temp debug to see identical contacts // point.x += scale * 0.01f * (contactPointCount - i + 1); out << PxU32(PxDebugColor::eARGB_RED); out.outputSegment(point + PxVec3(-s, 0, 0), point + PxVec3(s, 0, 0)); out.outputSegment(point + PxVec3(0, -s, 0), point + PxVec3(0, s, 0)); out.outputSegment(point + PxVec3(0, 0, -s), point + PxVec3(0, 0, s)); } i++; } } } while (nextOffset != offset); } } } // Render objects before simulation starts void Sc::Scene::visualizeStartStep() { PX_PROFILE_ZONE("Sim.visualizeStartStep", mContextId); // Update from visualization parameters if(mVisualizationParameterChanged) { mVisualizationParameterChanged = false; // Update SIPs if visualization is enabled if( getVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT) || getVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL) || getVisualizationParameter(PxVisualizationParameter::eCONTACT_ERROR) || getVisualizationParameter(PxVisualizationParameter::eCONTACT_FORCE)) mInternalFlags |= SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_VISUALIZATION; } #if PX_ENABLE_DEBUG_VISUALIZATION const PxReal scale = getVisualizationScale(); if(scale==0.0f) { // make sure visualization inside simulate was skipped PX_ASSERT(getRenderBuffer().empty()); return; // early out if visualization scale is 0 } PxRenderOutput out(getRenderBuffer()); if(getVisualizationParameter(PxVisualizationParameter::eCOLLISION_COMPOUNDS)) mAABBManager->visualize(out); // Visualize joints { const float frameScale = scale * getVisualizationParameter(PxVisualizationParameter::eJOINT_LOCAL_FRAMES); const float limitScale = scale * getVisualizationParameter(PxVisualizationParameter::eJOINT_LIMITS); if(frameScale!=0.0f || limitScale!=0.0f) { Cm::ConstraintImmediateVisualizer viz(frameScale, limitScale, out); PxU32 flags = 0; if(frameScale!=0.0f) flags |= PxConstraintVisualizationFlag::eLOCAL_FRAMES; if(limitScale!=0.0f) flags |= PxConstraintVisualizationFlag::eLIMITS; const PxTransform idt(PxIdentity); Sc::ConstraintCore*const * constraints = mConstraints.getEntries(); for(PxU32 i=0, size = mConstraints.size();i<size; i++) { ConstraintSim* sim = constraints[i]->getSim(); if(sim) visualize(*sim, viz, flags, idt); } } } { // PT: put common reads here to avoid doing them for each interaction const PxReal param_contactForce = getVisualizationParameter(PxVisualizationParameter::eCONTACT_FORCE); const PxReal param_contactNormal = getVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL); const PxReal param_contactError = getVisualizationParameter(PxVisualizationParameter::eCONTACT_ERROR); const PxReal param_contactPoint = getVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT); if(param_contactForce!=0.0f || param_contactNormal!=0.0f || param_contactError!=0.0f || param_contactPoint!=0.0f) { PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); ElementSimInteraction** interactions = getActiveInteractions(InteractionType::eOVERLAP); PxU32 nbActiveInteractions = getNbActiveInteractions(InteractionType::eOVERLAP); while(nbActiveInteractions--) static_cast<ShapeInteraction*>(*interactions++)->visualize( out, outputs, scale, param_contactForce, param_contactNormal, param_contactError, param_contactPoint); } } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif }
8,345
C++
39.31884
177
0.731815
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScShapeSim.h" using namespace physx; using namespace Sc; void resetElementID(Scene& scene, ShapeSimBase& shapeSim); ShapeSim::ShapeSim(RigidSim& owner, ShapeCore& core) : ShapeSimBase(owner, &core) { initSubsystemsDependingOnElementID(); core.setExclusiveSim(this); } ShapeSim::~ShapeSim() { Sc::ShapeCore::getCore(*mLLShape.mShapeCore).setExclusiveSim(NULL); Scene& scScene = getScene(); resetElementID(scScene, *this); }
2,141
C++
42.714285
81
0.765063
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintInteraction.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScConstraintInteraction.h" #include "ScConstraintSim.h" #include "ScBodySim.h" #include "ScScene.h" #include "PxsRigidBody.h" #include "PxsSimpleIslandManager.h" using namespace physx; using namespace Sc; ConstraintInteraction::ConstraintInteraction(ConstraintSim* constraint, RigidSim& r0, RigidSim& r1) : Interaction (r0, r1, InteractionType::eCONSTRAINTSHADER, InteractionFlag::eCONSTRAINT), mConstraint (constraint) { { onActivate(NULL); registerInActors(); } BodySim* b0 = mConstraint->getBody(0); BodySim* b1 = mConstraint->getBody(1); if(b0) b0->onConstraintAttach(); if(b1) b1->onConstraintAttach(); IG::SimpleIslandManager* simpleIslandManager = getScene().getSimpleIslandManager(); mEdgeIndex = simpleIslandManager->addConstraint(&mConstraint->getLowLevelConstraint(), b0 ? b0->getNodeIndex() : PxNodeIndex(), b1 ? b1->getNodeIndex() : PxNodeIndex(), this); } ConstraintInteraction::~ConstraintInteraction() { PX_ASSERT(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)); PX_ASSERT(!getDirtyFlags()); PX_ASSERT(!mConstraint->readFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED)); } static PX_FORCE_INLINE void removeFromActiveBreakableList(ConstraintSim* constraint, Scene& s) { if(constraint->readFlag(ConstraintSim::eBREAKABLE | ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED) == (ConstraintSim::eBREAKABLE | ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED)) s.removeActiveBreakableConstraint(constraint); } void ConstraintInteraction::destroy() { setClean(true); // removes the pair from the dirty interaction list etc. Scene& scene = getScene(); removeFromActiveBreakableList(mConstraint, scene); if(mEdgeIndex != IG_INVALID_EDGE) scene.getSimpleIslandManager()->removeConnection(mEdgeIndex); mEdgeIndex = IG_INVALID_EDGE; unregisterFromActors(); BodySim* b0 = mConstraint->getBody(0); BodySim* b1 = mConstraint->getBody(1); if(b0) b0->onConstraintDetach(); // Note: Has to be done AFTER the interaction has unregistered from the actors if(b1) b1->onConstraintDetach(); // Note: Has to be done AFTER the interaction has unregistered from the actors clearInteractionFlag(InteractionFlag::eIS_ACTIVE); // ensures that broken constraints do not go into the list of active breakable constraints anymore } void ConstraintInteraction::updateState() { PX_ASSERT(!mConstraint->isBroken()); PX_ASSERT(getDirtyFlags() & InteractionDirtyFlag::eBODY_KINEMATIC); // at the moment this should be the only reason for this method being called // at least one of the bodies got switched from kinematic to dynamic. This will not have changed the sleep state of the interactions, so the // constraint interactions are just marked dirty and processed as part of the dirty interaction update system. // // -> need to check whether to activate the constraint and whether constraint break testing // is now necessary // // the transition from dynamic to kinematic will always trigger an onDeactivate() (because the body gets deactivated) // and thus there is no need to consider that case here. // onActivate(NULL); // note: this will not activate if the necessary conditions are not met, so it can be called even if the pair has been deactivated again before the // simulation step started } bool ConstraintInteraction::onActivate(void*) { PX_ASSERT(!mConstraint->isBroken()); BodySim* b0 = mConstraint->getBody(0); BodySim* b1 = mConstraint->getBody(1); const bool b0Vote = !b0 || b0->isActive(); const bool b1Vote = !b1 || b1->isActive(); const bool b0Dynamic = b0 && (!b0->isKinematic()); const bool b1Dynamic = b1 && (!b1->isKinematic()); // // note: constraints between kinematics and kinematics/statics are always inactive and must not be activated // if((b0Vote || b1Vote) && (b0Dynamic || b1Dynamic)) { raiseInteractionFlag(InteractionFlag::eIS_ACTIVE); if(mConstraint->readFlag(ConstraintSim::eBREAKABLE | ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED) == ConstraintSim::eBREAKABLE) getScene().addActiveBreakableConstraint(mConstraint, this); return true; } else return false; } bool ConstraintInteraction::onDeactivate() { const BodySim* b0 = mConstraint->getBody(0); const BodySim* b1 = mConstraint->getBody(1); const bool b0Dynamic = b0 && (!b0->isKinematic()); const bool b1Dynamic = b1 && (!b1->isKinematic()); PX_ASSERT( (!b0 && b1 && !b1->isActive()) || (!b1 && b0 && !b0->isActive()) || ((b0 && b1 && (!b0->isActive() || !b1->isActive()))) ); // // note: constraints between kinematics and kinematics/statics should always get deactivated // if(((!b0 || !b0->isActive()) && (!b1 || !b1->isActive())) || (!b0Dynamic && !b1Dynamic)) { removeFromActiveBreakableList(mConstraint, getScene()); clearInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } else return false; }
6,538
C++
37.017442
176
0.743194
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ACTOR_SIM_H #define SC_ACTOR_SIM_H #include "foundation/PxUserAllocated.h" #include "CmPtrTable.h" #include "CmUtils.h" #include "PxActor.h" #include "ScInteractionFlags.h" #include "ScActorCore.h" #include "PxsSimpleIslandManager.h" #include "PxFiltering.h" namespace physx { class PxActor; namespace Sc { #define SC_NOT_IN_SCENE_INDEX 0xffffffff // the body is not in the scene yet #define SC_NOT_IN_ACTIVE_LIST_INDEX 0xfffffffe // the body is in the scene but not in the active list struct PxFilterObjectFlagEx : PxFilterObjectFlag { enum Enum { eRIGID_STATIC = eNEXT_FREE, eRIGID_DYNAMIC = eNEXT_FREE<<1, eNON_RIGID = eNEXT_FREE<<2, eSOFTBODY = eNEXT_FREE<<3, eFEMCLOTH = eNEXT_FREE<<4, ePARTICLESYSTEM = eNEXT_FREE<<5, eHAIRSYSTEM = eNEXT_FREE<<6, eLAST = eHAIRSYSTEM }; }; static const PxReal ScInternalWakeCounterResetValue = 20.0f*0.02f; class Interaction; class ElementSim; class Scene; class ShapeManager : public PxUserAllocated { public: ShapeManager() {} ~ShapeManager() {} PX_FORCE_INLINE PxU32 getNbElements() const { return mShapes.getCount(); } PX_FORCE_INLINE ElementSim** getElements() { return reinterpret_cast<ElementSim**>(mShapes.getPtrs()); } PX_FORCE_INLINE ElementSim*const* getElements() const { return reinterpret_cast<ElementSim*const*>(mShapes.getPtrs()); } // void onElementAttach(ElementSim& element); void onElementDetach(ElementSim& element); Cm::PtrTable mShapes; }; class ActorSim : public ShapeManager { friend class Scene; // the scene is allowed to set the scene array index friend class Interaction; PX_NOCOPY(ActorSim) public: enum InternalFlags { //BF_DISABLE_GRAVITY = 1 << 0, // Don't apply the scene's gravity BF_HAS_STATIC_TOUCH = 1 << 1, // Set when a body is part of an island with static contacts. Needed to be able to recalculate adaptive force if this changes BF_KINEMATIC_MOVED = 1 << 2, // Set when the kinematic was moved BF_ON_DEATHROW = 1 << 3, // Set when the body is destroyed BF_IS_IN_SLEEP_LIST = 1 << 4, // Set when the body is added to the list of bodies which were put to sleep BF_IS_IN_WAKEUP_LIST = 1 << 5, // Set when the body is added to the list of bodies which were woken up BF_SLEEP_NOTIFY = 1 << 6, // A sleep notification should be sent for this body (and not a wakeup event, even if the body is part of the woken list as well) BF_WAKEUP_NOTIFY = 1 << 7, // A wake up notification should be sent for this body (and not a sleep event, even if the body is part of the sleep list as well) BF_HAS_CONSTRAINTS = 1 << 8, // Set if the body has one or more constraints BF_KINEMATIC_SETTLING = 1 << 9, // Set when the body was moved kinematically last frame BF_KINEMATIC_SETTLING_2 = 1 << 10, BF_KINEMATIC_MOVE_FLAGS = BF_KINEMATIC_MOVED | BF_KINEMATIC_SETTLING | BF_KINEMATIC_SETTLING_2, //Used to clear kinematic masks in 1 call BF_KINEMATIC_SURFACE_VELOCITY = 1 << 11, //Set when the application calls setKinematicVelocity. Actor remains awake until application calls clearKinematicVelocity. BF_IS_COMPOUND_RIGID = 1 << 12, // Set when the body is a compound actor, we dont want to set the sq bounds // PT: WARNING: flags stored on 16-bits now. }; ActorSim(Scene&, ActorCore&); virtual ~ActorSim(); // Get the scene the actor resides in PX_FORCE_INLINE Scene& getScene() const { return mScene; } // Get the number of interactions connected to the actor PX_FORCE_INLINE PxU32 getActorInteractionCount() const { return mInteractions.size(); } // Get an iterator to the interactions connected to the actor PX_FORCE_INLINE Interaction** getActorInteractions() const { return mInteractions.begin(); } // Get the type ID of the actor PX_FORCE_INLINE PxActorType::Enum getActorType() const { return mCore.getActorCoreType(); } // Returns true if the actor is a dynamic rigid body (including articulation links) PX_FORCE_INLINE PxU16 isDynamicRigid() const { return mFilterFlags & PxFilterObjectFlagEx::eRIGID_DYNAMIC; } PX_FORCE_INLINE PxU16 isSoftBody() const { return mFilterFlags & PxFilterObjectFlagEx::eSOFTBODY; } PX_FORCE_INLINE PxU16 isFEMCloth() const { return mFilterFlags & PxFilterObjectFlagEx::eFEMCLOTH; } PX_FORCE_INLINE PxU16 isParticleSystem() const { return mFilterFlags & PxFilterObjectFlagEx::ePARTICLESYSTEM; } PX_FORCE_INLINE PxU16 isHairSystem() const { return mFilterFlags & PxFilterObjectFlagEx::eHAIRSYSTEM; } PX_FORCE_INLINE PxU16 isNonRigid() const { return mFilterFlags & PxFilterObjectFlagEx::eNON_RIGID; } PX_FORCE_INLINE PxU16 isStaticRigid() const { return mFilterFlags & PxFilterObjectFlagEx::eRIGID_STATIC; } virtual void postActorFlagChange(PxU32, PxU32) {} void setActorsInteractionsDirty(InteractionDirtyFlag::Enum flag, const ActorSim* other, PxU8 interactionFlag); PX_FORCE_INLINE ActorCore& getActorCore() const { return mCore; } PX_FORCE_INLINE bool isActive() const { return (mActiveListIndex < SC_NOT_IN_ACTIVE_LIST_INDEX); } PX_FORCE_INLINE PxU32 getActiveListIndex() const { return mActiveListIndex; } // if the body is active, the index is smaller than SC_NOT_IN_ACTIVE_LIST_INDEX PX_FORCE_INLINE void setActiveListIndex(PxU32 index) { mActiveListIndex = index; } PX_FORCE_INLINE PxU32 getActiveCompoundListIndex() const { return mActiveCompoundListIndex; } // if the body is active and is compound, the index is smaller than SC_NOT_IN_ACTIVE_LIST_INDEX PX_FORCE_INLINE void setActiveCompoundListIndex(PxU32 index) { mActiveCompoundListIndex = index; } PX_FORCE_INLINE PxNodeIndex getNodeIndex() const { return mNodeIndex; } PX_FORCE_INLINE PxU32 getActorID() const { return mId; } PX_FORCE_INLINE PxU16 getInternalFlag() const { return mInternalFlags; } PX_FORCE_INLINE PxU16 readInternalFlag(InternalFlags flag) const { return PxU16(mInternalFlags & flag); } PX_FORCE_INLINE void raiseInternalFlag(InternalFlags flag) { mInternalFlags |= flag; } PX_FORCE_INLINE void clearInternalFlag(InternalFlags flag) { mInternalFlags &= ~flag; } PX_FORCE_INLINE PxFilterObjectAttributes getFilterAttributes() const { return PxFilterObjectAttributes(mFilterFlags); } virtual PxActor* getPxActor() const = 0; //This can all be removed and functionality can be subsumed by the island system, removing the need for this //virtual call and any associated work virtual void registerCountedInteraction() {} virtual void unregisterCountedInteraction() {} virtual PxU32 getNumCountedInteractions() const { return 0; } virtual void internalWakeUp(PxReal wakeCounterValue = ScInternalWakeCounterResetValue) { PX_UNUSED(wakeCounterValue); } private: //These are called from interaction creation/destruction void registerInteractionInActor(Interaction* interaction); void unregisterInteractionFromActor(Interaction* interaction); void reallocInteractions(Sc::Interaction**& mem, PxU32& capacity, PxU32 size, PxU32 requiredMinCapacity); protected: // dsequeira: interaction arrays are a major cause of small allocations, so we don't want to delegate them to the heap allocator // it's not clear this inline array is really needed, we should take it out and see whether the cache perf is worse static const PxU32 INLINE_INTERACTION_CAPACITY = 4; Interaction* mInlineInteractionMem[INLINE_INTERACTION_CAPACITY]; Cm::OwnedArray<Sc::Interaction*, Sc::ActorSim, PxU32, &Sc::ActorSim::reallocInteractions> mInteractions; Scene& mScene; ActorCore& mCore; // Sleeping PxU32 mActiveListIndex; // Used by Scene to track active bodies PxU32 mActiveCompoundListIndex; // Used by Scene to track active compound bodies // Island manager PxNodeIndex mNodeIndex; PxU32 mId; // PT: ID provided by Sc::Scene::mActorIDTracker PxU16 mInternalFlags; PxU16 mFilterFlags; // PT: PxFilterObjectAttributes. Capturing the type information in local flags here is redundant // but avoids reading the Core memory from the Sim object, and is also faster to test multiple types at once. }; } // namespace Sc } #endif
10,302
C
44.588495
198
0.713162
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeInteraction.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SHAPE_INTERACTION_H #define SC_SHAPE_INTERACTION_H #include "ScElementSimInteraction.h" #include "ScShapeSim.h" #include "ScActorPair.h" #include "ScScene.h" #include "ScBodySim.h" #include "PxsContactManager.h" #include "PxsContext.h" #include "PxsSimpleIslandManager.h" #define INVALID_REPORT_PAIR_ID 0xffffffff namespace physx { static PX_FORCE_INLINE bool isParticleSystem(const PxActorType::Enum actorType) { return actorType == PxActorType::ePBD_PARTICLESYSTEM || actorType == PxActorType::eFLIP_PARTICLESYSTEM || actorType == PxActorType::eMPM_PARTICLESYSTEM; } class PxsContactManagerOutputIterator; namespace Sc { class ContactReportAllocationManager; /* Description: A ShapeInteraction represents a pair of objects which _may_ have contacts. Created by the broadphase and processed by the NPhaseCore. */ class ShapeInteraction : public ElementSimInteraction { friend class NPhaseCore; ShapeInteraction& operator=(const ShapeInteraction&); public: enum SiFlag { PAIR_FLAGS_MASK = (PxPairFlag::eNEXT_FREE - 1), // Bits where the PxPairFlags get stored NEXT_FREE = ((PAIR_FLAGS_MASK << 1) & ~PAIR_FLAGS_MASK), HAS_TOUCH = (NEXT_FREE << 0), // Tracks the last know touch state HAS_NO_TOUCH = (NEXT_FREE << 1), // Tracks the last know touch state TOUCH_KNOWN = (HAS_TOUCH | HAS_NO_TOUCH), // If none of these flags is set, the touch state is not known (for example, this is true for pairs that never ran narrowphase CONTACTS_COLLECT_POINTS = (NEXT_FREE << 2), // The user wants to get the contact points (includes debug rendering) CONTACTS_RESPONSE_DISABLED = (NEXT_FREE << 3), // Collision response disabled (either by the user through PxPairFlag::eSOLVE_CONTACT or because the pair has two kinematics) CONTACT_FORCE_THRESHOLD_PAIRS = PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST), CONTACT_REPORT_EVENTS = PxU32(PxPairFlag::eNOTIFY_TOUCH_FOUND) | PxU32(PxPairFlag::eNOTIFY_TOUCH_PERSISTS) | PxU32(PxPairFlag::eNOTIFY_TOUCH_LOST) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST), CONTACT_REPORT_EXTRA_DATA = PxU32(PxPairFlag::ePRE_SOLVER_VELOCITY) | PxU32(PxPairFlag::ePOST_SOLVER_VELOCITY) | PxU32(PxPairFlag::eCONTACT_EVENT_POSE), FORCE_THRESHOLD_EXCEEDED_NOW = (NEXT_FREE << 4), FORCE_THRESHOLD_EXCEEDED_BEFORE = (NEXT_FREE << 5), FORCE_THRESHOLD_EXCEEDED_FLAGS = FORCE_THRESHOLD_EXCEEDED_NOW | FORCE_THRESHOLD_EXCEEDED_BEFORE, IS_IN_PERSISTENT_EVENT_LIST = (NEXT_FREE << 6), // The pair is in the list of persistent contact events WAS_IN_PERSISTENT_EVENT_LIST = (NEXT_FREE << 7), // The pair is inactive but used to be in the list of persistent contact events IN_PERSISTENT_EVENT_LIST = IS_IN_PERSISTENT_EVENT_LIST | WAS_IN_PERSISTENT_EVENT_LIST, IS_IN_FORCE_THRESHOLD_EVENT_LIST= (NEXT_FREE << 8), // The pair is in the list of force threshold contact events IS_IN_CONTACT_EVENT_LIST = IS_IN_PERSISTENT_EVENT_LIST | IS_IN_FORCE_THRESHOLD_EVENT_LIST, LL_MANAGER_RECREATE_EVENT = CONTACT_REPORT_EVENTS | CONTACTS_COLLECT_POINTS | CONTACTS_RESPONSE_DISABLED | PxU32(PxPairFlag::eMODIFY_CONTACTS) }; ShapeInteraction(ShapeSimBase& s1, ShapeSimBase& s2, PxPairFlags pairFlags, PxsContactManager* contactManager); ~ShapeInteraction(); // Submits to contact stream void processUserNotification(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform, PxsContactManagerOutputIterator& outputs); // ccdPass is 0 for discrete collision and then 1,2,... for the CCD passes void processUserNotificationSync(); void processUserNotificationAsync(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform, PxsContactManagerOutputIterator& outputs, ContactReportAllocationManager* alloc = NULL); // ccdPass is 0 for discrete collision and then 1,2,... for the CCD passes void visualize( PxRenderOutput&, PxsContactManagerOutputIterator&, float scale, float param_contactForce, float param_contactNormal, float param_contactError, float param_contactPoint ); PxU32 getContactPointData(const void*& contactPatches, const void*& contactPoints, PxU32& contactDataSize, PxU32& contactPointCount, PxU32& patchCount, const PxReal*& impulses, PxU32 startOffset, PxsContactManagerOutputIterator& outputs); bool managerLostTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs); void managerNewTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs); PX_FORCE_INLINE void adjustCountersOnLostTouch(); PX_FORCE_INLINE void adjustCountersOnNewTouch(); PX_FORCE_INLINE void sendCCDRetouch(PxU32 ccdPass, PxsContactManagerOutputIterator& outputs); void setContactReportPostSolverVelocity(ContactStreamManager& cs); PX_FORCE_INLINE void sendLostTouchReport(bool shapeVolumeRemoved, PxU32 ccdPass, PxsContactManagerOutputIterator& ouptuts); void resetManagerCachedState() const; PX_FORCE_INLINE ActorPair* getActorPair() const { return mActorPair; } PX_FORCE_INLINE void setActorPair(ActorPair& aPair) { mActorPair = &aPair; } PX_FORCE_INLINE void clearActorPair() { mActorPair = NULL; } PX_FORCE_INLINE ActorPairReport& getActorPairReport() const { return ActorPairReport::cast(*mActorPair); } PX_INLINE PxIntBool isReportPair() const { /*PX_ASSERT(!(PxIntBool(getPairFlags() & CONTACT_REPORT_EVENTS)) || mActorPair->isReportPair());*/ return PxIntBool(getPairFlags() & CONTACT_REPORT_EVENTS); } PX_INLINE PxIntBool hasTouch() const { return readFlag(HAS_TOUCH); } PX_INLINE PxIntBool hasCCDTouch() const { PX_ASSERT(mManager); return mManager->getHadCCDContact(); } PX_INLINE void swapAndClearForceThresholdExceeded(); PX_FORCE_INLINE void raiseFlag(SiFlag flag) { mFlags |= flag; } PX_FORCE_INLINE PxIntBool readFlag(SiFlag flag) const { return PxIntBool(mFlags & flag); } PX_FORCE_INLINE PxU32 getPairFlags() const; PX_FORCE_INLINE void removeFromReportPairList(); void onShapeChangeWhileSleeping(bool shapeOfDynamicChanged); PX_FORCE_INLINE PxIntBool hasKnownTouchState() const; bool onActivate(void* data); bool onDeactivate(); void updateState(const PxU8 externalDirtyFlags); const PxsContactManager* getContactManager() const { return mManager; } void clearIslandGenData(); PX_FORCE_INLINE PxU32 getEdgeIndex() const { return mEdgeIndex; } PX_FORCE_INLINE Sc::ShapeSimBase& getShape0() const { return static_cast<ShapeSimBase&>(getElement0()); } PX_FORCE_INLINE Sc::ShapeSimBase& getShape1() const { return static_cast<ShapeSimBase&>(getElement1()); } private: ActorPair* mActorPair; PxsContactManager* mManager; PxU32 mContactReportStamp; PxU32 mReportPairIndex; // Owned by NPhaseCore for its report pair list PxU32 mEdgeIndex; PxU16 mReportStreamIndex; // position of this pair in the contact report stream void createManager(void* contactManager); PX_INLINE bool updateManager(void* contactManager); PX_INLINE void destroyManager(); PX_FORCE_INLINE bool activeManagerAllowed() const; PX_FORCE_INLINE PxU32 getManagerContactState() const { return mFlags & LL_MANAGER_RECREATE_EVENT; } PX_FORCE_INLINE void clearFlag(SiFlag flag) { mFlags &= ~flag; } PX_INLINE void setFlag(SiFlag flag, bool value) { if (value) raiseFlag(flag); else clearFlag(flag); } PX_FORCE_INLINE void setHasTouch() { clearFlag(HAS_NO_TOUCH); raiseFlag(HAS_TOUCH); } PX_FORCE_INLINE void setHasNoTouch() { clearFlag(HAS_TOUCH); raiseFlag(HAS_NO_TOUCH); } PX_FORCE_INLINE void setPairFlags(PxPairFlags flags); PX_FORCE_INLINE void processReportPairOnActivate(); PX_FORCE_INLINE void processReportPairOnDeactivate(); // Certain SiFlag cache properties of the pair. If these properties change then the flags have to be updated. // For example: is collision enabled for this pair? are contact points requested for this pair? PX_FORCE_INLINE void updateFlags(const Sc::Scene&, const Sc::ActorSim&, const Sc::ActorSim&, const PxU32 pairFlags); friend class Sc::Scene; }; } // namespace Sc // PT: TODO: is there a reason for force-inlining all that stuff? PX_FORCE_INLINE void Sc::ShapeInteraction::sendLostTouchReport(bool shapeVolumeRemoved, PxU32 ccdPass, PxsContactManagerOutputIterator& outputs) { PX_ASSERT(hasTouch()); PX_ASSERT(isReportPair()); const PxU32 pairFlags = getPairFlags(); const PxU32 notifyTouchLost = pairFlags & PxU32(PxPairFlag::eNOTIFY_TOUCH_LOST); const PxIntBool thresholdExceeded = readFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_NOW); const PxU32 notifyThresholdLost = thresholdExceeded ? (pairFlags & PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST)) : 0; if(!notifyTouchLost && !notifyThresholdLost) return; PxU16 infoFlag = 0; if(mActorPair->getTouchCount() == 1) // this code assumes that the actor pair touch count does get decremented afterwards infoFlag |= PxContactPairFlag::eACTOR_PAIR_LOST_TOUCH; //Lost touch is processed after solver, so we should use the previous transform to update the pose for objects if user request eCONTACT_EVENT_POSE const bool useCurrentTransform = false; const PxU32 triggeredFlags = notifyTouchLost | notifyThresholdLost; PX_ASSERT(triggeredFlags); processUserNotification(triggeredFlags, infoFlag, true, ccdPass, useCurrentTransform, outputs); if(shapeVolumeRemoved) { ActorPairReport& apr = getActorPairReport(); ContactStreamManager& cs = apr.getContactStreamManager(); cs.raiseFlags(ContactStreamManagerFlag::eTEST_FOR_REMOVED_SHAPES); } } PX_FORCE_INLINE void Sc::ShapeInteraction::setPairFlags(PxPairFlags flags) { PX_ASSERT(PxU32(flags) < PxPairFlag::eNEXT_FREE); // to find out if a new PxPairFlag has been added after eLAST instead of in front PxU32 newFlags = mFlags; PxU32 fl = PxU32(flags) & PAIR_FLAGS_MASK; newFlags &= (~PAIR_FLAGS_MASK); // clear old flags newFlags |= fl; mFlags = newFlags; } // PT: returning PxU32 instead of PxPairFlags to remove LHS. Please do not undo this. PX_FORCE_INLINE PxU32 Sc::ShapeInteraction::getPairFlags() const { return (mFlags & PAIR_FLAGS_MASK); } PX_INLINE void Sc::ShapeInteraction::swapAndClearForceThresholdExceeded() { PxU32 flags = mFlags; PX_COMPILE_TIME_ASSERT(FORCE_THRESHOLD_EXCEEDED_NOW == (FORCE_THRESHOLD_EXCEEDED_BEFORE >> 1)); PxU32 nowToBefore = (flags & FORCE_THRESHOLD_EXCEEDED_NOW) << 1; flags &= ~(FORCE_THRESHOLD_EXCEEDED_NOW | FORCE_THRESHOLD_EXCEEDED_BEFORE); flags |= nowToBefore; mFlags = flags; } PX_FORCE_INLINE void Sc::ShapeInteraction::removeFromReportPairList() { // this method should only get called if the pair is in the list for // persistent or force based contact reports PX_ASSERT(mReportPairIndex != INVALID_REPORT_PAIR_ID); PX_ASSERT(readFlag(IS_IN_CONTACT_EVENT_LIST)); Scene& scene = getScene(); if (readFlag(IS_IN_FORCE_THRESHOLD_EVENT_LIST)) scene.getNPhaseCore()->removeFromForceThresholdContactEventPairs(this); else { PX_ASSERT(readFlag(IS_IN_PERSISTENT_EVENT_LIST)); scene.getNPhaseCore()->removeFromPersistentContactEventPairs(this); } } PX_INLINE bool Sc::ShapeInteraction::updateManager(void* contactManager) { if (activeManagerAllowed()) { if (mManager == 0) createManager(contactManager); return (mManager != NULL); // creation might fail (pool reached limit, mem allocation failed etc.) } else return false; } PX_INLINE void Sc::ShapeInteraction::destroyManager() { PX_ASSERT(mManager); Scene& scene = getScene(); PxvNphaseImplementationContext* nphaseImplementationContext = scene.getLowLevelContext()->getNphaseImplementationContext(); PX_ASSERT(nphaseImplementationContext); nphaseImplementationContext->unregisterContactManager(mManager); /*if (mEdgeIndex != IG_INVALID_EDGE) scene.getSimpleIslandManager()->clearEdgeRigidCM(mEdgeIndex);*/ scene.getLowLevelContext()->destroyContactManager(mManager); mManager = 0; } PX_FORCE_INLINE bool Sc::ShapeInteraction::activeManagerAllowed() const { ShapeSimBase& shape0 = getShape0(); ShapeSimBase& shape1 = getShape1(); ActorSim& bodySim0 = shape0.getActor(); ActorSim& bodySim1 = shape1.getActor(); // the first shape always belongs to a dynamic body or soft body #if PX_SUPPORT_GPU_PHYSX PX_ASSERT(bodySim0.isDynamicRigid() || bodySim0.isSoftBody() || bodySim0.isFEMCloth() || bodySim0.isParticleSystem() || bodySim0.isHairSystem()); #else PX_ASSERT(bodySim0.isDynamicRigid()); #endif // PT: try to prevent https://omniverse-jirasw.nvidia.com/browse/OM-103695 if(!bodySim0.getNodeIndex().isValid()) return false; const IG::IslandSim& islandSim = getScene().getSimpleIslandManager()->getSpeculativeIslandSim(); //check whether active in the speculative sim! return (islandSim.getNode(bodySim0.getNodeIndex()).isActive() || (!bodySim1.isStaticRigid() && islandSim.getNode(bodySim1.getNodeIndex()).isActive())); } PX_FORCE_INLINE void Sc::ShapeInteraction::sendCCDRetouch(PxU32 ccdPass, PxsContactManagerOutputIterator& outputs) { const PxU32 pairFlags = getPairFlags(); if (pairFlags & PxPairFlag::eNOTIFY_TOUCH_CCD) processUserNotification(PxPairFlag::eNOTIFY_TOUCH_CCD, 0, false, ccdPass, false, outputs); } PX_FORCE_INLINE void Sc::ShapeInteraction::adjustCountersOnLostTouch() { PX_ASSERT(mActorPair->getTouchCount()); mActorPair->decTouchCount(); } PX_FORCE_INLINE void Sc::ShapeInteraction::adjustCountersOnNewTouch() { mActorPair->incTouchCount(); } PX_FORCE_INLINE PxIntBool Sc::ShapeInteraction::hasKnownTouchState() const { // For a pair where the bodies were added asleep, the touch state is not known until narrowphase runs on the pair for the first time. // If such a pair looses AABB overlap before, the conservative approach is to wake the bodies up. This method provides an indicator that // this is such a pair. Note: this might also wake up objects that do not touch but that's the price to pay (unless we want to run // overlap tests on such pairs). if (mManager) return mManager->touchStatusKnown(); else return readFlag(TOUCH_KNOWN); } } #endif
16,460
C
44.09863
248
0.740522
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScConstraintCore.h" #include "ScPhysics.h" #include "ScConstraintSim.h" using namespace physx; Sc::ConstraintCore::ConstraintCore(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) : mFlags (PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES), mIsDirty (1), mAppliedForce (PxVec3(0.0f)), mAppliedTorque (PxVec3(0.0f)), mConnector (&connector), mSolverPrep (shaders.solverPrep), mVisualize (shaders.visualize), mDataSize (dataSize), mLinearBreakForce (PX_MAX_F32), mAngularBreakForce (PX_MAX_F32), mMinResponseThreshold (0.0f), mSim (NULL) { } void Sc::ConstraintCore::setFlags(PxConstraintFlags flags) { PxConstraintFlags old = mFlags; flags = flags | (old & PxConstraintFlag::eGPU_COMPATIBLE); if(flags != old) { mFlags = flags; if(mSim) mSim->postFlagChange(old, flags); } } void Sc::ConstraintCore::getForce(PxVec3& force, PxVec3& torque) const { if(!mSim) { force = PxVec3(0.0f); torque = PxVec3(0.0f); } else mSim->getForce(force, torque); } void Sc::ConstraintCore::setBodies(RigidCore* r0v, RigidCore* r1v) { if(mSim) mSim->setBodies(r0v, r1v); } void Sc::ConstraintCore::setBreakForce(PxReal linear, PxReal angular) { mLinearBreakForce = linear; mAngularBreakForce = angular; if(mSim) mSim->setBreakForceLL(linear, angular); } void Sc::ConstraintCore::setMinResponseThreshold(PxReal threshold) { mMinResponseThreshold = threshold; if(mSim) mSim->setMinResponseThresholdLL(threshold); } PxConstraint* Sc::ConstraintCore::getPxConstraint() { return gOffsetTable.convertScConstraint2Px(this); } const PxConstraint* Sc::ConstraintCore::getPxConstraint() const { return gOffsetTable.convertScConstraint2Px(this); } void Sc::ConstraintCore::breakApart() { // TODO: probably want to do something with the interaction here // as well as remove the constraint from LL. mFlags |= PxConstraintFlag::eBROKEN; }
3,642
C++
30.678261
126
0.750412
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationJointSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ARTICULATION_JOINT_SIM_H #define SC_ARTICULATION_JOINT_SIM_H #include "ScInteraction.h" namespace physx { namespace Sc { class ArticulationJointCore; class BodySim; class ArticulationJointSim : public Interaction { PX_NOCOPY(ArticulationJointSim) public: ArticulationJointSim(ArticulationJointCore& joint, ActorSim& parent, ActorSim& child); ~ArticulationJointSim(); bool onActivate(void*); bool onDeactivate(); PX_FORCE_INLINE ArticulationJointCore& getCore() const { return mCore; } BodySim& getParent() const; BodySim& getChild() const; void setDirty(); private: ArticulationJointCore& mCore; }; } // namespace Sc } #endif
2,434
C
35.893939
98
0.741578
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBodyCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScBodyCore.h" #include "ScBodySim.h" #include "ScPhysics.h" #include "ScScene.h" #include "PxsSimulationController.h" #include "ScArticulationSim.h" using namespace physx; static void updateBodySim(Sc::BodyCore& bodyCore) { Sc::BodySim* bodySim = bodyCore.getSim(); if(bodySim) bodySim->getScene().updateBodySim(*bodySim); } Sc::BodyCore::BodyCore(PxActorType::Enum type, const PxTransform& bodyPose) : RigidCore(type) { const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); const bool isDynamic = type == PxActorType::eRIGID_DYNAMIC; const float linearDamping = isDynamic ? 0.0f : 0.05f; const float maxLinearVelocitySq = isDynamic ? 1e32f /*PX_MAX_F32*/ : 100.f * 100.f * scale.length * scale.length; const float maxAngularVelocitySq = isDynamic ? 100.0f * 100.0f : 50.0f * 50.0f; mCore.init(bodyPose, PxVec3(1.0f), 1.0f, Sc::Physics::sWakeCounterOnCreation, scale.speed, linearDamping, 0.05f, maxLinearVelocitySq, maxAngularVelocitySq, type); } Sc::BodyCore::~BodyCore() { PX_ASSERT(getSim() == 0); } Sc::BodySim* Sc::BodyCore::getSim() const { return static_cast<BodySim*>(Sc::ActorCore::getSim()); } void Sc::BodyCore::restoreDynamicData() { BodySim* sim = getSim(); PX_ASSERT(sim); const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PxsBodyCore& core = getCore(); simStateRestoreBodyProperties(simStateData, core); } //-------------------------------------------------------------- // // BodyCore interface implementation // //-------------------------------------------------------------- void Sc::BodyCore::setBody2World(const PxTransform& p) { mCore.body2World = p; PX_ASSERT(p.p.isFinite()); PX_ASSERT(p.q.isFinite()); BodySim* sim = getSim(); if(sim) { sim->postBody2WorldChange(); sim->getScene().updateBodySim(*sim); } } void Sc::BodyCore::setCMassLocalPose(const PxTransform& newBody2Actor) { const PxTransform oldActor2World = mCore.body2World * mCore.getBody2Actor().getInverse(); const PxTransform newBody2World = oldActor2World * newBody2Actor; PX_ASSERT(newBody2World.p.isFinite()); PX_ASSERT(newBody2World.q.isFinite()); mCore.body2World = newBody2World; setBody2Actor(newBody2Actor); } void Sc::BodyCore::setLinearVelocity(const PxVec3& v, bool skipBodySimUpdate) { mCore.linearVelocity = v; PX_ASSERT(!skipBodySimUpdate || (getFlags() & PxRigidBodyFlag::eKINEMATIC)); if(!skipBodySimUpdate) updateBodySim(*this); } void Sc::BodyCore::setAngularVelocity(const PxVec3& v, bool skipBodySimUpdate) { mCore.angularVelocity = v; PX_ASSERT(!skipBodySimUpdate || (getFlags() & PxRigidBodyFlag::eKINEMATIC)); if(!skipBodySimUpdate) updateBodySim(*this); } void Sc::BodyCore::setCfmScale(PxReal cfmScale) { mCore.cfmScale = cfmScale; updateBodySim(*this); } void Sc::BodyCore::setBody2Actor(const PxTransform& p) { PX_ASSERT(p.p.isFinite()); PX_ASSERT(p.q.isFinite()); mCore.setBody2Actor(p); updateBodySim(*this); } void Sc::BodyCore::addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { BodySim* sim = getSim(); PX_ASSERT(sim); sim->addSpatialAcceleration(linAcc, angAcc); } void Sc::BodyCore::setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { BodySim* sim = getSim(); PX_ASSERT(sim); sim->setSpatialAcceleration(linAcc, angAcc); } void Sc::BodyCore::clearSpatialAcceleration(bool force, bool torque) { PX_ASSERT(force || torque); BodySim* sim = getSim(); PX_ASSERT(sim); sim->clearSpatialAcceleration(force, torque); } void Sc::BodyCore::addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta) { BodySim* sim = getSim(); PX_ASSERT(sim); sim->addSpatialVelocity(linVelDelta, angVelDelta); } void Sc::BodyCore::clearSpatialVelocity(bool force, bool torque) { PX_ASSERT(force || torque); BodySim* sim = getSim(); PX_ASSERT(sim); sim->clearSpatialVelocity(force, torque); } PxReal Sc::BodyCore::getInverseMass() const { BodySim* sim = getSim(); if(!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { return mCore.inverseMass; } else { const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); return simStateData->getKinematicData()->backupInvMass; } } void Sc::BodyCore::setInverseMass(PxReal m) { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { mCore.inverseMass = m; updateBodySim(*this); } else { SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); simStateData->getKinematicData()->backupInvMass = m; } } const PxVec3& Sc::BodyCore::getInverseInertia() const { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { return mCore.inverseInertia; } else { const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); return (simStateData->getKinematicData()->backupInverseInertia); } } void Sc::BodyCore::setInverseInertia(const PxVec3& i) { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { mCore.inverseInertia = i; updateBodySim(*this); } else { SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); simStateData->getKinematicData()->backupInverseInertia = i; } } PxReal Sc::BodyCore::getLinearDamping() const { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { return mCore.linearDamping; } else { const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); return (simStateData->getKinematicData()->backupLinearDamping); } } void Sc::BodyCore::setLinearDamping(PxReal d) { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { mCore.linearDamping = d; updateBodySim(*this); } else { SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); simStateData->getKinematicData()->backupLinearDamping = d; } } PxReal Sc::BodyCore::getAngularDamping() const { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { return mCore.angularDamping; } else { const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); return (simStateData->getKinematicData()->backupAngularDamping); } } void Sc::BodyCore::setAngularDamping(PxReal v) { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { mCore.angularDamping = v; updateBodySim(*this); } else { SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); simStateData->getKinematicData()->backupAngularDamping = v; } } PxReal Sc::BodyCore::getMaxAngVelSq() const { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { return mCore.maxAngularVelocitySq; } else { const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); return (simStateData->getKinematicData()->backupMaxAngVelSq); } } void Sc::BodyCore::setMaxAngVelSq(PxReal v) { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { mCore.maxAngularVelocitySq = v; updateBodySim(*this); } else { SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); simStateData->getKinematicData()->backupMaxAngVelSq = v; } } PxReal Sc::BodyCore::getMaxLinVelSq() const { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { return mCore.maxLinearVelocitySq; } else { const SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); return (simStateData->getKinematicData()->backupMaxLinVelSq); } } void Sc::BodyCore::setMaxLinVelSq(PxReal v) { BodySim* sim = getSim(); if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC))) { mCore.maxLinearVelocitySq = v; updateBodySim(*this); } else { SimStateData* simStateData = sim->getSimStateData(true); PX_ASSERT(simStateData); PX_ASSERT(simStateData->getKinematicData()); simStateData->getKinematicData()->backupMaxLinVelSq = v; } } void Sc::BodyCore::setFlags(PxRigidBodyFlags f) { const PxRigidBodyFlags old = mCore.mFlags; if(f != old) { const PxU32 wasKinematic = old & PxRigidBodyFlag::eKINEMATIC; const PxU32 isKinematic = f & PxRigidBodyFlag::eKINEMATIC; const bool switchToKinematic = ((!wasKinematic) && isKinematic); const bool switchToDynamic = (wasKinematic && (!isKinematic)); mCore.mFlags = f; BodySim* sim = getSim(); if (sim) { const PxU32 posePreviewFlag = f & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW; if(PxU32(old & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) != posePreviewFlag) sim->postPosePreviewChange(posePreviewFlag); // for those who might wonder about the complexity here: // our current behavior is that you are not allowed to set a kinematic target unless the object is in a scene. // Thus, the kinematic data should only be created/destroyed when we know for sure that we are in a scene. if(switchToKinematic) sim->switchToKinematic(); else if(switchToDynamic) sim->switchToDynamic(); const PxU32 wasSpeculativeCCD = old & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD; const PxU32 isSpeculativeCCD = f & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD; if(wasSpeculativeCCD ^ isSpeculativeCCD) { if(wasSpeculativeCCD) { sim->removeFromSpeculativeCCDMap(); sim->getLowLevelBody().mInternalFlags &= (~PxsRigidBody::eSPECULATIVE_CCD); } else { //Kinematic body switch puts the body to sleep, so we do not mark the speculative CCD bitmap for this actor to true in this case. if(!switchToKinematic) sim->addToSpeculativeCCDMap(); sim->getLowLevelBody().mInternalFlags |= (PxsRigidBody::eSPECULATIVE_CCD); } } const PxU32 wasIntegrateGyroscopic = old & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES; const PxU32 isIntegrateGyroscopic = f & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES; if (wasIntegrateGyroscopic ^ isIntegrateGyroscopic) { if(wasIntegrateGyroscopic) sim->getLowLevelBody().mInternalFlags &= (PxsRigidBody::eENABLE_GYROSCOPIC); else sim->getLowLevelBody().mInternalFlags |= (PxsRigidBody::eENABLE_GYROSCOPIC); } const PxU32 wasRetainAccel = old & PxRigidBodyFlag::eRETAIN_ACCELERATIONS; const PxU32 isRetainAccel = f & PxRigidBodyFlag::eRETAIN_ACCELERATIONS; if (wasRetainAccel ^ isRetainAccel) { if (wasRetainAccel) sim->getLowLevelBody().mInternalFlags &= (PxsRigidBody::eRETAIN_ACCELERATION); else sim->getLowLevelBody().mInternalFlags |= (PxsRigidBody::eRETAIN_ACCELERATION); } //Force flag change through... sim->getScene().updateBodySim(*sim); } if(switchToKinematic) putToSleep(); if(sim) { const PxRigidBodyFlags ktFlags(PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES | PxRigidBodyFlag::eKINEMATIC); const bool hadKt = (old & ktFlags) == ktFlags; const bool hasKt = (f & ktFlags) == ktFlags; if(hasKt && !hadKt) sim->destroySqBounds(); else if(hadKt && !hasKt) sim->createSqBounds(); } } } void Sc::BodyCore::setMaxContactImpulse(PxReal m) { mCore.maxContactImpulse = m; updateBodySim(*this); } void Sc::BodyCore::setOffsetSlop(PxReal slop) { mCore.offsetSlop = slop; updateBodySim(*this); } PxNodeIndex Sc::BodyCore::getInternalIslandNodeIndex() const { BodySim* sim = getSim(); return sim ? sim->getNodeIndex() : PxNodeIndex(PX_INVALID_NODE); } void Sc::BodyCore::setWakeCounter(PxReal wakeCounter, bool forceWakeUp) { mCore.wakeCounter = wakeCounter; BodySim* sim = getSim(); if(sim) { //wake counter change, we need to trigger dma pxgbodysim data again sim->getScene().updateBodySim(*sim); if ((wakeCounter > 0.0f) || forceWakeUp) sim->wakeUp(); sim->postSetWakeCounter(wakeCounter, forceWakeUp); } } void Sc::BodyCore::setSleepThreshold(PxReal t) { mCore.sleepThreshold = t; updateBodySim(*this); } void Sc::BodyCore::setFreezeThreshold(PxReal t) { mCore.freezeThreshold = t; updateBodySim(*this); } bool Sc::BodyCore::isSleeping() const { BodySim* sim = getSim(); return sim ? !sim->isActive() : true; } void Sc::BodyCore::putToSleep() { mCore.linearVelocity = PxVec3(0.0f); mCore.angularVelocity = PxVec3(0.0f); // important to clear all values before setting the wake counter because the values decide // whether an object is ready to go to sleep or not. setWakeCounter(0.0f); BodySim* sim = getSim(); if(sim) sim->putToSleep(); } void Sc::BodyCore::onOriginShift(const PxVec3& shift) { mCore.body2World.p -= shift; BodySim* b = getSim(); if(b) b->onOriginShift(shift, getFlags() & PxRigidBodyFlag::eKINEMATIC); // BodySim might not exist if actor has simulation disabled (PxActorFlag::eDISABLE_SIMULATION) } // PT: TODO: why do we test againt NULL everywhere but not in 'isFrozen' ? PxIntBool Sc::BodyCore::isFrozen() const { return getSim()->isFrozen(); } void Sc::BodyCore::setSolverIterationCounts(PxU16 c) { mCore.solverIterationCounts = c; Sc::BodySim* sim = getSim(); if (sim) { sim->getLowLevelBody().solverIterationCounts = c; sim->getScene().setDynamicsDirty(); } } /////////////////////////////////////////////////////////////////////////////// bool Sc::BodyCore::getKinematicTarget(PxTransform& p) const { PX_ASSERT(mCore.mFlags & PxRigidBodyFlag::eKINEMATIC); const BodySim* sim = getSim(); return (sim && simStateGetKinematicTarget(sim->getSimStateData_Unchecked(), p)); } bool Sc::BodyCore::getHasValidKinematicTarget() const { //The use pattern for this is that we should only look for kinematic data if we know it is kinematic. //We might look for velmod data even if it is kinematic. BodySim* sim = getSim(); return (sim && simStateGetHasValidKinematicTarget(sim->getSimStateData_Unchecked())); } void Sc::BodyCore::setKinematicTarget(const PxTransform& p, PxReal wakeCounter) { PX_ASSERT(mCore.mFlags & PxRigidBodyFlag::eKINEMATIC); Sc::BodySim* sim = getSim(); PX_ASSERT(sim); sim->setKinematicTarget(p); wakeUp(wakeCounter); } void Sc::BodyCore::invalidateKinematicTarget() { Sc::BodySim* sim = getSim(); PX_ASSERT(sim); simStateInvalidateKinematicTarget(sim->getSimStateData_Unchecked()); } void Sc::BodyCore::setFixedBaseLink(bool value) { BodySim* sim = getSim(); if(sim) sim->getLowLevelBody().mCore->fixedBaseLink = PxU8(value); } void Sc::BodyCore::onRemoveKinematicFromScene() { PX_ASSERT(mCore.mFlags & PxRigidBodyFlag::eKINEMATIC); PX_ASSERT(getSim() && getSim()->checkSimStateKinematicStatus(true)); // make sure that a kinematic which is not part of a scene is in the expected state mCore.wakeCounter = 0.0f; mCore.linearVelocity = PxVec3(0.0f); mCore.angularVelocity = PxVec3(0.0f); } ///////////////////////////////////////////////////////////////////////////////
17,153
C++
26.892683
164
0.714277
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ARTICULATION_SIM_H #define SC_ARTICULATION_SIM_H #include "foundation/PxUserAllocated.h" #include "ScArticulationCore.h" #include "PxsSimpleIslandManager.h" #include "DyArticulationTendon.h" namespace physx { namespace Bp { class BoundsArray; } namespace Sc { class BodySim; class BodyCore; class ArticulationJointSim; class ArticulationSpatialTendonSim; class ArticulationFixedTendonSim; class ArticulationSensorSim; class ArticulationCore; class Scene; class ConstraintSim; struct ArticulationSimDirtyFlag { enum Enum { eNONE = 0, eUPDATE = 1 << 0 }; }; typedef PxFlags<ArticulationSimDirtyFlag::Enum, PxU32> ArticulationSimDirtyFlags; class ArticulationSim : public PxUserAllocated { PX_NOCOPY(ArticulationSim) public: ArticulationSim(ArticulationCore& core, Scene& scene, BodyCore& root); ~ArticulationSim(); PX_FORCE_INLINE Dy::FeatherstoneArticulation* getLowLevelArticulation() const { return mLLArticulation; } PX_FORCE_INLINE ArticulationCore& getCore() const { return mCore; } //we don't need removeBody method anymore because when the articulation is removed from the scene, the articulation sim will //get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed void addBody(BodySim& body, BodySim* parent, ArticulationJointSim* joint); void removeBody(BodySim& body); //we don't need removeTendon method anymore because when the articulation is removed from the scene, the articulation sim will //get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed void addTendon(ArticulationSpatialTendonSim*); //we don't need removeTendon method anymore because when the articulation is removed from the scene, the articulation sim will //get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed void addTendon(ArticulationFixedTendonSim*); //we don't need removeSensor method anymore because when the articulation is removed from the scene, the articulation sim will //get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed void addSensor(ArticulationSensorSim* sensor, const PxU32 linkID); void createLLStructure(); // resize LL memory if necessary void initializeConfiguration(); void debugCheckWakeCounterOfLinks(PxReal wakeCounter) const; void debugCheckSleepStateOfLinks(bool isSleeping) const; bool isSleeping() const; void internalWakeUp(PxReal wakeCounter); // called when sim sets sleep timer void sleepCheck(PxReal dt); void putToSleep(); void updateCCDLinks(PxArray<BodySim*>& sims); void updateCached(PxBitMapPinned* shapehapeChangedMap); void markShapesUpdated(PxBitMapPinned* shapeChangedMap); void updateContactDistance(PxReal* contactDistance, PxReal dt, const Bp::BoundsArray& boundsArray); void setActive(bool b, bool asPartOfCreation=false); void updateForces(PxReal dt); void saveLastCCDTransform(); void clearAcceleration(PxReal dt); void setFixedBaseLink(bool value); //external reduced coordinate implementation PxU32 getDofs() const; //This function return the dof of the inbound joint, which belong to a link with corresponding linkID PxU32 getDof(const PxU32 linkID) const; PxArticulationCache* createCache(); PxU32 getCacheDataSize() const; void zeroCache(PxArticulationCache&) const; bool applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag) const; void copyInternalStateToCache (PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const; void packJointData(const PxReal* maximum, PxReal* reduced) const; void unpackJointData(const PxReal* reduced, PxReal* maximum) const; void commonInit(); void computeGeneralizedGravityForce(PxArticulationCache& cache); void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache); void computeGeneralizedExternalForce(PxArticulationCache& cache); void computeJointAcceleration(PxArticulationCache& cache); void computeJointForce(PxArticulationCache& cache); void computeKinematicJacobian(const PxU32 linkID, PxArticulationCache& cache); void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols); void computeCoefficientMatrix(PxArticulationCache& cache); bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* jointTorque, const PxVec3 gravity, const PxU32 maxIter); void computeGeneralizedMassMatrix(PxArticulationCache& cache); PxU32 getCoefficientMatrixSize() const; void setRootLinearVelocity(const PxVec3& velocity); void setRootAngularVelocity(const PxVec3& velocity); PxSpatialVelocity getLinkVelocity(const PxU32 linkId) const; PxSpatialVelocity getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const; //internal method implementation PX_FORCE_INLINE PxNodeIndex getIslandNodeIndex() const { return mIslandNodeIndex; } void setGlobalPose(); PxU32 findBodyIndex(BodySim &body) const; void setJointDirty(Dy::ArticulationJointCore& jointCore); void addLoopConstraint(ConstraintSim* constraint); void removeLoopConstraint(ConstraintSim* constraint); PX_FORCE_INLINE PxU32 getMaxDepth() { return mMaxDepth; } void setArticulationDirty(PxU32 flag); PX_FORCE_INLINE void setDirtyFlag(ArticulationSimDirtyFlag::Enum flag) { mDirtyFlags = flag; } PX_FORCE_INLINE ArticulationSimDirtyFlags getDirtyFlag() const { return mDirtyFlags; } PX_FORCE_INLINE const Dy::ArticulationLink& getLink(const PxU32 linkId) const { return mLinks[linkId]; } PxU32 getRootActorIndex() const; const PxSpatialForce& getSensorForce(const PxU32 lowLevelIndex) const; void updateKinematic(PxArticulationKinematicFlags flags); void copyJointStatus(const PxU32 linkIndex); PX_FORCE_INLINE void getLLArticulationInitialized(bool val) { mIsLLArticulationInitialized = val; } PX_FORCE_INLINE bool getLLArticulationInitialized() { return mIsLLArticulationInitialized; } private: Dy::FeatherstoneArticulation* mLLArticulation; Scene& mScene; ArticulationCore& mCore; PxArray<Dy::ArticulationLink> mLinks; PxArray<BodySim*> mBodies; PxArray<ArticulationJointSim*> mJoints; PxArray<Dy::ArticulationSpatialTendon*> mSpatialTendons; PxArray<Dy::ArticulationFixedTendon*> mFixedTendons; PxArray<Dy::ArticulationSensor*> mSensors; PxArray<PxSpatialForce> mSensorForces; PxNodeIndex mIslandNodeIndex; PxArray <Dy::ArticulationLoopConstraint> mLoopConstraints; PxU32 mMaxDepth; bool mIsLLArticulationInitialized; ArticulationSimDirtyFlags mDirtyFlags; }; } // namespace Sc } #endif
9,172
C
39.409691
162
0.727867
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimStateData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SIM_STATE_DATA_H #define SC_SIM_STATE_DATA_H #include "foundation/PxMemory.h" #include "ScBodyCore.h" namespace physx { namespace Sc { struct KinematicTransform { PxTransform targetPose; // The body will move to this pose over the superstep following this getting set. PxU8 targetValid; // User set a kinematic target. PxU8 pad[2]; PxU8 type; }; struct Kinematic : public KinematicTransform { // The following members buffer the original body data to restore them when switching back to dynamic body // (for kinematics the corresponding LowLevel properties are set to predefined values) PxVec3 backupInverseInertia; // The inverse of the body space inertia tensor PxReal backupInvMass; // The inverse of the body mass PxReal backupLinearDamping; // The velocity is scaled by (1.0f - this * dt) inside integrateVelocity() every substep. PxReal backupAngularDamping; PxReal backupMaxAngVelSq; // The angular velocity's magnitude is clamped to this maximum value. PxReal backupMaxLinVelSq; // The angular velocity's magnitude is clamped to this maximum value }; PX_COMPILE_TIME_ASSERT(0 == (sizeof(Kinematic) & 0x0f)); enum VelocityModFlags { VMF_GRAVITY_DIRTY = (1 << 0), VMF_ACC_DIRTY = (1 << 1), VMF_VEL_DIRTY = (1 << 2) }; // Important: Struct is reset in setForcesToDefaults. struct VelocityMod { PxVec3 linearPerSec; // A request to change the linear velocity by this much each second. The velocity is changed by this * dt inside integrateVelocity(). PxU8 pad0[4]; PxVec3 angularPerSec; PxU8 pad1[3]; PxU8 type; PxVec3 linearPerStep; // A request to change the linear velocity by this much the next step. The velocity is changed inside updateForces(). PxU32 pad2; PxVec3 angularPerStep; PxU32 pad3; PX_FORCE_INLINE void clear() { linearPerSec = angularPerSec = linearPerStep = angularPerStep = PxVec3(0.0f); } PX_FORCE_INLINE void clearPerStep() { linearPerStep = angularPerStep = PxVec3(0.0f); } PX_FORCE_INLINE const PxVec3& getLinearVelModPerSec() const { return linearPerSec; } PX_FORCE_INLINE void accumulateLinearVelModPerSec(const PxVec3& v) { linearPerSec += v; } PX_FORCE_INLINE void setLinearVelModPerSec(const PxVec3& v) { linearPerSec = v; } PX_FORCE_INLINE void clearLinearVelModPerSec() { linearPerSec = PxVec3(0.0f); } PX_FORCE_INLINE const PxVec3& getLinearVelModPerStep() const { return linearPerStep; } PX_FORCE_INLINE void accumulateLinearVelModPerStep(const PxVec3& v) { linearPerStep += v; } PX_FORCE_INLINE void clearLinearVelModPerStep() { linearPerStep = PxVec3(0.0f); } PX_FORCE_INLINE const PxVec3& getAngularVelModPerSec() const { return angularPerSec; } PX_FORCE_INLINE void accumulateAngularVelModPerSec(const PxVec3& v) { angularPerSec += v; } PX_FORCE_INLINE void setAngularVelModPerSec(const PxVec3& v) { angularPerSec = v; } PX_FORCE_INLINE void clearAngularVelModPerSec() { angularPerSec = PxVec3(0.0f); } PX_FORCE_INLINE const PxVec3& getAngularVelModPerStep() const { return angularPerStep; } PX_FORCE_INLINE void accumulateAngularVelModPerStep(const PxVec3& v) { angularPerStep += v; } PX_FORCE_INLINE void clearAngularVelModPerStep() { angularPerStep = PxVec3(0.0f); } }; PX_COMPILE_TIME_ASSERT(sizeof(VelocityMod) == sizeof(Kinematic)); // Structure to store data either for kinematics (target pose etc.) or for dynamics (vel and accel changes). // note: we do not delete this object for kinematics even if no target is set. struct SimStateData : public PxUserAllocated // TODO: may want to optimize the allocation of this further. { PxU8 data[sizeof(Kinematic)]; enum Enum { eVelMod=0, eKine }; SimStateData(){} SimStateData(const PxU8 type) { PxMemZero(data, sizeof(Kinematic)); Kinematic* kine = reinterpret_cast<Kinematic*>(data); kine->type = type; } PX_FORCE_INLINE PxU32 getType() const { const Kinematic* kine = reinterpret_cast<const Kinematic*>(data); return kine->type;} PX_FORCE_INLINE bool isKine() const {return eKine == getType();} PX_FORCE_INLINE bool isVelMod() const {return eVelMod == getType();} PX_FORCE_INLINE Kinematic* getKinematicData() { Kinematic* kine = reinterpret_cast<Kinematic*>(data); PX_ASSERT(eKine == kine->type); return kine;} PX_FORCE_INLINE VelocityMod* getVelocityModData() { VelocityMod* velmod = reinterpret_cast<VelocityMod*>(data); PX_ASSERT(eVelMod == velmod->type); return velmod;} PX_FORCE_INLINE const Kinematic* getKinematicData() const { const Kinematic* kine = reinterpret_cast<const Kinematic*>(data); PX_ASSERT(eKine == kine->type); return kine;} PX_FORCE_INLINE const VelocityMod* getVelocityModData() const { const VelocityMod* velmod = reinterpret_cast<const VelocityMod*>(data); PX_ASSERT(eVelMod == velmod->type); return velmod;} }; PX_FORCE_INLINE void simStateBackupAndClearBodyProperties(SimStateData* simStateData, PxsBodyCore& core) { PX_ASSERT(simStateData && simStateData->isKine()); Kinematic* kine = simStateData->getKinematicData(); kine->backupLinearDamping = core.linearDamping; kine->backupAngularDamping = core.angularDamping; kine->backupInverseInertia = core.inverseInertia; kine->backupInvMass = core.inverseMass; kine->backupMaxAngVelSq = core.maxAngularVelocitySq; kine->backupMaxLinVelSq = core.maxLinearVelocitySq; core.inverseMass = 0.0f; core.inverseInertia = PxVec3(0.0f); core.linearDamping = 0.0f; core.angularDamping = 0.0f; core.maxAngularVelocitySq = PX_MAX_REAL; core.maxLinearVelocitySq = PX_MAX_REAL; } PX_FORCE_INLINE void simStateRestoreBodyProperties(const SimStateData* simStateData, PxsBodyCore& core) { PX_ASSERT(simStateData && simStateData->isKine()); const Kinematic* kine = simStateData->getKinematicData(); core.inverseMass = kine->backupInvMass; core.inverseInertia = kine->backupInverseInertia; core.linearDamping = kine->backupLinearDamping; core.angularDamping = kine->backupAngularDamping; core.maxAngularVelocitySq = kine->backupMaxAngVelSq; core.maxLinearVelocitySq = kine->backupMaxLinVelSq; } PX_FORCE_INLINE void simStateClearVelMod(SimStateData* simStateData) { if (simStateData && simStateData->isVelMod()) { VelocityMod* velmod = simStateData->getVelocityModData(); velmod->clear(); } } PX_FORCE_INLINE bool simStateGetKinematicTarget(const SimStateData* simStateData, PxTransform& p) { if (simStateData && simStateData->isKine() && simStateData->getKinematicData()->targetValid) { p = simStateData->getKinematicData()->targetPose; return true; } else return false; } PX_FORCE_INLINE bool simStateGetHasValidKinematicTarget(const SimStateData* simStateData) { PX_ASSERT(!simStateData || simStateData->isKine()); return simStateData && simStateData->isKine() && simStateData->getKinematicData()->targetValid; } PX_FORCE_INLINE void simStateSetKinematicTarget(SimStateData* simStateData, const PxTransform& p) { PX_ASSERT(simStateData && simStateData->isKine()); // setting the kinematic target is only allowed if the body is part of a scene, at which point the // mSimStateData buffer must exist Kinematic* kine = simStateData->getKinematicData(); kine->targetPose = p; kine->targetValid = 1; } PX_FORCE_INLINE void simStateInvalidateKinematicTarget(SimStateData* simStateData) { PX_ASSERT(simStateData && simStateData->isKine()); simStateData->getKinematicData()->targetValid = 0; } } // namespace Sc } // namespace physx #endif
9,395
C
42.906542
189
0.734114
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScIterators.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScIterators.h" #include "ScBodySim.h" #include "ScShapeSim.h" #include "ScShapeInteraction.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// Sc::ContactIterator::Pair::Pair(const void*& contactPatches, const void*& contactPoints, PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches, ShapeSimBase& shape0, ShapeSimBase& shape1, ActorSim* actor0, ActorSim* actor1) : mIndex(0) , mNumContacts(numContacts) , mIter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(contactPoints), reinterpret_cast<const PxU32*>(forces + numContacts), numPatches, numContacts) , mForces(forces) , mActor0(actor0->getPxActor()) , mActor1(actor1->getPxActor()) { mCurrentContact.shape0 = shape0.getPxShape(); mCurrentContact.shape1 = shape1.getPxShape(); mCurrentContact.normalForceAvailable = (forces != NULL); } Sc::ContactIterator::Pair* Sc::ContactIterator::getNextPair() { PX_ASSERT(mCurrent || (mCurrent == mLast)); if(mCurrent < mLast) { ShapeInteraction* si = static_cast<ShapeInteraction*>(*mCurrent); const void* contactPatches = NULL; const void* contactPoints = NULL; PxU32 contactDataSize = 0; const PxReal* forces = NULL; PxU32 numContacts = 0; PxU32 numPatches = 0; PxU32 nextOffset = si->getContactPointData(contactPatches, contactPoints, contactDataSize, numContacts, numPatches, forces, mOffset, *mOutputs); if (nextOffset == mOffset) ++mCurrent; else mOffset = nextOffset; mCurrentPair = Pair(contactPatches, contactPoints, contactDataSize, forces, numContacts, numPatches, si->getShape0(), si->getShape1(), &si->getActorSim0(), &si->getActorSim1()); return &mCurrentPair; } else return NULL; } Sc::Contact* Sc::ContactIterator::Pair::getNextContact() { if(mIndex < mNumContacts) { if(!mIter.hasNextContact()) { if(!mIter.hasNextPatch()) return NULL; mIter.nextPatch(); } PX_ASSERT(mIter.hasNextContact()); mIter.nextContact(); mCurrentContact.normal = mIter.getContactNormal(); mCurrentContact.point = mIter.getContactPoint(); mCurrentContact.separation = mIter.getSeparation(); mCurrentContact.normalForce = mForces ? mForces[mIndex] : 0; mCurrentContact.faceIndex0 = mIter.getFaceIndex0(); mCurrentContact.faceIndex1 = mIter.getFaceIndex1(); mIndex++; return &mCurrentContact; } return NULL; } ///////////////////////////////////////////////////////////////////////////////
4,205
C++
37.944444
179
0.719857
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodyCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScSoftBodyCore.h" #include "ScFEMClothCore.h" #include "ScPhysics.h" #include "ScSoftBodySim.h" #include "DySoftBody.h" #include "GuTetrahedronMesh.h" #include "GuBV4.h" #include "geometry/PxTetrahedronMesh.h" using namespace physx; Sc::SoftBodyCore::SoftBodyCore() : ActorCore(PxActorType::eSOFTBODY, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0), mGpuMemStat(0) { const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); mCore.initialRotation = PxQuat(PxIdentity); mCore.sleepThreshold = 5e-5f * scale.speed * scale.speed; mCore.wakeCounter = Physics::sWakeCounterOnCreation; mCore.freezeThreshold = 5e-6f * scale.speed * scale.speed; mCore.maxPenBias = -1e32f;//-PX_MAX_F32; mCore.solverIterationCounts = (1 << 8) | 4; mCore.dirty = true; mCore.mFlags = PxSoftBodyFlags(0); mCore.mPositionInvMass = NULL; mCore.mRestPosition = NULL; mCore.mSimPositionInvMass = NULL; mCore.mSimVelocity = NULL; mCore.mKinematicTarget = NULL; } Sc::SoftBodyCore::~SoftBodyCore() { } void Sc::SoftBodyCore::setMaterial(const PxU16 handle) { mCore.setMaterial(handle); mCore.dirty = true; } void Sc::SoftBodyCore::clearMaterials() { mCore.clearMaterials(); mCore.dirty = true; } void Sc::SoftBodyCore::setFlags(PxSoftBodyFlags flags) { Sc::SoftBodySim* sim = getSim(); if (sim) { const bool wasDisabledSelfCollision = mCore.mFlags & PxSoftBodyFlag::eDISABLE_SELF_COLLISION; const bool isDisabledSelfCollision = flags & PxSoftBodyFlag::eDISABLE_SELF_COLLISION; if (wasDisabledSelfCollision != isDisabledSelfCollision) { if (isDisabledSelfCollision) sim->disableSelfCollision(); else sim->enableSelfCollision(); } } mCore.mFlags = flags; mCore.dirty = true; } template <typename I> void computeRestPoses(PxVec4* pInvMasses, PxMat33* tetraRestPoses, const I* const indices, const PxU32 nbTetra) { for (PxU32 i = 0; i < nbTetra; ++i) { const PxU32 startIndex = i * 4; // calculate rest pose const PxVec3 x0 = pInvMasses[indices[startIndex + 0]].getXYZ(); const PxVec3 x1 = pInvMasses[indices[startIndex + 1]].getXYZ(); const PxVec3 x2 = pInvMasses[indices[startIndex + 2]].getXYZ(); const PxVec3 x3 = pInvMasses[indices[startIndex + 3]].getXYZ(); const PxVec3 u1 = x1 - x0; const PxVec3 u2 = x2 - x0; const PxVec3 u3 = x3 - x0; PxMat33 Q = PxMat33(u1, u2, u3); tetraRestPoses[i] = Q.getInverse(); #if PX_CHECKED const float det = Q.getDeterminant(); if (fabsf(det) <= 1.e-9f) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeRestPoses(): Degenerate or inverted tetrahedron\n"); } #endif } } PxFEMParameters Sc::SoftBodyCore::getParameter() const { return mCore.parameters; } void Sc::SoftBodyCore::setParameter(const PxFEMParameters parameter) { mCore.parameters = parameter; mCore.dirty = true; } PxReal Sc::SoftBodyCore::getSleepThreshold() const { return mCore.sleepThreshold; } void Sc::SoftBodyCore::setSleepThreshold(const PxReal v) { mCore.sleepThreshold = v; mCore.dirty = true; } PxReal Sc::SoftBodyCore::getFreezeThreshold() const { return mCore.freezeThreshold; } void Sc::SoftBodyCore::setFreezeThreshold(const PxReal v) { mCore.freezeThreshold = v; mCore.dirty = true; } void Sc::SoftBodyCore::setSolverIterationCounts(const PxU16 c) { mCore.solverIterationCounts = c; mCore.dirty = true; } PxReal Sc::SoftBodyCore::getWakeCounter() const { return mCore.wakeCounter; } void Sc::SoftBodyCore::setWakeCounter(const PxReal v) { mCore.wakeCounter = v; mCore.dirty = true; Sc::SoftBodySim* sim = getSim(); if (sim) { sim->onSetWakeCounter(); } } void Sc::SoftBodyCore::setWakeCounterInternal(const PxReal v) { mCore.wakeCounter = v; mCore.dirty = true; Sc::SoftBodySim* sim = getSim(); if (sim) { sim->onSetWakeCounter(); } } bool Sc::SoftBodyCore::isSleeping() const { Sc::SoftBodySim* sim = getSim(); return sim ? sim->isSleeping() : (mCore.wakeCounter == 0.0f); } void Sc::SoftBodyCore::wakeUp(PxReal wakeCounter) { mCore.wakeCounter = wakeCounter; mCore.dirty = true; } void Sc::SoftBodyCore::putToSleep() { mCore.wakeCounter = 0.0f; mCore.dirty = true; } PxActor* Sc::SoftBodyCore::getPxActor() const { return PxPointerOffset<PxActor*>(const_cast<SoftBodyCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); } void Sc::SoftBodyCore::attachShapeCore(ShapeCore* shapeCore) { Sc::SoftBodySim* sim = getSim(); if (sim) { sim->attachShapeCore(shapeCore); mCore.dirty = true; } } void Sc::SoftBodyCore::attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState) { Sc::SoftBodySim* sim = getSim(); if (sim) { sim->attachSimulationMesh(simulationMesh, simulationState); mCore.dirty = true; } } Sc::SoftBodySim* Sc::SoftBodyCore::getSim() const { return static_cast<Sc::SoftBodySim*>(ActorCore::getSim()); } void Sc::SoftBodyCore::setSimulationFilterData(const PxFilterData& data) { mFilterData = data; } PxFilterData Sc::SoftBodyCore::getSimulationFilterData() const { return mFilterData; } void Sc::SoftBodyCore::addParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addParticleFilter(core, *sim, particleId, userBufferId, tetId); } void Sc::SoftBodyCore::removeParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().removeParticleFilter(core, *sim, particleId, userBufferId, tetId); } PxU32 Sc::SoftBodyCore::addParticleAttachment(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric) { Sc::SoftBodySim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) handle = sim->getScene().addParticleAttachment(core, *sim, particleId, userBufferId, tetId, barycentric); return handle; } void Sc::SoftBodyCore::removeParticleAttachment(Sc::ParticleSystemCore* core, PxU32 handle) { Sc::SoftBodySim* sim = getSim(); if (sim) { sim->getScene().removeParticleAttachment(core, *sim, handle); setWakeCounter(ScInternalWakeCounterResetValue); } } void Sc::SoftBodyCore::addRigidFilter(Sc::BodyCore* core, PxU32 vertId) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addRigidFilter(core, *sim, vertId); } void Sc::SoftBodyCore::removeRigidFilter(Sc::BodyCore* core, PxU32 vertId) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().removeRigidFilter(core, *sim, vertId); } PxU32 Sc::SoftBodyCore::addRigidAttachment(Sc::BodyCore* core, PxU32 particleId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { Sc::SoftBodySim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if(sim) handle = sim->getScene().addRigidAttachment(core, *sim, particleId, actorSpacePose, constraint); return handle; } void Sc::SoftBodyCore::removeRigidAttachment(Sc::BodyCore* core, PxU32 handle) { Sc::SoftBodySim* sim = getSim(); if (sim) { sim->getScene().removeRigidAttachment(core, *sim, handle); setWakeCounter(ScInternalWakeCounterResetValue); } } void Sc::SoftBodyCore::addTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addTetRigidFilter(core, *sim, tetIdx); } void Sc::SoftBodyCore::removeTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx) { Sc::SoftBodySim* sim = getSim(); if (sim) { sim->getScene().removeTetRigidFilter(core, *sim, tetIdx); } } PxU32 Sc::SoftBodyCore::addTetRigidAttachment(Sc::BodyCore* core, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { Sc::SoftBodySim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) handle = sim->getScene().addTetRigidAttachment(core, *sim, tetIdx, barycentric, actorSpacePose, constraint); return handle; } void Sc::SoftBodyCore::addSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addSoftBodyFilter(core, tetIdx0, *sim, tetIdx1); } void Sc::SoftBodyCore::removeSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().removeSoftBodyFilter(core, tetIdx0, *sim, tetIdx1); } void Sc::SoftBodyCore::addSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addSoftBodyFilters(core, *sim, tetIndices0, tetIndices1, tetIndicesSize); } void Sc::SoftBodyCore::removeSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().removeSoftBodyFilters(core, *sim, tetIndices0, tetIndices1, tetIndicesSize); } PxU32 Sc::SoftBodyCore::addSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset) { Sc::SoftBodySim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) handle = sim->getScene().addSoftBodyAttachment(core, tetIdx0, triBarycentric0, *sim, tetIdx1, tetBarycentric1, constraint, constraintOffset); return handle; } void Sc::SoftBodyCore::removeSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 handle) { Sc::SoftBodySim* sim = getSim(); setWakeCounterInternal(ScInternalWakeCounterResetValue); core.setWakeCounterInternal(ScInternalWakeCounterResetValue); if (sim) sim->getScene().removeSoftBodyAttachment(core, *sim, handle); } void Sc::SoftBodyCore::addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addClothFilter(core, triIdx, *sim, tetIdx); } void Sc::SoftBodyCore::removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().removeClothFilter(core, triIdx, *sim, tetIdx); } void Sc::SoftBodyCore::addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().addVertClothFilter(core, vertIdx, *sim, tetIdx); } void Sc::SoftBodyCore::removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx) { Sc::SoftBodySim* sim = getSim(); if (sim) sim->getScene().removeVertClothFilter(core, vertIdx, *sim, tetIdx); } PxU32 Sc::SoftBodyCore::addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset) { Sc::SoftBodySim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) handle = sim->getScene().addClothAttachment(core, triIdx, triBarycentric, *sim, tetIdx, tetBarycentric, constraint, constraintOffset); return handle; } void Sc::SoftBodyCore::removeClothAttachment(Sc::FEMClothCore& core, PxU32 handle) { Sc::SoftBodySim* sim = getSim(); setWakeCounter(ScInternalWakeCounterResetValue); core.setWakeCounter(ScInternalWakeCounterResetValue); if (sim) sim->getScene().removeClothAttachment(core, *sim, handle); } PxU32 Sc::SoftBodyCore::getGpuSoftBodyIndex() const { const Sc::SoftBodySim* sim = getSim(); return sim ? sim->getGpuSoftBodyIndex() : 0xffffffff; } void Sc::SoftBodyCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags) { PX_UNUSED(shape); SoftBodySim* sim = getSim(); if (!sim) return; SoftBodyShapeSim& s = sim->getShapeSim(); if (notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY) s.onVolumeOrTransformChange(); if (notifyFlags & ShapeChangeNotifyFlag::eMATERIAL) s.onMaterialChange(); if (notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING) s.onResetFiltering(); if (notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY) s.onVolumeOrTransformChange(); if (notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA) s.onFilterDataChange(); if (notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET) s.onContactOffsetChange(); if (notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET) s.onRestOffsetChange(); } void Sc::SoftBodyCore::setKinematicTargets(const PxVec4* positions, PxSoftBodyFlags flags) { mCore.mKinematicTarget = positions; if (positions != NULL) { mCore.mFlags |= PxSoftBodyFlags(flags & PxSoftBodyFlags(PxSoftBodyFlag::eKINEMATIC | PxSoftBodyFlag::ePARTIALLY_KINEMATIC)); } else { mCore.mFlags.clear(PxSoftBodyFlag::eKINEMATIC); mCore.mFlags.clear(PxSoftBodyFlag::ePARTIALLY_KINEMATIC); } mCore.dirty = true; } #endif //PX_SUPPORT_GPU_PHYSX
14,426
C++
26.637931
161
0.745598
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScArticulationSim.h" #include "ScArticulationCore.h" #include "ScArticulationJointSim.h" #include "ScArticulationJointCore.h" #include "ScBodySim.h" #include "ScConstraintSim.h" #include "ScArticulationTendonSim.h" #include "ScArticulationSensorSim.h" #include "ScArticulationSensor.h" #include "ScScene.h" #include "DyConstraint.h" #include "DyFeatherstoneArticulation.h" #include "PxsContext.h" #include "CmSpatialVector.h" #include "foundation/PxVecMath.h" #include "PxsSimpleIslandManager.h" #include "ScShapeSim.h" #include "PxsSimulationController.h" using namespace physx; using namespace physx::Dy; Sc::ArticulationSim::ArticulationSim(ArticulationCore& core, Scene& scene, BodyCore& root) : mLLArticulation (NULL), mScene (scene), mCore (core), mLinks ("ScArticulationSim::links"), mBodies ("ScArticulationSim::bodies"), mJoints ("ScArticulationSim::joints"), mMaxDepth (0), mIsLLArticulationInitialized(false) { mLinks.reserve(16); mJoints.reserve(16); mBodies.reserve(16); mLLArticulation = mScene.createLLArticulation(this); mIslandNodeIndex = scene.getSimpleIslandManager()->addArticulation(mLLArticulation, false); if(!mLLArticulation) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation: could not allocate low-level resources."); return; } PX_ASSERT(root.getSim()); addBody(*root.getSim(), NULL, NULL); mCore.setSim(this); mLLArticulation->setDyContext(mScene.getDynamicsContext()); mLLArticulation->getSolverDesc().initData(&core.getCore(), NULL); //mLLArticulation->onUpdateSolverDesc(); } Sc::ArticulationSim::~ArticulationSim() { if (!mLLArticulation) return; mScene.destroyLLArticulation(*mLLArticulation); mScene.getSimpleIslandManager()->removeNode(mIslandNodeIndex); mCore.setSim(NULL); } PxU32 Sc::ArticulationSim::findBodyIndex(BodySim& body) const { for(PxU32 i=0; i<mBodies.size(); i++) { if(mBodies[i]==&body) return i; } PX_ASSERT(0); return 0x80000000; } void Sc::ArticulationSim::addLoopConstraint(ConstraintSim* constraintSim) { const PxU32 size = mLoopConstraints.size(); if (size < mLoopConstraints.size()) mLoopConstraints.reserve(size*2 + 1); BodySim* bodySim0 = constraintSim->getBody(0); BodySim* bodySim1 = constraintSim->getBody(1); ArticulationLoopConstraint lConstraint; if (bodySim0) lConstraint.linkIndex0 = findBodyIndex(*bodySim0); else lConstraint.linkIndex0 = 0x80000000; if(bodySim1) lConstraint.linkIndex1 = findBodyIndex(*bodySim1); else lConstraint.linkIndex1 = 0x80000000; lConstraint.constraint = &constraintSim->getLowLevelConstraint(); mLoopConstraints.pushBack(lConstraint); } void Sc::ArticulationSim::removeLoopConstraint(ConstraintSim* constraintSim) { Dy::Constraint* constraint = &constraintSim->getLowLevelConstraint(); const PxU32 size = mLoopConstraints.size(); PxU32 index = 0; while (index < size && mLoopConstraints[index].constraint != constraint) ++index; if (index != size) mLoopConstraints.replaceWithLast(index); } void Sc::ArticulationSim::updateCached(PxBitMapPinned* shapeChangedMap) { for(PxU32 i=0; i<mBodies.size(); i++) mBodies[i]->updateCached(shapeChangedMap); } void Sc::ArticulationSim::markShapesUpdated(PxBitMapPinned* shapeChangedMap) { for (PxU32 a = 0; a < mBodies.size(); ++a) { PxU32 nbElems = mBodies[a]->getNbElements(); ElementSim** elems = mBodies[a]->getElements(); while (nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); if (sim->isInBroadPhase()) shapeChangedMap->growAndSet(sim->getElementID()); } } } void Sc::ArticulationSim::addBody(BodySim& body, BodySim* parent, ArticulationJointSim* joint) { mBodies.pushBack(&body); mJoints.pushBack(joint); mLLArticulation->addBody(); const PxU32 index = mLinks.size(); PX_ASSERT((((index==0) && (joint == 0)) && (parent == 0)) || (((index!=0) && joint) && (parent && (parent->getArticulation() == this)))); ArticulationLink& link = mLinks.insert(); link.bodyCore = &body.getBodyCore().getCore(); link.children = 0; link.mPathToRootStartIndex = 0; link.mPathToRootCount = 0; link.mChildrenStartIndex = 0xffffffff; link.mNumChildren = 0; bool shouldSleep; bool currentlyAsleep; const bool bodyReadyForSleep = body.checkSleepReadinessBesidesWakeCounter(); const PxReal wakeCounter = getCore().getWakeCounter(); if(parent) { currentlyAsleep = !mBodies[0]->isActive(); shouldSleep = currentlyAsleep && bodyReadyForSleep; PxU32 parentIndex = findBodyIndex(*parent); link.parent = parentIndex; ArticulationLink& parentLink = mLinks[parentIndex]; link.pathToRoot = parentLink.pathToRoot | ArticulationBitField(1)<<index; link.inboundJoint = &joint->getCore().getCore(); parentLink.children |= ArticulationBitField(1)<<index; if (parentLink.mChildrenStartIndex == 0xffffffff) parentLink.mChildrenStartIndex = index; parentLink.mNumChildren++; } else { currentlyAsleep = (wakeCounter == 0.0f); shouldSleep = currentlyAsleep && bodyReadyForSleep; link.parent = DY_ARTICULATION_LINK_NONE; link.pathToRoot = 1; link.inboundJoint = NULL; } if(currentlyAsleep && !shouldSleep) { for(PxU32 i=0; i < (mBodies.size() - 1); i++) mBodies[i]->internalWakeUpArticulationLink(wakeCounter); } body.setArticulation(this, wakeCounter, shouldSleep, index); } void Sc::ArticulationSim::removeBody(BodySim& body) { for (PxU32 i = 0; i < mBodies.size(); ++i) { if (mBodies[i] == &body) { mBodies.replaceWithLast(i); mJoints.replaceWithLast(i); break; } } } void Sc::ArticulationSim::addTendon(ArticulationSpatialTendonSim* tendonSim) { tendonSim->mArtiSim = this; const PxU32 index = mSpatialTendons.size(); Dy::ArticulationSpatialTendon& llTendon = tendonSim->mLLTendon; llTendon.setTendonIndex(index); mSpatialTendons.pushBack(&llTendon); //mSpatialTendons.pushBack(&tendonSim->mLLTendon); } void Sc::ArticulationSim::addTendon(ArticulationFixedTendonSim* tendonSim) { tendonSim->mArtiSim = this; const PxU32 index = mFixedTendons.size(); Dy::ArticulationFixedTendon& llTendon = tendonSim->mLLTendon; llTendon.setTendonIndex(index); mFixedTendons.pushBack(&llTendon); } void Sc::ArticulationSim::addSensor(ArticulationSensorSim* sensorSim, const PxU32 linkID) { const PxU32 index = mSensors.size(); sensorSim->setLowLevelIndex(index); sensorSim->mArticulationSim = this; Dy::ArticulationSensor& llSensor = sensorSim->getLLSensor(); llSensor.mLinkID = PxU16(linkID); mSensors.pushBack(&llSensor); mSensorForces.insert(); mSensorForces.back().force = PxVec3(0.f); mSensorForces.back().torque = PxVec3(0.f); } void Sc::ArticulationSim::createLLStructure() { if(!mBodies.size()) return; mLLArticulation->setupLinks(mLinks.size(), const_cast<Dy::ArticulationLink*>(mLinks.begin())); mLLArticulation->assignTendons(mSpatialTendons.size(), const_cast<Dy::ArticulationSpatialTendon**>(mSpatialTendons.begin())); mLLArticulation->assignTendons(mFixedTendons.size(), const_cast<Dy::ArticulationFixedTendon**>(mFixedTendons.begin())); mLLArticulation->assignSensors(mSensors.size(), const_cast<Dy::ArticulationSensor**>(mSensors.begin()), const_cast<PxSpatialForce*>(mSensorForces.begin())); mIsLLArticulationInitialized = true; } void Sc::ArticulationSim::initializeConfiguration() { Dy::ArticulationData& data = mLLArticulation->getArticulationData(); mLLArticulation->jcalc(data); mLLArticulation->mJcalcDirty = false; Dy::ArticulationLink* links = data.getLinks(); Dy::ArticulationJointCoreData* jointData = data.getJointData(); const PxU32 linkCount = data.getLinkCount(); PxReal* jointVelocites = data.getJointVelocities(); PxReal* jointPositions = data.getJointPositions(); PxReal* jointTargetPositions = data.getJointTargetPositions(); PxReal* jointTargetVelocities = data.getJointTargetVelocities(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { Dy::ArticulationLink& link = links[linkID]; Dy::ArticulationJointCore* joint = link.inboundJoint; Dy::ArticulationJointCoreData& jointDatum = jointData[linkID]; PxReal* jPositions = &jointPositions[jointDatum.jointOffset]; PxReal* jVelocites = &jointVelocites[jointDatum.jointOffset]; PxReal* jTargetPositions = &jointTargetPositions[jointDatum.jointOffset]; PxReal* jTargetVelocities = &jointTargetVelocities[jointDatum.jointOffset]; for (PxU8 i = 0; i < jointDatum.dof; ++i) { const PxU32 dofId = joint->dofIds[i]; jPositions[i] = joint->jointPos[dofId]; jVelocites[i] = joint->jointVel[dofId]; jTargetPositions[i] = joint->targetP[dofId]; jTargetVelocities[i] = joint->targetV[dofId]; } } PxU32 flags = (Dy::ArticulationDirtyFlag::eDIRTY_POSITIONS | Dy::ArticulationDirtyFlag::eDIRTY_VELOCITIES | Dy::ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_POS | Dy::ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_VEL); mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::Enum(flags)); mLLArticulation->initPathToRoot(); } void Sc::ArticulationSim::updateKinematic(PxArticulationKinematicFlags flags) { Dy::ArticulationData& data = mLLArticulation->getArticulationData(); if (mLLArticulation->mJcalcDirty) { mLLArticulation->jcalc(data); mLLArticulation->mJcalcDirty = false; } if ((flags & PxArticulationKinematicFlag::ePOSITION)) { mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_POSITIONS); mLLArticulation->teleportLinks(data); } if ((flags & PxArticulationKinematicFlag::ePOSITION) || (flags & PxArticulationKinematicFlag::eVELOCITY)) { mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITIES); mLLArticulation->computeLinkVelocities(data); } } void Sc::ArticulationSim::copyJointStatus(const PxU32 linkID) { Dy::ArticulationData& data = mLLArticulation->getArticulationData(); Dy::ArticulationLink* links = data.getLinks(); Dy::ArticulationJointCoreData* jointData = data.getJointData(); Dy::ArticulationLink& link = links[linkID]; Dy::ArticulationJointCore* joint = link.inboundJoint; Dy::ArticulationJointCoreData& jointDatum = jointData[linkID]; PxReal* jointVelocites = data.getJointVelocities(); PxReal* jointPositions = data.getJointPositions(); PxReal* jVelocities = &jointVelocites[jointDatum.jointOffset]; PxReal* jPositions = &jointPositions[jointDatum.jointOffset]; for(PxU8 i = 0; i < jointDatum.dof; ++i) { const PxU32 dofId = joint->dofIds[i]; joint->jointPos[dofId] = jPositions[i]; joint->jointVel[dofId] = jVelocities[i]; } } void Sc::ArticulationSim::updateCCDLinks(PxArray<BodySim*>& sims) { for (PxU32 a = 0; a < mBodies.size(); ++a) { if (mBodies[a]->getLowLevelBody().getCore().mFlags & PxRigidBodyFlag::eENABLE_CCD) { sims.pushBack(mBodies[a]); } } } void Sc::ArticulationSim::putToSleep() { for (PxU32 i = 0; i < mLinks.size(); i++) { BodySim* bodySim = mBodies[i]; PxsRigidBody& rigid = bodySim->getLowLevelBody(); PxsBodyCore& bodyCore = bodySim->getBodyCore().getCore(); //rigid.setPose(rigid.getLastCCDTransform()); //KS - the IG deactivates bodies in parallel with the solver. It appears that under certain circumstances, the solver's integration (which performs //sleep checks) could decide that the body is no longer a candidate for sleeping on the same frame that the island gen decides to deactivate the island //that the body is contained in. This is a rare occurrence but the behavior we want to emulate is that of IG running before solver so we should therefore //permit the IG to make the authoritative decision over whether the body should be active or inactive. bodyCore.wakeCounter = 0.0f; bodyCore.linearVelocity = PxVec3(0.0f); bodyCore.angularVelocity = PxVec3(0.0f); rigid.clearAllFrameFlags(); //Force update } mScene.getSimulationController()->updateArticulation(mLLArticulation, mIslandNodeIndex); } void Sc::ArticulationSim::sleepCheck(PxReal dt) { if(!mBodies.size()) return; #if PX_CHECKED { PxReal maxTimer = 0.0f, minTimer = PX_MAX_F32; bool allActive = true, noneActive = true; PX_UNUSED(allActive); PX_UNUSED(noneActive); for(PxU32 i=0;i<mLinks.size();i++) { PxReal timer = mBodies[i]->getBodyCore().getWakeCounter(); maxTimer = PxMax(maxTimer, timer); minTimer = PxMin(minTimer, timer); bool active = mBodies[i]->isActive(); allActive &= active; noneActive &= !active; } // either all links are asleep, or no links are asleep PX_ASSERT(maxTimer==0 || minTimer!=0); PX_ASSERT(allActive || noneActive); } #endif if(!mBodies[0]->isActive()) return; const PxReal sleepThreshold = getCore().getCore().sleepThreshold; PxReal maxTimer = 0.0f , minTimer = PX_MAX_F32; for(PxU32 i=0;i<mLinks.size();i++) { const Cm::SpatialVector& motionVelocity = mLLArticulation->getMotionVelocity(i); PxReal timer = mBodies[i]->updateWakeCounter(dt, sleepThreshold, motionVelocity); maxTimer = PxMax(maxTimer, timer); minTimer = PxMin(minTimer, timer); } mCore.setWakeCounterInternal(maxTimer); if(maxTimer != 0.0f) { if(minTimer == 0.0f) { // make sure nothing goes to sleep unless everything does for(PxU32 i=0;i<mLinks.size();i++) mBodies[i]->getBodyCore().setWakeCounterFromSim(PxMax(1e-6f, mBodies[i]->getBodyCore().getWakeCounter())); } return; } for(PxU32 i=0;i<mLinks.size();i++) { mBodies[i]->notifyReadyForSleeping(); mBodies[i]->getLowLevelBody().resetSleepFilter(); } mScene.getSimpleIslandManager()->deactivateNode(mIslandNodeIndex); } bool Sc::ArticulationSim::isSleeping() const { return (mBodies.size() > 0) ? (!mBodies[0]->isActive()) : true; } void Sc::ArticulationSim::internalWakeUp(PxReal wakeCounter) { if(mCore.getWakeCounter() < wakeCounter) { mCore.setWakeCounterInternal(wakeCounter); for(PxU32 i=0;i<mBodies.size();i++) mBodies[i]->internalWakeUpArticulationLink(wakeCounter); } } void Sc::ArticulationSim::updateForces(PxReal dt) { PxU32 count = 0; bool anyForcesApplied = false; for(PxU32 i=0;i<mBodies.size();i++) { if (i+1 < mBodies.size()) { PxPrefetchLine(mBodies[i+1],128); PxPrefetchLine(mBodies[i+1],256); } anyForcesApplied |= mBodies[i]->updateForces(dt, NULL, NULL, count, &mLLArticulation->getSolverDesc().acceleration[i]); } if(anyForcesApplied) mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_EXT_ACCEL); } void Sc::ArticulationSim::clearAcceleration(PxReal dt) { PxU32 count = 0; bool anyBodyRetains = false; for (PxU32 i = 0; i < mBodies.size(); i++) { if (i + 1 < mBodies.size()) { PxPrefetchLine(mBodies[i + 1], 128); PxPrefetchLine(mBodies[i + 1], 256); } const bool accDirty = mBodies[i]->readVelocityModFlag(VMF_ACC_DIRTY); // the code restores the pre-impulse state: // if we only applied an impulse and no acceleration, we clear the acceleration here. // if we applied an acceleration, we re-apply the acceleration terms we have in the velMod. // we cleared out the impulse here when we pushed the data at the start of the sim. if (!accDirty) { mLLArticulation->getSolverDesc().acceleration[i].linear = PxVec3(0.f); mLLArticulation->getSolverDesc().acceleration[i].angular = PxVec3(0.f); } else { mBodies[i]->updateForces(dt, NULL, NULL, count, &mLLArticulation->getSolverDesc().acceleration[i]); } // we need to raise the dirty flag if retain accelerations is on // because in that case we need to restore the acceleration without impulses. We // can only do that using the CPU->GPU codepath because we don't distinguish between // acceleration and impulses on the GPU. // The flag must be raised here because we don't know at the start of the next sim step // that the data in velMod is actually valid and the articulation would not be added // to the dirty list. // without retain accelerations, the accelerations are cleared directly on the GPU. if (mBodies[i]->getFlagsFast() & PxRigidBodyFlag::eRETAIN_ACCELERATIONS) anyBodyRetains = true; } if (anyBodyRetains) { mScene.getSimulationController()->updateArticulationExtAccel(mLLArticulation, mIslandNodeIndex); } } void Sc::ArticulationSim::saveLastCCDTransform() { for(PxU32 i=0;i<mBodies.size();i++) { if (i+1 < mBodies.size()) { PxPrefetchLine(mBodies[i+1],128); PxPrefetchLine(mBodies[i+1],256); } mBodies[i]->getLowLevelBody().saveLastCCDTransform(); } } void Sc::ArticulationSim::setFixedBaseLink(bool value) { const PxU32 linkCount = mLinks.size(); if(linkCount > 0) mLinks[0].bodyCore->fixedBaseLink = PxU8(value); } PxU32 Sc::ArticulationSim::getDofs() const { return mLLArticulation->getDofs(); } PxU32 Sc::ArticulationSim::getDof(const PxU32 linkID) const { return mLLArticulation->getDof(linkID); } PX_COMPILE_TIME_ASSERT(sizeof(Cm::SpatialVector)==sizeof(PxSpatialForce)); PxArticulationCache* Sc::ArticulationSim::createCache() { return FeatherstoneArticulation::createCache(getDofs(), mLinks.size(), mSensors.size()); } PxU32 Sc::ArticulationSim::getCacheDataSize() const { return FeatherstoneArticulation::getCacheDataSize(getDofs(), mLinks.size(), mSensors.size()); } void Sc::ArticulationSim::zeroCache(PxArticulationCache& cache) const { const PxU32 cacheDataSize = getCacheDataSize(); PxMemZero(cache.externalForces, cacheDataSize); } //copy external data to internal data bool Sc::ArticulationSim::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag) const { //checkResize(); bool shouldWake = false; if (mLLArticulation->applyCache(cache, flag, shouldWake)) { mScene.getSimulationController()->updateArticulation(mLLArticulation, mIslandNodeIndex); } return shouldWake; } //copy internal data to external data void Sc::ArticulationSim::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const { mLLArticulation->copyInternalStateToCache(cache, flag, isGpuSimEnabled); } void Sc::ArticulationSim::packJointData(const PxReal* maximum, PxReal* reduced) const { mLLArticulation->packJointData(maximum, reduced); } void Sc::ArticulationSim::unpackJointData(const PxReal* reduced, PxReal* maximum) const { mLLArticulation->unpackJointData(reduced, maximum); } void Sc::ArticulationSim::commonInit() { mLLArticulation->initializeCommonData(); } void Sc::ArticulationSim::computeGeneralizedGravityForce(PxArticulationCache& cache) { mLLArticulation->getGeneralizedGravityForce(mScene.getGravity(), cache); } void Sc::ArticulationSim::computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) { mLLArticulation->getCoriolisAndCentrifugalForce(cache); } void Sc::ArticulationSim::computeGeneralizedExternalForce(PxArticulationCache& cache) { mLLArticulation->getGeneralizedExternalForce(cache); } void Sc::ArticulationSim::computeJointAcceleration(PxArticulationCache& cache) { mLLArticulation->getJointAcceleration(mScene.getGravity(), cache); } void Sc::ArticulationSim::computeJointForce(PxArticulationCache& cache) { mLLArticulation->getJointForce(cache); } void Sc::ArticulationSim::computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) { mLLArticulation->getDenseJacobian(cache, nRows, nCols); } void Sc::ArticulationSim::computeCoefficientMatrix(PxArticulationCache& cache) { mLLArticulation->getCoefficientMatrixWithLoopJoints(mLoopConstraints.begin(), mLoopConstraints.size(), cache); } bool Sc::ArticulationSim::computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter) { const PxReal invLengthScale = 1.f / mScene.getLengthScale(); return mLLArticulation->getLambda(mLoopConstraints.begin(), mLoopConstraints.size(), cache, initialState, jointTorque, gravity, maxIter, invLengthScale); } void Sc::ArticulationSim::computeGeneralizedMassMatrix(PxArticulationCache& cache) { mLLArticulation->getGeneralizedMassMatrixCRB(cache); /*const PxU32 totalDofs = mLLArticulation->getDofs(); PxReal* massMatrix = reinterpret_cast<PxReal*>(PX_ALLOC(sizeof(PxReal) * totalDofs * totalDofs, "MassMatrix")); PxMemCopy(massMatrix, cache.massMatrix, sizeof(PxReal)*totalDofs * totalDofs); mLLArticulation->getGeneralizedMassMatrix(cache); PxReal* massMatrix1 = cache.massMatrix; for (PxU32 i = 0; i < totalDofs; ++i) { PxReal* row = &massMatrix1[i * totalDofs]; for (PxU32 j = 0; j < totalDofs; ++j) { const PxReal dif = row[j] - massMatrix[j*totalDofs + i]; PX_ASSERT (PxAbs(dif) < 2e-4f) } } PX_FREE(massMatrix);*/ } PxU32 Sc::ArticulationSim::getCoefficientMatrixSize() const { const PxU32 size = mLoopConstraints.size(); const PxU32 totalDofs = mLLArticulation->getDofs(); return size * totalDofs; } void Sc::ArticulationSim::setRootLinearVelocity(const PxVec3& velocity) { mLLArticulation->setRootLinearVelocity(velocity); } void Sc::ArticulationSim::setRootAngularVelocity(const PxVec3& velocity) { mLLArticulation->setRootAngularVelocity(velocity); } PxSpatialVelocity Sc::ArticulationSim::getLinkVelocity(const PxU32 linkId) const { Cm::SpatialVector vel = mLLArticulation->getLinkScalarVelocity(linkId); return reinterpret_cast<PxSpatialVelocity&>(vel); } PxSpatialVelocity Sc::ArticulationSim::getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const { Cm::SpatialVector accel = mLLArticulation->getMotionAcceleration(linkId, isGpuSimEnabled); return reinterpret_cast<PxSpatialVelocity&>(accel); } // This method allows user teleport the root links and the articulation //system update all other links pose void Sc::ArticulationSim::setGlobalPose() { mLLArticulation->teleportRootLink(); } void Sc::ArticulationSim::setJointDirty(Dy::ArticulationJointCore& jointCore) { PX_UNUSED(jointCore); mScene.getSimulationController()->updateArticulationJoint(mLLArticulation, mIslandNodeIndex); } void Sc::ArticulationSim::setArticulationDirty(PxU32 flag) { Dy::FeatherstoneArticulation* featherstoneArtic = static_cast<Dy::FeatherstoneArticulation*>(mLLArticulation); featherstoneArtic->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::Enum(flag)); mScene.getSimulationController()->updateArticulation(mLLArticulation, mIslandNodeIndex); } void Sc::ArticulationSim::debugCheckWakeCounterOfLinks(PxReal wakeCounter) const { PX_UNUSED(wakeCounter); #ifdef _DEBUG // make sure the links are in sync with the articulation for(PxU32 i=0; i < mBodies.size(); i++) { PX_ASSERT(mBodies[i]->getBodyCore().getWakeCounter() == wakeCounter); } #endif } void Sc::ArticulationSim::debugCheckSleepStateOfLinks(bool isSleeping) const { PX_UNUSED(isSleeping); #ifdef _DEBUG // make sure the links are in sync with the articulation for(PxU32 i=0; i < mBodies.size(); i++) { if (isSleeping) { PX_ASSERT(!mBodies[i]->isActive()); PX_ASSERT(mBodies[i]->getBodyCore().getWakeCounter() == 0.0f); PX_ASSERT(mBodies[i]->checkSleepReadinessBesidesWakeCounter()); } else PX_ASSERT(mBodies[i]->isActive()); } #endif } PxU32 Sc::ArticulationSim::getRootActorIndex() const { return mBodies[0]->getActorID(); } const PxSpatialForce& Sc::ArticulationSim::getSensorForce(const PxU32 lowLevelIndex) const { return mSensorForces[lowLevelIndex]; }
24,950
C++
29.465201
157
0.74994
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationTendonJointCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScArticulationTendonJointCore.h" #include "ScArticulationTendonSim.h" using namespace physx; void Sc::ArticulationTendonJointCore::setCoefficient(PxArticulationAxis::Enum axis_, const PxReal coefficient_, const PxReal recipCoefficient_) { axis = axis_; coefficient = coefficient_; recipCoefficient = recipCoefficient_; if (mTendonSim) { mTendonSim->setTendonJointCoefficient(*this, axis_, coefficient, recipCoefficient); } }
2,144
C++
46.666666
143
0.771455
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorPair.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_ACTOR_PAIR_H #define SC_ACTOR_PAIR_H #include "ScRigidSim.h" #include "ScContactStream.h" #include "ScNPhaseCore.h" #if PX_SUPPORT_GPU_PHYSX #include "ScSoftBodySim.h" #endif namespace physx { namespace Sc { class ActorPairContactReportData { public: ActorPairContactReportData() : mStrmResetStamp (0xffffffff), mActorAID (0xffffffff), mActorBID (0xffffffff), mPxActorA (NULL), mPxActorB (NULL) {} ContactStreamManager mContactStreamManager; PxU32 mStrmResetStamp; PxU32 mActorAID; PxU32 mActorBID; PxActor* mPxActorA; PxActor* mPxActorB; }; /** \brief Class shared by all shape interactions for a pair of actors. This base class is used if no shape pair of an actor pair has contact reports requested. */ class ActorPair { public: enum ActorPairFlags { eIS_REPORT_PAIR = (1<<0), eNEXT_FREE = (1<<1) }; PX_FORCE_INLINE ActorPair() : mInternalFlags(0), mTouchCount(0), mRefCount(0) {} PX_FORCE_INLINE ~ActorPair() {} PX_FORCE_INLINE PxIntBool isReportPair() const { return (mInternalFlags & eIS_REPORT_PAIR); } PX_FORCE_INLINE void incTouchCount() { mTouchCount++; PX_ASSERT(mTouchCount); } PX_FORCE_INLINE void decTouchCount() { PX_ASSERT(mTouchCount); mTouchCount--; } PX_FORCE_INLINE PxU32 getTouchCount() const { return mTouchCount; } PX_FORCE_INLINE void incRefCount() { ++mRefCount; PX_ASSERT(mRefCount>0); } PX_FORCE_INLINE PxU32 decRefCount() { PX_ASSERT(mRefCount>0); return --mRefCount; } PX_FORCE_INLINE PxU32 getRefCount() const { return mRefCount; } private: ActorPair& operator=(const ActorPair&); protected: PxU16 mInternalFlags; PxU16 mTouchCount; PxU16 mRefCount; PxU16 mPad; // instances of this class are stored in a pool which needs an item size of at least size_t }; /** \brief Class shared by all shape interactions for a pair of actors if contact reports are requested. This class is used if at least one shape pair of an actor pair has contact reports requested. \note If a pair of actors had contact reports requested for some of the shape interactions but all of them switch to not wanting contact reports any longer, then the ActorPairReport instance is kept being used and won't get replaced by a simpler ActorPair instance. */ class ActorPairReport : public ActorPair { public: enum ActorPairReportFlags { eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET = ActorPair::eNEXT_FREE // PT: whether the pair is already stored in the 'ContactReportActorPairSet' or not }; PX_FORCE_INLINE ActorPairReport(ActorSim&, ActorSim&); PX_FORCE_INLINE ~ActorPairReport(); PX_INLINE ContactStreamManager& createContactStreamManager(NPhaseCore&); PX_FORCE_INLINE ContactStreamManager& getContactStreamManager() const { PX_ASSERT(mReportData); return mReportData->mContactStreamManager; } PX_FORCE_INLINE ActorSim& getActorA() const { return mActorA; } PX_FORCE_INLINE ActorSim& getActorB() const { return mActorB; } PX_INLINE PxU32 getActorAID() const { PX_ASSERT(mReportData); return mReportData->mActorAID; } PX_INLINE PxU32 getActorBID() const { PX_ASSERT(mReportData); return mReportData->mActorBID; } PX_INLINE PxActor* getPxActorA() const { PX_ASSERT(mReportData); return mReportData->mPxActorA; } PX_INLINE PxActor* getPxActorB() const { PX_ASSERT(mReportData); return mReportData->mPxActorB; } PX_INLINE bool streamResetStamp(PxU32 cmpStamp); PX_FORCE_INLINE PxU16 isInContactReportActorPairSet() const { return PxU16(mInternalFlags & eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET); } PX_FORCE_INLINE void setInContactReportActorPairSet() { mInternalFlags |= eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET; } PX_FORCE_INLINE void clearInContactReportActorPairSet() { mInternalFlags &= ~eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET; } PX_FORCE_INLINE void createContactReportData(NPhaseCore&); PX_FORCE_INLINE void releaseContactReportData(NPhaseCore&); PX_FORCE_INLINE void convert(ActorPair& aPair) { PX_ASSERT(!aPair.isReportPair()); mTouchCount = PxU16(aPair.getTouchCount()); mRefCount = PxU16(aPair.getRefCount()); } PX_FORCE_INLINE static ActorPairReport& cast(ActorPair& aPair) { PX_ASSERT(aPair.isReportPair()); return static_cast<ActorPairReport&>(aPair); } private: ActorPairReport& operator=(const ActorPairReport&); ActorSim& mActorA; ActorSim& mActorB; ActorPairContactReportData* mReportData; }; } // namespace Sc PX_FORCE_INLINE Sc::ActorPairReport::ActorPairReport(ActorSim& actor0, ActorSim& actor1) : ActorPair(), mActorA (actor0), mActorB (actor1), mReportData (NULL) { PX_ASSERT(mInternalFlags == 0); mInternalFlags = ActorPair::eIS_REPORT_PAIR; } PX_FORCE_INLINE Sc::ActorPairReport::~ActorPairReport() { PX_ASSERT(mReportData == NULL); } PX_INLINE bool Sc::ActorPairReport::streamResetStamp(PxU32 cmpStamp) { PX_ASSERT(mReportData); const bool ret = (cmpStamp != mReportData->mStrmResetStamp); mReportData->mStrmResetStamp = cmpStamp; return ret; } PX_INLINE Sc::ContactStreamManager& Sc::ActorPairReport::createContactStreamManager(NPhaseCore& npCore) { // Lazy create report data if(!mReportData) createContactReportData(npCore); return mReportData->mContactStreamManager; } PX_FORCE_INLINE void Sc::ActorPairReport::createContactReportData(NPhaseCore& npCore) { PX_ASSERT(!mReportData); Sc::ActorPairContactReportData* reportData = npCore.createActorPairContactReportData(); mReportData = reportData; if(reportData) { const ActorCore& actorCoreA = mActorA.getActorCore(); const ActorCore& actorCoreB = mActorB.getActorCore(); reportData->mActorAID = mActorA.getActorID(); reportData->mActorBID = mActorB.getActorID(); #if PX_SUPPORT_GPU_PHYSX if (mActorA.getActorType() == PxActorType::eSOFTBODY) reportData->mPxActorA = static_cast<const SoftBodyCore&>(actorCoreA).getPxActor(); else #endif reportData->mPxActorA = static_cast<const RigidCore&>(actorCoreA).getPxActor(); #if PX_SUPPORT_GPU_PHYSX if (mActorA.getActorType() == PxActorType::eSOFTBODY) reportData->mPxActorB = static_cast<const SoftBodyCore&>(actorCoreB).getPxActor(); else #endif reportData->mPxActorB = static_cast<const RigidCore&>(actorCoreB).getPxActor(); } } PX_FORCE_INLINE void Sc::ActorPairReport::releaseContactReportData(NPhaseCore& npCore) { // Can't take the NPhaseCore (scene) reference from the actors since they're already gone on scene release if(mReportData) { npCore.releaseActorPairContactReportData(mReportData); mReportData = NULL; } } } #endif
8,326
C
35.52193
172
0.744896
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBodySim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScBodySim.h" #include "ScShapeSim.h" #include "ScScene.h" #include "ScArticulationSim.h" #include "PxsContext.h" #include "PxsSimpleIslandManager.h" #include "PxsSimulationController.h" #include "ScSimStateData.h" using namespace physx; using namespace physx::Dy; using namespace Sc; #define PX_FREEZE_INTERVAL 1.5f #define PX_FREE_EXIT_THRESHOLD 4.f #define PX_FREEZE_TOLERANCE 0.25f #define PX_SLEEP_DAMPING 0.5f #define PX_FREEZE_SCALE 0.9f static void updateBPGroup(ActorSim* sim) { PxU32 nbElems = sim->getNbElements(); ElementSim** elems = sim->getElements(); while (nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); current->updateBPGroup(); } } BodySim::BodySim(Scene& scene, BodyCore& core, bool compound) : RigidSim (scene, core), mLLBody (&core.getCore(), PX_FREEZE_INTERVAL), mSimStateData (NULL), mVelModState (VMF_GRAVITY_DIRTY), mArticulation (NULL) { core.getCore().numCountedInteractions = 0; core.getCore().disableGravity = core.getActorFlags() & PxActorFlag::eDISABLE_GRAVITY; if(core.getFlags() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) mLLBody.mInternalFlags |= PxsRigidBody::eSPECULATIVE_CCD; if(core.getFlags() & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES) mLLBody.mInternalFlags |= PxsRigidBody::eENABLE_GYROSCOPIC; if(core.getFlags() & PxRigidBodyFlag::eRETAIN_ACCELERATIONS) mLLBody.mInternalFlags |= PxsRigidBody::eRETAIN_ACCELERATION; // PT: don't read the core ptr we just wrote, use input param // PT: at time of writing we get a big L2 here because even though bodycore has been prefetched, the wake counter is 160 bytes away const bool isAwake = (core.getWakeCounter() > 0) || (!core.getLinearVelocity().isZero()) || (!core.getAngularVelocity().isZero()); const bool isKine = isKinematic(); IG::SimpleIslandManager* simpleIslandManager = scene.getSimpleIslandManager(); if(!isArticulationLink()) { mNodeIndex = simpleIslandManager->addRigidBody(&mLLBody, isKine, isAwake); } else { if(mArticulation) { const PxU32 linkIndex = mArticulation->findBodyIndex(*this); const PxNodeIndex index = mArticulation->getIslandNodeIndex(); mNodeIndex.setIndices(index.index(), linkIndex); } } PX_ASSERT(mActiveListIndex == SC_NOT_IN_SCENE_INDEX); // A.B. need to set the compound rigid flag early enough, so that we add the rigid into // active list and do not create the shape bounds if(compound) raiseInternalFlag(BF_IS_COMPOUND_RIGID); setActive(isAwake, true); if(isAwake) { scene.addToActiveList(*this); PX_ASSERT(isActive()); } else { mActiveListIndex = SC_NOT_IN_ACTIVE_LIST_INDEX; mActiveCompoundListIndex = SC_NOT_IN_ACTIVE_LIST_INDEX; PX_ASSERT(!isActive()); simpleIslandManager->deactivateNode(mNodeIndex); } if(isKine) { initKinematicStateBase(core, true); setupSimStateData(true); notifyPutToSleep(); // sleep state of kinematics is fully controlled by the simulation controller not the island manager mFilterFlags |= PxFilterObjectFlag::eKINEMATIC; } } BodySim::~BodySim() { Scene& scene = mScene; const bool active = isActive(); tearDownSimStateData(isKinematic()); PX_ASSERT(!mSimStateData); // PX-4603. AD: assuming that the articulation code cleans up the dirty state in case this is an articulation link. if (!isArticulationLink()) scene.getVelocityModifyMap().boundedReset(mNodeIndex.index()); PX_ASSERT(!readInternalFlag(BF_ON_DEATHROW)); // Before 3.0 it could happen that destroy could get called twice. Assert to make sure this is fixed. raiseInternalFlag(BF_ON_DEATHROW); scene.removeBody(*this); //Articulations are represented by a single node, so they must only be removed by the articulation and not the links! if(mArticulation == NULL && mNodeIndex.articulationLinkId() == 0) //If it wasn't an articulation link, then we can remove it scene.getSimpleIslandManager()->removeNode(mNodeIndex); PX_ASSERT(mActiveListIndex != SC_NOT_IN_SCENE_INDEX); if (active) scene.removeFromActiveList(*this); mActiveListIndex = SC_NOT_IN_SCENE_INDEX; mActiveCompoundListIndex = SC_NOT_IN_SCENE_INDEX; mCore.setSim(NULL); } void BodySim::updateCached(PxBitMapPinned* shapeChangedMap) { if(!(mLLBody.mInternalFlags & PxsRigidBody::eFROZEN)) { PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); current->updateCached(0, shapeChangedMap); } } } void BodySim::updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray) { PX_ASSERT(!(mLLBody.mInternalFlags & PxsRigidBody::eFROZEN)); // PT: should not be called otherwise PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); current->updateCached(transformCache, boundsArray); } } bool BodySim::setupSimStateData(bool isKinematic) { SimStateData* data = mSimStateData; if(!data) { data = mScene.getSimStateDataPool()->construct(); if(!data) return false; } if(isKinematic) { PX_ASSERT(!mSimStateData || !mSimStateData->isKine()); PX_PLACEMENT_NEW(data, SimStateData(SimStateData::eKine)); Kinematic* kine = data->getKinematicData(); kine->targetValid = 0; simStateBackupAndClearBodyProperties(data, getBodyCore().getCore()); } else { PX_ASSERT(!mSimStateData || !mSimStateData->isVelMod()); PX_PLACEMENT_NEW(data, SimStateData(SimStateData::eVelMod)); VelocityMod* velmod = data->getVelocityModData(); velmod->clear(); } mSimStateData = data; return true; } void BodySim::tearDownSimStateData(bool isKinematic) { PX_ASSERT(!mSimStateData || mSimStateData->isKine() == isKinematic); if (mSimStateData) { if (isKinematic) simStateRestoreBodyProperties(mSimStateData, getBodyCore().getCore()); mScene.getSimStateDataPool()->destroy(mSimStateData); mSimStateData = NULL; } } void BodySim::switchToKinematic() { setupSimStateData(true); { initKinematicStateBase(getBodyCore(), false); // - interactions need to get refiltered to make sure that kinematic-kinematic and kinematic-static pairs get suppressed // - unlike postSwitchToDynamic(), constraint interactions are not marked dirty here because a transition to kinematic will put the object asleep which in turn // triggers onDeactivate() on the constraint pairs that are active. If such pairs get deactivated, they will get removed from the list of active breakable // constraints automatically. setActorsInteractionsDirty(InteractionDirtyFlag::eBODY_KINEMATIC, NULL, InteractionFlag::eFILTERABLE); mScene.getSimpleIslandManager()->setKinematic(mNodeIndex); updateBPGroup(this); } mScene.setDynamicsDirty(); mFilterFlags |= PxFilterObjectFlag::eKINEMATIC; } void BodySim::switchToDynamic() { tearDownSimStateData(true); { mScene.getSimpleIslandManager()->setDynamic(mNodeIndex); setForcesToDefaults(true); // - interactions need to get refiltered to make sure that former kinematic-kinematic and kinematic-static pairs get enabled // - switching from kinematic to dynamic does not change the sleep state of the body. The constraint interactions are marked dirty // to check later whether they need to be activated plus potentially tracked for constraint break testing. This special treatment // is necessary because constraints between two kinematic bodies are considered inactive, no matter whether one of the kinematics // is active (has a target) or not. setActorsInteractionsDirty(InteractionDirtyFlag::eBODY_KINEMATIC, NULL, InteractionFlag::eFILTERABLE | InteractionFlag::eCONSTRAINT); clearInternalFlag(BF_KINEMATIC_MOVE_FLAGS); if(isActive()) mScene.swapInActiveBodyList(*this); // updateBPGroup(this); } mScene.setDynamicsDirty(); mFilterFlags &= ~PxFilterObjectFlag::eKINEMATIC; } void BodySim::setKinematicTarget(const PxTransform& p) { PX_ASSERT(getSimStateData(true)); PX_ASSERT(getSimStateData(true)->isKine()); simStateSetKinematicTarget(getSimStateData_Unchecked(), p); PX_ASSERT(getSimStateData(true)->getKinematicData()->targetValid); raiseInternalFlag(BF_KINEMATIC_MOVED); // Important to set this here already because trigger interactions need to have this information when being activated. clearInternalFlag(BF_KINEMATIC_SURFACE_VELOCITY); } void BodySim::addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { notifyAddSpatialAcceleration(); if (!mSimStateData || !mSimStateData->isVelMod()) setupSimStateData(false); VelocityMod* velmod = mSimStateData->getVelocityModData(); if (linAcc) velmod->accumulateLinearVelModPerSec(*linAcc); if (angAcc) velmod->accumulateAngularVelModPerSec(*angAcc); } void BodySim::setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { notifyAddSpatialAcceleration(); if (!mSimStateData || !mSimStateData->isVelMod()) setupSimStateData(false); VelocityMod* velmod = mSimStateData->getVelocityModData(); if (linAcc) velmod->setLinearVelModPerSec(*linAcc); if (angAcc) velmod->setAngularVelModPerSec(*angAcc); } void BodySim::clearSpatialAcceleration(bool force, bool torque) { PX_ASSERT(force || torque); notifyClearSpatialAcceleration(); if (mSimStateData) { PX_ASSERT(mSimStateData->isVelMod()); VelocityMod* velmod = mSimStateData->getVelocityModData(); if (force) velmod->clearLinearVelModPerSec(); if (torque) velmod->clearAngularVelModPerSec(); } } void BodySim::addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta) { notifyAddSpatialVelocity(); if (!mSimStateData || !mSimStateData->isVelMod()) setupSimStateData(false); VelocityMod* velmod = mSimStateData->getVelocityModData(); if (linVelDelta) velmod->accumulateLinearVelModPerStep(*linVelDelta); if (angVelDelta) velmod->accumulateAngularVelModPerStep(*angVelDelta); } void BodySim::clearSpatialVelocity(bool force, bool torque) { PX_ASSERT(force || torque); notifyClearSpatialVelocity(); if (mSimStateData) { PX_ASSERT(mSimStateData->isVelMod()); VelocityMod* velmod = mSimStateData->getVelocityModData(); if (force) velmod->clearLinearVelModPerStep(); if (torque) velmod->clearAngularVelModPerStep(); } } void BodySim::raiseVelocityModFlagAndNotify(VelocityModFlags flag) { //The dirty flag is stored separately in the BodySim so that we query the dirty flag before going to //the expense of querying the simStateData for the velmod values. raiseVelocityModFlag(flag); if (!isArticulationLink()) mScene.getVelocityModifyMap().growAndSet(getNodeIndex().index()); else mScene.addDirtyArticulationSim(getArticulation()); } void BodySim::postActorFlagChange(PxU32 oldFlags, PxU32 newFlags) { // PT: don't convert to bool if not needed const PxU32 wasWeightless = oldFlags & PxActorFlag::eDISABLE_GRAVITY; const PxU32 isWeightless = newFlags & PxActorFlag::eDISABLE_GRAVITY; if (isWeightless != wasWeightless) { if (mVelModState == 0) raiseVelocityModFlag(VMF_GRAVITY_DIRTY); getBodyCore().getCore().disableGravity = isWeightless!=0; } } void BodySim::postBody2WorldChange() { mLLBody.saveLastCCDTransform(); notifyShapesOfTransformChange(); } void BodySim::postSetWakeCounter(PxReal t, bool forceWakeUp) { if ((t > 0.0f) || forceWakeUp) notifyNotReadyForSleeping(); else { const bool readyForSleep = checkSleepReadinessBesidesWakeCounter(); if (readyForSleep) notifyReadyForSleeping(); } } void BodySim::postPosePreviewChange(PxU32 posePreviewFlag) { if (isActive()) { if (posePreviewFlag & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) mScene.addToPosePreviewList(*this); else mScene.removeFromPosePreviewList(*this); } else PX_ASSERT(!mScene.isInPosePreviewList(*this)); } void BodySim::activate() { BodyCore& core = getBodyCore(); // Activate body { PX_ASSERT((!isKinematic()) || notInScene() || readInternalFlag(InternalFlags(BF_KINEMATIC_MOVED | BF_KINEMATIC_SURFACE_VELOCITY))); // kinematics should only get activated when a target is set. // exception: object gets newly added, then the state change will happen later if(!isArticulationLink()) { mLLBody.mInternalFlags &= (~PxsRigidBody::eFROZEN); // Put in list of activated bodies. The list gets cleared at the end of a sim step after the sleep callbacks have been fired. mScene.onBodyWakeUp(this); } if(core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) { PX_ASSERT(!mScene.isInPosePreviewList(*this)); mScene.addToPosePreviewList(*this); } createSqBounds(); } activateInteractions(*this); //set speculative CCD bit map if speculative CCD flag is on if(core.getFlags() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) addToSpeculativeCCDMap(); } void BodySim::deactivate() { deactivateInteractions(*this); BodyCore& core = getBodyCore(); // Deactivate body { PX_ASSERT((!isKinematic()) || notInScene() || !readInternalFlag(BF_KINEMATIC_MOVED)); // kinematics should only get deactivated when no target is set. // exception: object gets newly added, then the state change will happen later if(!readInternalFlag(BF_ON_DEATHROW)) { // Set velocity to 0. // Note: this is also fine if the method gets called because the user puts something to sleep (this behavior is documented in the API) PX_ASSERT(core.getWakeCounter() == 0.0f); const PxVec3 zero(0.0f); core.setLinearVelocityInternal(zero); core.setAngularVelocityInternal(zero); setForcesToDefaults(!core.getCore().disableGravity); } if(!isArticulationLink()) // Articulations have their own sleep logic. mScene.onBodySleep(this); if(core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) { PX_ASSERT(mScene.isInPosePreviewList(*this)); mScene.removeFromPosePreviewList(*this); } destroySqBounds(); } // reset speculative CCD bit map if speculative CCD flag is on if(core.getFlags() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) removeFromSpeculativeCCDMap(); } void BodySim::wakeUp() { setActive(true); notifyWakeUp(); } void BodySim::putToSleep() { PX_ASSERT(getBodyCore().getWakeCounter() == 0.0f); PX_ASSERT(getBodyCore().getLinearVelocity().isZero()); PX_ASSERT(getBodyCore().getAngularVelocity().isZero()); notifyClearSpatialAcceleration(); notifyClearSpatialVelocity(); simStateClearVelMod(getSimStateData_Unchecked()); setActive(false); notifyPutToSleep(); } void BodySim::internalWakeUp(PxReal wakeCounterValue) { if(mArticulation) mArticulation->internalWakeUp(wakeCounterValue); else internalWakeUpBase(wakeCounterValue); } void BodySim::internalWakeUpArticulationLink(PxReal wakeCounterValue) { PX_ASSERT(mArticulation); internalWakeUpBase(wakeCounterValue); } void BodySim::internalWakeUpBase(PxReal wakeCounterValue) //this one can only increase the wake counter, not decrease it, so it can't be used to put things to sleep! { if ((!isKinematic()) && (getBodyCore().getWakeCounter() < wakeCounterValue)) { PX_ASSERT(wakeCounterValue > 0.0f); getBodyCore().setWakeCounterFromSim(wakeCounterValue); //we need to update the gpu body sim because we reset the wake counter for the body core mScene.updateBodySim(*this); setActive(true); notifyWakeUp(); if(0) // PT: commented-out for PX-2197 mLLBody.mInternalFlags &= (~PxsRigidBody::eFROZEN); } } void BodySim::notifyReadyForSleeping() { if(mArticulation == NULL) mScene.getSimpleIslandManager()->deactivateNode(mNodeIndex); } void BodySim::notifyNotReadyForSleeping() { mScene.getSimpleIslandManager()->activateNode(mNodeIndex); } void BodySim::notifyWakeUp() { mScene.getSimpleIslandManager()->activateNode(mNodeIndex); } void BodySim::notifyPutToSleep() { mScene.getSimpleIslandManager()->putNodeToSleep(mNodeIndex); } //This function will be called by CPU sleepCheck code // PT: TODO: actually this seems to be only called by the articulation sim code, while regular rigid bodies use a copy of that code in LowLevelDynamics? PxReal BodySim::updateWakeCounter(PxReal dt, PxReal energyThreshold, const Cm::SpatialVector& motionVelocity) { // update the body's sleep state and BodyCore& core = getBodyCore(); const PxReal wakeCounterResetTime = ScInternalWakeCounterResetValue; PxReal wc = core.getWakeCounter(); { PxVec3 bcSleepLinVelAcc = mLLBody.sleepLinVelAcc; PxVec3 bcSleepAngVelAcc = mLLBody.sleepAngVelAcc; if(wc < wakeCounterResetTime * 0.5f || wc < dt) { const PxTransform& body2World = getBody2World(); // calculate normalized energy: kinetic energy divided by mass const PxVec3 t = core.getInverseInertia(); const PxVec3 inertia(t.x > 0.0f ? 1.0f/t.x : 1.0f, t.y > 0.0f ? 1.0f/t.y : 1.0f, t.z > 0.0f ? 1.0f/t.z : 1.0f); PxVec3 sleepLinVelAcc = motionVelocity.linear; PxVec3 sleepAngVelAcc = body2World.q.rotateInv(motionVelocity.angular); bcSleepLinVelAcc += sleepLinVelAcc; bcSleepAngVelAcc += sleepAngVelAcc; PxReal invMass = core.getInverseMass(); if(invMass == 0.0f) invMass = 1.0f; const PxReal angular = bcSleepAngVelAcc.multiply(bcSleepAngVelAcc).dot(inertia) * invMass; const PxReal linear = bcSleepLinVelAcc.magnitudeSquared(); const PxReal normalizedEnergy = 0.5f * (angular + linear); // scale threshold by cluster factor (more contacts => higher sleep threshold) const PxReal clusterFactor = PxReal(1 + getNumCountedInteractions()); const PxReal threshold = clusterFactor*energyThreshold; if (normalizedEnergy >= threshold) { PX_ASSERT(isActive()); mLLBody.resetSleepFilter(); const float factor = threshold == 0.0f ? 2.0f : PxMin(normalizedEnergy/threshold, 2.0f); PxReal oldWc = wc; wc = factor * 0.5f * wakeCounterResetTime + dt * (clusterFactor - 1.0f); core.setWakeCounterFromSim(wc); if (oldWc == 0.0f) // for the case where a sleeping body got activated by the system (not the user) AND got processed by the solver as well notifyNotReadyForSleeping(); return wc; } } mLLBody.sleepLinVelAcc = bcSleepLinVelAcc; mLLBody.sleepAngVelAcc = bcSleepAngVelAcc; } wc = PxMax(wc-dt, 0.0f); core.setWakeCounterFromSim(wc); return wc; } PX_FORCE_INLINE void BodySim::initKinematicStateBase(BodyCore&, bool asPartOfCreation) { PX_ASSERT(!readInternalFlag(BF_KINEMATIC_MOVED)); if (!asPartOfCreation && isActive()) mScene.swapInActiveBodyList(*this); //mLLBody.setAccelerationV(Cm::SpatialVector::zero()); // Need to be before setting setRigidBodyFlag::KINEMATIC } bool BodySim::updateForces(PxReal dt, PxsRigidBody** updatedBodySims, PxU32* updatedBodyNodeIndices, PxU32& index, Cm::SpatialVector* acceleration) { PxVec3 linVelDt(0.0f), angVelDt(0.0f); const bool accDirty = readVelocityModFlag(VMF_ACC_DIRTY); const bool velDirty = readVelocityModFlag(VMF_VEL_DIRTY); SimStateData* simStateData = NULL; bool forceChangeApplied = false; //if we change the logic like this, which means we don't need to have two seperate variables in the pxgbodysim to represent linAcc and angAcc. However, this //means angAcc will be always 0 if( (accDirty || velDirty) && ((simStateData = getSimStateData(false)) != NULL) ) { VelocityMod* velmod = simStateData->getVelocityModData(); //we don't have support for articulation yet if (updatedBodySims) { updatedBodySims[index] = &getLowLevelBody(); updatedBodyNodeIndices[index++] = getNodeIndex().index(); } if(velDirty) { linVelDt = velmod->getLinearVelModPerStep(); angVelDt = velmod->getAngularVelModPerStep(); } if (accDirty) { linVelDt += velmod->getLinearVelModPerSec()*dt; angVelDt += velmod->getAngularVelModPerSec()*dt; } if (acceleration) { const PxReal invDt = 1.f / dt; acceleration->linear = linVelDt * invDt; acceleration->angular = angVelDt * invDt; } else { getBodyCore().updateVelocities(linVelDt, angVelDt); } forceChangeApplied = true; } setForcesToDefaults(readVelocityModFlag(VMF_ACC_DIRTY)); return forceChangeApplied; } void BodySim::onConstraintDetach() { PX_ASSERT(readInternalFlag(BF_HAS_CONSTRAINTS)); PxU32 size = getActorInteractionCount(); Interaction** interactions = getActorInteractions(); unregisterCountedInteraction(); while(size--) { const Interaction* interaction = *interactions++; if(interaction->getType() == InteractionType::eCONSTRAINTSHADER) return; } clearInternalFlag(BF_HAS_CONSTRAINTS); // There are no other constraint interactions left } void BodySim::setArticulation(ArticulationSim* a, PxReal wakeCounter, bool asleep, PxU32 bodyIndex) { mArticulation = a; if(a) { PxNodeIndex index = mArticulation->getIslandNodeIndex(); mNodeIndex.setIndices(index.index(), bodyIndex); getBodyCore().setWakeCounterFromSim(wakeCounter); if (getFlagsFast() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) mScene.setSpeculativeCCDArticulationLink(mNodeIndex.index()); //Articulations defer registering their shapes with the nphaseContext until the IG node index is known. { ElementSim** current = getElements(); PxU32 nbElements = getNbElements(); while (nbElements--) { ShapeSim* sim = static_cast<ShapeSim*>(*current++); mScene.getLowLevelContext()->getNphaseImplementationContext()->registerShape(mNodeIndex, sim->getCore().getCore(), sim->getElementID(), sim->getActor().getPxActor()); } } //Force node index into LL shapes setBodyNodeIndex(mNodeIndex); if (a->getCore().getArticulationFlags() & PxArticulationFlag::eDISABLE_SELF_COLLISION) { //We need to reset the group IDs for all shapes in this body... ElementSim** current = getElements(); PxU32 nbElements = getNbElements(); Bp::AABBManagerBase* aabbMgr = mScene.getAABBManager(); Bp::FilterGroup::Enum rootGroup = Bp::getFilterGroup(false, a->getRootActorIndex(), false); while (nbElements--) { ShapeSim* sim = static_cast<ShapeSim*>(*current++); aabbMgr->setBPGroup(sim->getElementID(), rootGroup); } } if (!asleep) { setActive(true); notifyWakeUp(); } else { notifyReadyForSleeping(); notifyPutToSleep(); setActive(false); } } else { //Setting a 1 in the articulation ID to avoid returning the node Index to the node index //manager mNodeIndex.setIndices(PX_INVALID_NODE, 1); } } void BodySim::createSqBounds() { if(!isActive() || usingSqKinematicTarget() || readInternalFlag(BF_IS_COMPOUND_RIGID)) return; PX_ASSERT(!isFrozen()); PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); current->createSqBounds(); } } void BodySim::destroySqBounds() { PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); current->destroySqBounds(); } } void BodySim::freezeTransforms(PxBitMapPinned* shapeChangedMap) { PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); sim->updateCached(PxsTransformFlag::eFROZEN, shapeChangedMap); sim->destroySqBounds(); } } void BodySim::disableCompound() { if(isActive()) mScene.removeFromActiveCompoundBodyList(*this); clearInternalFlag(BF_IS_COMPOUND_RIGID); }
25,049
C++
29.144404
195
0.742545
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScFEMClothSim.h" #include "ScFEMClothCore.h" #include "ScScene.h" #include "ScInteraction.h" // to be deleted #include "PxsSimulationController.h" using namespace physx; using namespace physx::Dy; Sc::FEMClothSim::FEMClothSim(FEMClothCore& core, Scene& scene) : ActorSim(scene, core), mShapeSim(*this) { mLLFEMCloth = scene.createLLFEMCloth(this); mNodeIndex = scene.getSimpleIslandManager()->addFEMCloth(mLLFEMCloth, false); scene.getSimpleIslandManager()->activateNode(mNodeIndex); mLLFEMCloth->setElementId(mShapeSim.getElementID()); } Sc::FEMClothSim::~FEMClothSim() { if (!mLLFEMCloth) return; mScene.destroyLLFEMCloth(*mLLFEMCloth); mScene.getSimpleIslandManager()->removeNode(mNodeIndex); mCore.setSim(NULL); } void Sc::FEMClothSim::updateBounds() { mShapeSim.updateBounds(); } void Sc::FEMClothSim::updateBoundsInAABBMgr() { mShapeSim.updateBoundsInAABBMgr(); } PxBounds3 Sc::FEMClothSim::getBounds() const { return mShapeSim.getBounds(); } bool Sc::FEMClothSim::isSleeping() const { IG::IslandSim& sim = mScene.getSimpleIslandManager()->getAccurateIslandSim(); return sim.getActiveNodeIndex(mNodeIndex) == PX_INVALID_NODE; } void Sc::FEMClothSim::onSetWakeCounter() { getScene().getSimulationController()->setClothWakeCounter(mLLFEMCloth); if (mLLFEMCloth->getCore().wakeCounter > 0.f) getScene().getSimpleIslandManager()->activateNode(mNodeIndex); else getScene().getSimpleIslandManager()->deactivateNode(mNodeIndex); } void Sc::FEMClothSim::attachShapeCore(ShapeCore* core) { mShapeSim.attachShapeCore(core); PxsShapeCore* shapeCore = const_cast<PxsShapeCore*>(&core->getCore()); mLLFEMCloth->setShapeCore(shapeCore); } #endif //PX_SUPPORT_GPU_PHYSX
3,347
C++
30.584905
78
0.766657
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScRigidCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScRigidCore.h" #include "ScStaticCore.h" #include "ScRigidSim.h" #include "ScShapeSim.h" #include "ScScene.h" using namespace physx; using namespace Sc; static ShapeSim& getSimForShape(const ShapeCore& core, const ActorSim& actorSim) { if(core.getExclusiveSim()) { return *core.getExclusiveSim(); } //Must be a shared shape. //Search backwards to emulate the behaviour of the previous linked list. PxU32 nbElems = actorSim.getNbElements(); ElementSim*const* elems = actorSim.getElements() + (nbElems - 1); while (nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems--); if (&sim->getCore() == &core) return *sim; } PX_ASSERT(0); // should never fail return *reinterpret_cast<ShapeSim*>(1); } RigidCore::RigidCore(const PxActorType::Enum type) : ActorCore(type, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0) { } RigidCore::~RigidCore() { } void RigidCore::addShapeToScene(ShapeCore& shapeCore) { RigidSim* sim = getSim(); PX_ASSERT(sim); if(!sim) return; sim->getScene().addShape_(*sim, shapeCore); } void RigidCore::removeShapeFromScene(ShapeCore& shapeCore, bool wakeOnLostTouch) { RigidSim* sim = getSim(); if(!sim) return; ShapeSim& s = getSimForShape(shapeCore, *sim); sim->getScene().removeShape_(s, wakeOnLostTouch); } void RigidCore::unregisterShapeFromNphase(Sc::ShapeCore& shapeCore) { RigidSim* sim = getSim(); if (!sim) return; ShapeSim& s = getSimForShape(shapeCore, *sim); s.getScene().unregisterShapeFromNphase(shapeCore, s.getElementID()); } void RigidCore::registerShapeInNphase(Sc::ShapeCore& shapeCore) { RigidSim* sim = getSim(); if (!sim) return; ShapeSim& s = getSimForShape(shapeCore, *sim); s.getScene().registerShapeInNphase(this, shapeCore, s.getElementID()); } void RigidCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags) { RigidSim* sim = getSim(); if(!sim) return; ShapeSim& s = getSimForShape(shape, *sim); if(notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY) s.onVolumeOrTransformChange(); if(notifyFlags & ShapeChangeNotifyFlag::eMATERIAL) s.onMaterialChange(); if(notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING) s.onResetFiltering(); if(notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY) s.onVolumeOrTransformChange(); if(notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA) s.onFilterDataChange(); if(notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET) s.onContactOffsetChange(); if(notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET) s.onRestOffsetChange(); } void RigidCore::onShapeFlagsChange(ShapeCore& shape, PxShapeFlags oldShapeFlags) { // DS: We pass flags to avoid searching multiple times or exposing RigidSim outside SC. //If we start hitting this a lot we should do it // a different way, but shape modification after insertion is rare. RigidSim* sim = getSim(); if(!sim) return; ShapeSim& s = getSimForShape(shape, *sim); s.onFlagChange(oldShapeFlags); } RigidSim* RigidCore::getSim() const { return static_cast<RigidSim*>(ActorCore::getSim()); } PxU32 RigidCore::getRigidID() const { return static_cast<RigidSim*>(ActorCore::getSim())->getActorID(); }
4,841
C++
31.28
119
0.749019
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemSim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef SC_HAIR_SYSTEM_SIM_H #define SC_HAIR_SYSTEM_SIM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "DyHairSystem.h" #include "ScHairSystemCore.h" #include "ScHairSystemShapeSim.h" #include "ScActorSim.h" namespace physx { namespace Sc { class Scene; class HairSystemSim : public ActorSim { PX_NOCOPY(HairSystemSim) public: HairSystemSim(HairSystemCore& core, Scene& scene); ~HairSystemSim(); PX_INLINE Dy::HairSystem* getLowLevelHairSystem() const { return mLLHairSystem; } PX_INLINE HairSystemCore& getCore() const { return static_cast<HairSystemCore&>(mCore); } virtual PxActor* getPxActor() const { return getCore().getPxActor(); } PxBounds3 getBounds() const; void updateBounds(); void updateBoundsInAABBMgr(); bool isSleeping() const; bool isActive() const { return !isSleeping(); } void setActive(bool active, bool asPartOfCreation=false); void onSetWakeCounter(); HairSystemShapeSim& getShapeSim() { return mShapeSim; } private: Dy::HairSystem* mLLHairSystem; HairSystemShapeSim mShapeSim; // PT: as far as I can tell these are never actually called // void activate(); // void deactivate(); }; } // namespace Sc } // namespace physx #endif #endif
2,838
C
33.621951
92
0.744538
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScHairSystemSim.h" #include "ScHairSystemCore.h" #include "ScHairSystemShapeCore.h" #include "ScScene.h" #include "PxsSimulationController.h" using namespace physx; using namespace physx::Dy; Sc::HairSystemSim::HairSystemSim(HairSystemCore& core, Scene& scene) : ActorSim(scene, core), mShapeSim(*this, &core.getShapeCore()) { mLLHairSystem = scene.createLLHairSystem(this); mNodeIndex = scene.getSimpleIslandManager()->addHairSystem(mLLHairSystem, false); scene.getSimpleIslandManager()->activateNode(mNodeIndex); mLLHairSystem->setElementId(mShapeSim.getElementID()); PxHairSystemGeometry geometry; core.getShapeCore().setGeometry(geometry); PxsShapeCore* shapeCore = const_cast<PxsShapeCore*>(&core.getShapeCore().getCore()); mLLHairSystem->setShapeCore(shapeCore); } Sc::HairSystemSim::~HairSystemSim() { if (!mLLHairSystem) { return; } mScene.destroyLLHairSystem(*mLLHairSystem); mScene.getSimpleIslandManager()->removeNode(mNodeIndex); mCore.setSim(NULL); } void Sc::HairSystemSim::updateBounds() { mShapeSim.updateBounds(); } void Sc::HairSystemSim::updateBoundsInAABBMgr() { mShapeSim.updateBoundsInAABBMgr(); } PxBounds3 Sc::HairSystemSim::getBounds() const { return mShapeSim.getBounds(); } bool Sc::HairSystemSim::isSleeping() const { IG::IslandSim& sim = mScene.getSimpleIslandManager()->getAccurateIslandSim(); return sim.getActiveNodeIndex(mNodeIndex) == PX_INVALID_NODE; } void Sc::HairSystemSim::onSetWakeCounter() { getScene().getSimulationController()->setHairSystemWakeCounter(mLLHairSystem); if (mLLHairSystem->getCore().mWakeCounter > 0.0f) { getScene().getSimpleIslandManager()->activateNode(mNodeIndex); } else { getScene().getSimpleIslandManager()->deactivateNode(mNodeIndex); } } /*void Sc::HairSystemSim::activate() { activateInteractions(*this); } void Sc::HairSystemSim::deactivate() { deactivateInteractions(*this); }*/ #endif //PX_SUPPORT_GPU_PHYSX
3,569
C++
30.315789
85
0.767722
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScHairSystemCore.h" #include "ScHairSystemSim.h" #include "ScPhysics.h" namespace physx { namespace Sc { HairSystemCore::HairSystemCore() : ActorCore(PxActorType::eHAIRSYSTEM, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0) { } HairSystemCore::~HairSystemCore() {} void HairSystemCore::setMaterial(const PxU16 handle) { mShapeCore.getLLCore().setMaterial(handle); } void HairSystemCore::clearMaterials() { mShapeCore.getLLCore().clearMaterials(); } void HairSystemCore::setSleepThreshold(const PxReal v) { mShapeCore.getLLCore().mSleepThreshold = v; mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void HairSystemCore::setSolverIterationCounts(const PxU16 c) { mShapeCore.getLLCore().mSolverIterationCounts = c; mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void HairSystemCore::setWakeCounter(const PxReal v) { mShapeCore.getLLCore().mWakeCounter = v; mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; HairSystemSim* sim = getSim(); if(sim) { sim->onSetWakeCounter(); } } bool HairSystemCore::isSleeping() const { HairSystemSim* sim = getSim(); return sim ? sim->isSleeping() : (mShapeCore.getLLCore().mWakeCounter == 0.0f); } void HairSystemCore::wakeUp(PxReal wakeCounter) { mShapeCore.getLLCore().mWakeCounter = wakeCounter; mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void HairSystemCore::putToSleep() { mShapeCore.getLLCore().mWakeCounter = 0.0f; mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxActor* HairSystemCore::getPxActor() const { return PxPointerOffset<PxActor*>(const_cast<HairSystemCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); } HairSystemSim* HairSystemCore::getSim() const { return static_cast<HairSystemSim*>(ActorCore::getSim()); } PxReal HairSystemCore::getContactOffset() const { return mShapeCore.getContactOffset(); } void HairSystemCore::setContactOffset(PxReal v) { mShapeCore.setContactOffset(v); HairSystemSim* sim = getSim(); if(sim) { sim->getScene().updateContactDistance(sim->getShapeSim().getElementID(), v); } } void HairSystemCore::addAttachment(const BodySim& bodySim) { const HairSystemSim* sim = getSim(); if(sim) { sim->getScene().addAttachment(bodySim, *sim); } } void HairSystemCore::removeAttachment(const BodySim& bodySim) { const HairSystemSim* sim = getSim(); if(sim) { sim->getScene().removeAttachment(bodySim, *sim); } } void HairSystemCore::addAttachment(const SoftBodySim& sbSim) { const Sc::HairSystemSim* sim = getSim(); if(sim) { sim->getScene().addAttachment(sbSim, *sim); } } void HairSystemCore::removeAttachment(const SoftBodySim& sbSim) { const Sc::HairSystemSim* sim = getSim(); if(sim) { sim->getScene().removeAttachment(sbSim, *sim); } } void Sc::HairSystemCore::setFlags(PxHairSystemFlags flags) { mShapeCore.getLLCore().mParams.mFlags = flags; mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } } // namespace Sc } // namespace physx #endif // PX_SUPPORT_GPU_PHYSX
4,746
C++
28.855346
118
0.758323
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSleep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScScene.h" #include "ScArticulationSim.h" #include "ScBodySim.h" #include "common/PxProfileZone.h" #include "ScActorSim.h" #include "ScArticulationSim.h" #if PX_SUPPORT_GPU_PHYSX #include "ScSoftBodySim.h" #include "ScFEMClothSim.h" #include "ScParticleSystemSim.h" #include "ScHairSystemSim.h" #endif using namespace physx; using namespace physx::Cm; using namespace physx::Dy; using namespace Sc; // PT: "setActive()" moved from ActorSim to BodySim because GPU classes silently re-implement this in a very different way (see below), // i.e. it defeats the purpose of the virtual activate()/deactivate() functions. void Sc::BodySim::setActive(bool active, bool asPartOfCreation) { PX_ASSERT(!active || isDynamicRigid()); // Currently there should be no need to activate an actor that does not take part in island generation if(asPartOfCreation || isActive() != active) { PX_ASSERT(!asPartOfCreation || (getActorInteractionCount() == 0)); // On creation or destruction there should be no interactions if(active) { if(!asPartOfCreation) getScene().addToActiveList(*this); // Inactive => Active activate(); PX_ASSERT(asPartOfCreation || isActive()); } else { if(!asPartOfCreation) getScene().removeFromActiveList(*this); // Active => Inactive deactivate(); PX_ASSERT(asPartOfCreation || (!isActive())); } } } void Sc::ArticulationSim::setActive(bool b, bool asPartOfCreation) { const PxReal wakeCounter = mCore.getWakeCounter(); const PxU32 nbBodies = mBodies.size(); for(PxU32 i=0;i<nbBodies;i++) { if(i+1 < nbBodies) { PxPrefetchLine(mBodies[i+1],0); PxPrefetchLine(mBodies[i+1],128); } //KS - force in the wake counter from the articulation to its links. This is required because //GPU articulation simulation does not DMA back wake counters for each link - it just brings back a global wake counter mBodies[i]->getBodyCore().setWakeCounterFromSim(wakeCounter); mBodies[i]->setActive(b, asPartOfCreation); } } // PT: moving all the sleeping-related implementations to the same file clearly exposes the inconsistencies between them #if PX_SUPPORT_GPU_PHYSX void Sc::ParticleSystemSim::setActive(bool /*active*/, bool /*asPartOfCreation*/) { } void Sc::FEMClothSim::activate() { mScene.getSimulationController()->activateCloth(mLLFEMCloth); activateInteractions(*this); } void Sc::FEMClothSim::deactivate() { mScene.getSimulationController()->deactivateCloth(mLLFEMCloth); deactivateInteractions(*this); } void Sc::FEMClothSim::setActive(bool active, bool /*asPartOfCreation*/) { if(active) activate(); else deactivate(); } void Sc::SoftBodySim::setActive(bool active, bool /*asPartOfCreation*/) { if(active) getScene().getSimulationController()->activateSoftbody(mLLSoftBody); else getScene().getSimulationController()->deactivateSoftbody(mLLSoftBody); } void Sc::HairSystemSim::setActive(bool active, bool /*asPartOfCreation*/) { if(active) getScene().getSimulationController()->activateHairSystem(mLLHairSystem); else getScene().getSimulationController()->deactivateHairSystem(mLLHairSystem); } #endif namespace { struct GetRigidSim { static PX_FORCE_INLINE BodySim* getSim(const IG::Node& node) { return reinterpret_cast<BodySim*>(reinterpret_cast<PxU8*>(node.mRigidBody) - BodySim::getRigidBodyOffset()); } }; struct GetArticSim { static PX_FORCE_INLINE ArticulationSim* getSim(const IG::Node& node) { return reinterpret_cast<ArticulationSim*>(node.mLLArticulation->getUserData()); } }; #if PX_SUPPORT_GPU_PHYSX struct GetSoftBodySim { static PX_FORCE_INLINE SoftBodySim* getSim(const IG::Node& node) { return node.mLLSoftBody->getSoftBodySim(); } }; struct GetFEMClothSim { static PX_FORCE_INLINE FEMClothSim* getSim(const IG::Node& node) { return node.mLLFEMCloth->getFEMClothSim(); } }; struct GetHairSystemSim { static PX_FORCE_INLINE HairSystemSim* getSim(const IG::Node& node) { return node.mLLHairSystem->getHairSystemSim(); } }; #endif } template<class SimT, class SimAccessT, const bool active> static void setActive(PxU32& nbModified, const IG::IslandSim& islandSim, IG::Node::NodeType type) { PxU32 nbToProcess = active ? islandSim.getNbNodesToActivate(type) : islandSim.getNbNodesToDeactivate(type); const PxNodeIndex* indices = active ? islandSim.getNodesToActivate(type) : islandSim.getNodesToDeactivate(type); while(nbToProcess--) { const IG::Node& node = islandSim.getNode(*indices++); PX_ASSERT(node.mType == type); if(node.isActive()==active) { SimT* sim = SimAccessT::getSim(node); if(sim) { sim->setActive(active); nbModified++; } } } } #ifdef BATCHED namespace { struct SetActiveRigidSim { template<const bool active> static void setActive(Scene& /*scene*/, PxU32 nbObjects, BodySim** objects) { if(1) { while(nbObjects--) { (*objects)->setActive(active); objects++; } } else { if(active) { // scene.addToActiveList(*this); // activate(); // PX_ASSERT(isActive()); } else { // scene.removeFromActiveList(*this); // deactivate(); // PX_ASSERT(!isActive()); } } } }; } template<class SimT, class SimAccessT, class SetActiveBatchedT, const bool active> static void setActiveBatched(Scene& scene, PxU32& nbModified, const IG::IslandSim& islandSim, IG::Node::NodeType type) { PxU32 nbToProcess = active ? islandSim.getNbNodesToActivate(type) : islandSim.getNbNodesToDeactivate(type); const PxNodeIndex* indices = active ? islandSim.getNodesToActivate(type) : islandSim.getNodesToDeactivate(type); PX_ALLOCA(batch, SimT*, nbToProcess); PxU32 nb = 0; while(nbToProcess--) { const IG::Node& node = islandSim.getNode(*indices++); PX_ASSERT(node.mType == type); if(node.isActive()==active) { SimT* sim = SimAccessT::getSim(node); if(sim && sim->isActive()!=active) batch.mPointer[nb++] = sim; } } SetActiveBatchedT::setActive<active>(scene, nb, batch.mPointer); nbModified = nb; } /* Batched version would be just: a) addToActiveList(batched objects) b) activate(batched objects) void Sc::ActorSim::setActive(bool active) { PX_ASSERT(!active || isDynamicRigid()); // Currently there should be no need to activate an actor that does not take part in island generation if(isActive() != active) { if(active) { // Inactive => Active getScene().addToActiveList(*this); activate(); PX_ASSERT(isActive()); } else { // Active => Inactive getScene().removeFromActiveList(*this); deactivate(); PX_ASSERT(!isActive()); } } } */ #endif void Sc::Scene::putObjectsToSleep() { PX_PROFILE_ZONE("Sc::Scene::putObjectsToSleep", mContextId); //Set to sleep all bodies that were in awake islands that have just been put to sleep. const IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); PxU32 nbBodiesDeactivated = 0; //setActiveBatched<BodySim, GetRigidSim, SetActiveRigidSim, false>(*this, nbBodiesDeactivated, islandSim, IG::Node::eRIGID_BODY_TYPE); setActive<BodySim, GetRigidSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eRIGID_BODY_TYPE); setActive<ArticulationSim, GetArticSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eARTICULATION_TYPE); #if PX_SUPPORT_GPU_PHYSX setActive<SoftBodySim, GetSoftBodySim, false>(nbBodiesDeactivated, islandSim, IG::Node::eSOFTBODY_TYPE); setActive<FEMClothSim, GetFEMClothSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eFEMCLOTH_TYPE); setActive<HairSystemSim, GetHairSystemSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eHAIRSYSTEM_TYPE); #endif if(nbBodiesDeactivated) mDynamicsContext->setStateDirty(true); } void Sc::Scene::wakeObjectsUp() { PX_PROFILE_ZONE("Sc::Scene::wakeObjectsUp", mContextId); //Wake up all bodies that were in sleeping islands that have just been hit by a moving object. const IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); PxU32 nbBodiesWoken = 0; setActive<BodySim, GetRigidSim, true>(nbBodiesWoken, islandSim, IG::Node::eRIGID_BODY_TYPE); setActive<ArticulationSim, GetArticSim, true>(nbBodiesWoken, islandSim, IG::Node::eARTICULATION_TYPE); #if PX_SUPPORT_GPU_PHYSX setActive<SoftBodySim, GetSoftBodySim, true>(nbBodiesWoken, islandSim, IG::Node::eSOFTBODY_TYPE); setActive<FEMClothSim, GetFEMClothSim, true>(nbBodiesWoken, islandSim, IG::Node::eFEMCLOTH_TYPE); setActive<HairSystemSim, GetHairSystemSim, true>(nbBodiesWoken, islandSim, IG::Node::eHAIRSYSTEM_TYPE); #endif if(nbBodiesWoken) mDynamicsContext->setStateDirty(true); }
10,286
C++
31.553797
200
0.73566
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSqBoundsManager.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_SQ_BOUNDS_MANAGER_H #define SC_SQ_BOUNDS_MANAGER_H #include "foundation/PxUserAllocated.h" #include "foundation/PxBitMap.h" #include "foundation/PxArray.h" #include "ScSqBoundsSync.h" namespace physx { class PxBounds3; namespace Sc { struct SqBoundsSync; struct SqRefFinder; class ShapeSimBase; class SqBoundsManager0 : public PxUserAllocated { PX_NOCOPY(SqBoundsManager0) public: SqBoundsManager0(); void addSyncShape(ShapeSimBase& shape); void removeSyncShape(ShapeSimBase& shape); void syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices); private: PxArray<ShapeSimBase*> mShapes; // PxArray<ScPrunerHandle> mRefs; // SQ pruner references PxArray<PxU32> mBoundsIndices; // indices into the Sc bounds array PxArray<ShapeSimBase*> mRefless; // shapesims without references }; class SqBoundsManagerEx : public PxUserAllocated { PX_NOCOPY(SqBoundsManagerEx) public: SqBoundsManagerEx(); ~SqBoundsManagerEx(); void addSyncShape(ShapeSimBase& shape); void removeSyncShape(ShapeSimBase& shape); void syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices); private: PxArray<ShapeSimBase*> mWaitingRoom; // PT: one of the many solutions discussed in https://confluence.nvidia.com/display/~pterdiman/The+new+SQ+system // Just to get something working. This will most likely need revisiting later. struct PrunerSyncData : public PxUserAllocated { PxArray<ShapeSimBase*> mShapes; // // PT: layout dictated by the SqPruner API here. We could consider merging these two arrays. PxArray<ScPrunerHandle> mRefs; // SQ pruner references PxArray<PxU32> mBoundsIndices; // indices into the Sc bounds array }; PrunerSyncData** mPrunerSyncData; PxU32 mPrunerSyncDataSize; void resize(PxU32 index); }; //class SqBoundsManager : public SqBoundsManager0 class SqBoundsManager : public SqBoundsManagerEx { public: }; } } #endif
3,898
C
35.439252
170
0.751154
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScParticleSystemCore.h" #include "ScPhysics.h" #include "ScParticleSystemSim.h" #include "DyParticleSystem.h" #include "PxvGlobals.h" #include "PxPhysXGpu.h" using namespace physx; Sc::ParticleSystemCore::ParticleSystemCore(PxActorType::Enum actorType) : ActorCore(actorType, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0) { } Sc::ParticleSystemCore::~ParticleSystemCore() { } Sc::ParticleSystemSim* Sc::ParticleSystemCore::getSim() const { return static_cast<ParticleSystemSim*>(ActorCore::getSim()); } PxReal Sc::ParticleSystemCore::getSleepThreshold() const { return mShapeCore.getLLCore().sleepThreshold;//mCore.sleepThreshold; } void Sc::ParticleSystemCore::setSleepThreshold(const PxReal v) { mShapeCore.getLLCore().sleepThreshold = v; } PxReal Sc::ParticleSystemCore::getRestOffset() const { return mShapeCore.getLLCore().restOffset; } void Sc::ParticleSystemCore::setRestOffset(const PxReal v) { mShapeCore.getLLCore().restOffset = v; } PxReal Sc::ParticleSystemCore::getContactOffset() const { return mShapeCore.getContactOffset(); } void Sc::ParticleSystemCore::setContactOffset(const PxReal v) { mShapeCore.setContactOffset(v); Sc::ParticleSystemSim* sim = getSim(); if (sim) { sim->getScene().updateContactDistance(sim->getShapeSim().getElementID(), v); } } PxReal Sc::ParticleSystemCore::getParticleContactOffset() const { return mShapeCore.getLLCore().particleContactOffset; } void Sc::ParticleSystemCore::setParticleContactOffset(const PxReal v) { mShapeCore.getLLCore().particleContactOffset = v; } PxReal Sc::ParticleSystemCore::getSolidRestOffset() const { return mShapeCore.getLLCore().solidRestOffset; } void Sc::ParticleSystemCore::setSolidRestOffset(const PxReal v) { mShapeCore.getLLCore().solidRestOffset = v; } PxReal Sc::ParticleSystemCore::getFluidRestOffset() const { return mShapeCore.getLLCore().fluidRestOffset; } void Sc::ParticleSystemCore::setFluidRestOffset(const PxReal v) { mShapeCore.getLLCore().fluidRestOffset = v; } void Sc::ParticleSystemCore::setMaxDepenetrationVelocity(const PxReal v) { mShapeCore.getLLCore().maxDepenetrationVelocity = v; } PxReal Sc::ParticleSystemCore::getMaxDepenetrationVelocity() const { return mShapeCore.getLLCore().maxDepenetrationVelocity; } void Sc::ParticleSystemCore::setMaxVelocity(const PxReal v) { mShapeCore.getLLCore().maxVelocity = v; } PxReal Sc::ParticleSystemCore::getMaxVelocity() const { return mShapeCore.getLLCore().maxVelocity; } PxParticleSystemCallback* Sc::ParticleSystemCore::getParticleSystemCallback() const { return mShapeCore.getLLCore().mCallback; } void Sc::ParticleSystemCore::setParticleSystemCallback(PxParticleSystemCallback* callback) { mShapeCore.getLLCore().mCallback = callback; } PxReal Sc::ParticleSystemCore::getFluidBoundaryDensityScale() const { return mShapeCore.getLLCore().fluidBoundaryDensityScale; } void Sc::ParticleSystemCore::setFluidBoundaryDensityScale(const PxReal v) { mShapeCore.getLLCore().fluidBoundaryDensityScale = v; } PxU32 Sc::ParticleSystemCore::getGridSizeX() const { return mShapeCore.getLLCore().gridSizeX; } void Sc::ParticleSystemCore::setGridSizeX(const PxU32 v) { mShapeCore.getLLCore().gridSizeX = v; } PxU32 Sc::ParticleSystemCore::getGridSizeY() const { return mShapeCore.getLLCore().gridSizeY; } void Sc::ParticleSystemCore::setGridSizeY(const PxU32 v) { mShapeCore.getLLCore().gridSizeY = v; } PxU32 Sc::ParticleSystemCore::getGridSizeZ() const { return mShapeCore.getLLCore().gridSizeZ; } void Sc::ParticleSystemCore::setGridSizeZ(const PxU32 v) { mShapeCore.getLLCore().gridSizeZ = v; } void Sc::ParticleSystemCore::setSolverIterationCounts(PxU16 c) { mShapeCore.getLLCore().solverIterationCounts = c; } PxReal Sc::ParticleSystemCore::getWakeCounter() const { return mShapeCore.getLLCore().wakeCounter; } void Sc::ParticleSystemCore::setWakeCounter(const PxReal v) { mShapeCore.getLLCore().wakeCounter = v; } void Sc::ParticleSystemCore::setWakeCounterInternal(const PxReal v) { mShapeCore.getLLCore().wakeCounter = v; } bool Sc::ParticleSystemCore::isSleeping() const { Sc::ParticleSystemSim* sim = getSim(); return sim ? sim->isSleeping() : (mShapeCore.getLLCore().wakeCounter == 0.0f); } void Sc::ParticleSystemCore::wakeUp(PxReal wakeCounter) { mShapeCore.getLLCore().wakeCounter = wakeCounter; } void Sc::ParticleSystemCore::putToSleep() { mShapeCore.getLLCore().wakeCounter = 0.0f; } PxActor* Sc::ParticleSystemCore::getPxActor() const { return PxPointerOffset<PxActor*>(const_cast<ParticleSystemCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); } // TOFIX void Sc::ParticleSystemCore::enableCCD(const bool enable) { mShapeCore.getLLCore().enableCCD = enable; } void Sc::ParticleSystemCore::addRigidAttachment(Sc::BodyCore* core) { Sc::ParticleSystemSim* sim = getSim(); if(sim) sim->getScene().addRigidAttachment(core, *sim); } void Sc::ParticleSystemCore::removeRigidAttachment(Sc::BodyCore* core) { Sc::ParticleSystemSim* sim = getSim(); if (sim) sim->getScene().removeRigidAttachment(core, *sim); } void Sc::ParticleSystemCore::setFlags(PxParticleFlags flags) { Sc::ParticleSystemSim* sim = getSim(); PxParticleFlags oldFlags = mShapeCore.getLLCore().mFlags; mShapeCore.getLLCore().mFlags = flags; if (sim) { bool wasRigidCollisionDisabled = oldFlags & PxParticleFlag::eDISABLE_RIGID_COLLISION; bool isRigidCollisionDisabled = flags & PxParticleFlag::eDISABLE_RIGID_COLLISION; if (wasRigidCollisionDisabled ^ isRigidCollisionDisabled) { if (wasRigidCollisionDisabled) sim->getShapeSim().createLowLevelVolume(); else sim->getShapeSim().destroyLowLevelVolume(); } } } #endif //PX_SUPPORT_GPU_PHYSX
7,348
C++
25.340502
122
0.773272
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothCore.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScFEMClothCore.h" #include "ScPhysics.h" #include "ScFEMClothSim.h" #include "DyFEMCloth.h" #include "GuTetrahedronMesh.h" #include "GuBV4.h" #include "geometry/PxTetrahedronMesh.h" #include "cudamanager/PxCudaContextManager.h" using namespace physx; Sc::FEMClothCore::FEMClothCore() : ActorCore(PxActorType::eFEMCLOTH, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0), mGpuMemStat(0) { mCore.solverIterationCounts = (1 << 8) | 4; mCore.dirty = true; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION mCore.mFlags = PxFEMClothFlags(0); #endif mCore.mPositionInvMass = NULL; mCore.mVelocity = NULL; mCore.mRestPosition = NULL; mCore.wakeCounter = Physics::sWakeCounterOnCreation; } Sc::FEMClothCore::~FEMClothCore() { } PxFEMParameters Sc::FEMClothCore::getParameter() const { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION return mCore.parameters; #else return PxFEMParameters(); #endif } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void Sc::FEMClothCore::setParameter(const PxFEMParameters& parameter) { mCore.parameters = parameter; mCore.dirty = true; } #else void Sc::FEMClothCore::setParameter(const PxFEMParameters&) { mCore.dirty = true; } #endif void Sc::FEMClothCore::addRigidFilter(Sc::BodyCore* core, PxU32 vertId) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->getScene().addRigidFilter(core, *sim, vertId); } void Sc::FEMClothCore::removeRigidFilter(Sc::BodyCore* core, PxU32 vertId) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->getScene().removeRigidFilter(core, *sim, vertId); } PxU32 Sc::FEMClothCore::addRigidAttachment(Sc::BodyCore* core, PxU32 particleId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* params) { Sc::FEMClothSim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) { handle = sim->getScene().addRigidAttachment(core, *sim, particleId, actorSpacePose, params); } return handle; } void Sc::FEMClothCore::removeRigidAttachment(Sc::BodyCore* core, PxU32 handle) { Sc::FEMClothSim* sim = getSim(); if (sim) { sim->getScene().removeRigidAttachment(core, *sim, handle); setWakeCounter(ScInternalWakeCounterResetValue); } } void Sc::FEMClothCore::addTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->getScene().addTriRigidFilter(core, *sim, triIdx); } void Sc::FEMClothCore::removeTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->getScene().removeTriRigidFilter(core, *sim, triIdx); } PxU32 Sc::FEMClothCore::addTriRigidAttachment(Sc::BodyCore* core, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { Sc::FEMClothSim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) handle = sim->getScene().addTriRigidAttachment(core, *sim, triIdx, barycentric, actorSpacePose, constraint); return handle; } void Sc::FEMClothCore::removeTriRigidAttachment(Sc::BodyCore* core, PxU32 handle) { Sc::FEMClothSim* sim = getSim(); if (sim) { sim->getScene().removeTriRigidAttachment(core, *sim, handle); setWakeCounter(ScInternalWakeCounterResetValue); } } void Sc::FEMClothCore::addClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, PxU32 triIdx) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->getScene().addClothFilter(*otherCore, otherTriIdx, *sim, triIdx); } void Sc::FEMClothCore::removeClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, PxU32 triIdx) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->getScene().removeClothFilter(*otherCore, otherTriIdx, *sim, triIdx); } PxU32 Sc::FEMClothCore::addClothAttachment(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric) { Sc::FEMClothSim* sim = getSim(); PxU32 handle = 0xFFFFFFFF; if (sim) handle = sim->getScene().addTriClothAttachment(*otherCore, otherTriIdx, otherTriBarycentric, *sim, triIdx, triBarycentric); return handle; } void Sc::FEMClothCore::removeClothAttachment(Sc::FEMClothCore* otherCore, PxU32 handle) { Sc::FEMClothSim* sim = getSim(); setWakeCounter(ScInternalWakeCounterResetValue); otherCore->setWakeCounter(ScInternalWakeCounterResetValue); if (sim) sim->getScene().removeTriClothAttachment(*otherCore, *sim, handle); } void Sc::FEMClothCore::setBendingScales(const PxReal* const bendingScales, PxU32 nbElements) { mCore.mBendingScales.assign(bendingScales, bendingScales + nbElements); mCore.dirty = true; } const PxReal* Sc::FEMClothCore::getBendingScales() const { return mCore.mBendingScales.empty() ? NULL : mCore.mBendingScales.begin(); } void Sc::FEMClothCore::setSolverIterationCounts(const PxU16 c) { mCore.solverIterationCounts = c; mCore.dirty = true; } PxActor* Sc::FEMClothCore::getPxActor() const { return PxPointerOffset<PxActor*>(const_cast<FEMClothCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); } void Sc::FEMClothCore::attachShapeCore(ShapeCore* shapeCore) { Sc::FEMClothSim* sim = getSim(); if (sim) sim->attachShapeCore(shapeCore); } PxReal Sc::FEMClothCore::getWakeCounter() const { return mCore.wakeCounter; } void Sc::FEMClothCore::setWakeCounter(const PxReal v) { mCore.wakeCounter = v; mCore.dirty = true; Sc::FEMClothSim* sim = getSim(); if (sim) { sim->onSetWakeCounter(); } } void Sc::FEMClothCore::setWakeCounterInternal(const PxReal v) { mCore.wakeCounter = v; mCore.dirty = true; Sc::FEMClothSim* sim = getSim(); if (sim) { sim->onSetWakeCounter(); } } Sc::FEMClothSim* Sc::FEMClothCore::getSim() const { return static_cast<Sc::FEMClothSim*>(ActorCore::getSim()); } void Sc::FEMClothCore::setSimulationFilterData(const PxFilterData& data) { mFilterData = data; } PxFilterData Sc::FEMClothCore::getSimulationFilterData() const { return mFilterData; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void Sc::FEMClothCore::setFlags(PxFEMClothFlags flags) { mCore.mFlags = flags; mCore.dirty = true; } #endif void Sc::FEMClothCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags) { PX_UNUSED(shape); FEMClothSim* sim = getSim(); if (!sim) return; FEMClothShapeSim& s = sim->getShapeSim(); if (notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY) s.onVolumeOrTransformChange(); if (notifyFlags & ShapeChangeNotifyFlag::eMATERIAL) s.onMaterialChange(); if (notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING) s.onResetFiltering(); if (notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY) s.onVolumeOrTransformChange(); if (notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA) s.onFilterDataChange(); if (notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET) s.onContactOffsetChange(); if (notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET) s.onRestOffsetChange(); } #endif //PX_SUPPORT_GPU_PHYSX
8,547
C++
27.026229
173
0.753715
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationJointSim.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScArticulationJointSim.h" #include "ScArticulationJointCore.h" #include "ScBodySim.h" #include "ScScene.h" #include "PxsRigidBody.h" #include "ScArticulationSim.h" #include "PxsSimpleIslandManager.h" using namespace physx; Sc::ArticulationJointSim::ArticulationJointSim(ArticulationJointCore& joint, ActorSim& parent, ActorSim& child) : Interaction (parent, child, InteractionType::eARTICULATION, 0), mCore (joint) { { onActivate(NULL); registerInActors(); } BodySim& childBody = static_cast<BodySim&>(child), & parentBody = static_cast<BodySim&>(parent); parentBody.getArticulation()->addBody(childBody, &parentBody, this); mCore.setSim(this); } Sc::ArticulationJointSim::~ArticulationJointSim() { // articulation interactions do not make use of the dirty flags yet. If they did, a setClean(true) has to be introduced here. PX_ASSERT(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)); PX_ASSERT(!getDirtyFlags()); unregisterFromActors(); mCore.setSim(NULL); } Sc::BodySim& Sc::ArticulationJointSim::getParent() const { return static_cast<BodySim&>(getActorSim0()); } Sc::BodySim& Sc::ArticulationJointSim::getChild() const { return static_cast<BodySim&>(getActorSim1()); } bool Sc::ArticulationJointSim::onActivate(void*) { if(!(getParent().isActive() && getChild().isActive())) return false; raiseInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } bool Sc::ArticulationJointSim::onDeactivate() { clearInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } void Sc::ArticulationJointSim::setDirty() { Dy::ArticulationJointCore& llCore = mCore.getCore(); ArticulationSim* sim = mCore.getArticulation()->getSim(); sim->setJointDirty(llCore); }
3,421
C++
33.918367
126
0.758842
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScObjectIDTracker.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_OBJECT_ID_TRACKER_H #define SC_OBJECT_ID_TRACKER_H #include "CmIDPool.h" #include "foundation/PxBitMap.h" #include "foundation/PxUserAllocated.h" namespace physx { namespace Sc { // PT: TODO: this has no direct dependency on "Sc". It should really be a "Cm" class. class ObjectIDTracker : public PxUserAllocated { PX_NOCOPY(ObjectIDTracker) public: ObjectIDTracker() : mPendingReleasedIDs("objectIDTrackerIDs") {} PX_INLINE PxU32 createID() { return mIDPool.getNewID(); } PX_INLINE void releaseID(PxU32 id) { markIDAsDeleted(id); mPendingReleasedIDs.pushBack(id); } PX_INLINE PxIntBool isDeletedID(PxU32 id) const { return mDeletedIDsMap.boundedTest(id); } PX_FORCE_INLINE PxU32 getDeletedIDCount() const { return mPendingReleasedIDs.size(); } PX_INLINE void clearDeletedIDMap() { mDeletedIDsMap.clear(); } PX_INLINE void resizeDeletedIDMap(PxU32 id, PxU32 numIds) { mDeletedIDsMap.resize(id); mPendingReleasedIDs.reserve(numIds); } PX_INLINE void processPendingReleases() { for(PxU32 i=0; i < mPendingReleasedIDs.size(); i++) mIDPool.freeID(mPendingReleasedIDs[i]); mPendingReleasedIDs.clear(); } PX_INLINE void reset() { processPendingReleases(); mPendingReleasedIDs.reset(); // Don't free stuff in IDPool, we still need the list of free IDs // And it does not seem worth freeing the memory of the bitmap } PX_INLINE PxU32 getMaxID() const { return mIDPool.getMaxID(); } private: PX_INLINE void markIDAsDeleted(PxU32 id) { PX_ASSERT(!isDeletedID(id)); mDeletedIDsMap.growAndSet(id); } Cm::IDPool mIDPool; PxBitMap mDeletedIDsMap; PxArray<PxU32> mPendingReleasedIDs; // Buffer for released IDs to make sure newly created objects do not re-use these IDs immediately }; } } #endif
3,791
C
36.544554
140
0.688209
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementInteractionMarker.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScElementInteractionMarker.h" #include "ScNPhaseCore.h" using namespace physx; Sc::ElementInteractionMarker::~ElementInteractionMarker() { if(isRegistered()) getScene().unregisterInteraction(this); unregisterFromActors(); }
1,940
C++
45.214285
74
0.768557
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimulationController.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScSimulationController.h" #include "foundation/PxAllocator.h" #include "CmTask.h" #include "CmFlushPool.h" #include "PxNodeIndex.h" #include "ScArticulationSim.h" #include "PxsContext.h" #include "foundation/PxAllocator.h" #include "BpAABBManager.h" #include "DyVArticulation.h" using namespace physx; void Sc::SimulationController::updateScBodyAndShapeSim(PxsTransformCache& /*cache*/, Bp::BoundsArray& /*boundArray*/, PxBaseTask* continuation) { mCallback->updateScBodyAndShapeSim(continuation); } namespace { class UpdateArticulationAfterIntegrationTask : public Cm::Task { IG::IslandSim& mIslandSim; const PxNodeIndex* const PX_RESTRICT mNodeIndices; const PxU32 mNbArticulations; const PxReal mDt; PX_NOCOPY(UpdateArticulationAfterIntegrationTask) public: static const PxU32 NbArticulationsPerTask = 64; UpdateArticulationAfterIntegrationTask(PxU64 contextId, PxU32 nbArticulations, PxReal dt, const PxNodeIndex* nodeIndices, IG::IslandSim& islandSim) : Cm::Task(contextId), mIslandSim(islandSim), mNodeIndices(nodeIndices), mNbArticulations(nbArticulations), mDt(dt) { } virtual void runInternal() { for (PxU32 i = 0; i < mNbArticulations; ++i) { PxNodeIndex nodeIndex = mNodeIndices[i]; //Sc::ArticulationSim* articSim = getArticulationSim(mIslandSim, nodeIndex); Sc::ArticulationSim* articSim = mIslandSim.getArticulationSim(nodeIndex); articSim->sleepCheck(mDt); articSim->updateCached(NULL); } } virtual const char* getName() const { return "UpdateArticulationAfterIntegrationTask"; } }; } //KS - TODO - parallelize this bit!!!!! void Sc::SimulationController::updateArticulationAfterIntegration( PxsContext* llContext, Bp::AABBManagerBase* aabbManager, PxArray<Sc::BodySim*>& ccdBodies, PxBaseTask* continuation, IG::IslandSim& islandSim, float dt ) { const PxU32 nbActiveArticulations = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE); Cm::FlushPool& flushPool = llContext->getTaskPool(); const PxNodeIndex* activeArticulations = islandSim.getActiveNodes(IG::Node::eARTICULATION_TYPE); for (PxU32 i = 0; i < nbActiveArticulations; i += UpdateArticulationAfterIntegrationTask::NbArticulationsPerTask) { UpdateArticulationAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(UpdateArticulationAfterIntegrationTask)), UpdateArticulationAfterIntegrationTask)(islandSim.getContextId(), PxMin(UpdateArticulationAfterIntegrationTask::NbArticulationsPerTask, PxU32(nbActiveArticulations - i)), dt, activeArticulations + i, islandSim); startTask(task, continuation); } llContext->getLock().lock(); //const IG::NodeIndex* activeArticulations = islandSim.getActiveNodes(IG::Node::eARTICULATION_TYPE); PxBitMapPinned& changedAABBMgrActorHandles = aabbManager->getChangedAABBMgActorHandleMap(); for (PxU32 i = 0; i < nbActiveArticulations; i++) { Sc::ArticulationSim* articSim = islandSim.getArticulationSim(activeArticulations[i]); //KS - check links for CCD flags and add to mCcdBodies list if required.... articSim->updateCCDLinks(ccdBodies); articSim->markShapesUpdated(&changedAABBMgrActorHandles); } llContext->getLock().unlock(); }
4,895
C++
37.551181
262
0.772012
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScInteractionFlags.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_INTERACTION_FLAGS_H #define SC_INTERACTION_FLAGS_H #include "foundation/Px.h" namespace physx { namespace Sc { struct InteractionFlag // PT: TODO: use PxFlags { enum Enum { eRB_ELEMENT = (1 << 0), // Interactions between rigid body shapes eCONSTRAINT = (1 << 1), eFILTERABLE = (1 << 2), // Interactions that go through the filter code eIN_DIRTY_LIST = (1 << 3), // The interaction is in the dirty list eIS_FILTER_PAIR = (1 << 4), // The interaction is tracked by the filter callback mechanism eIS_ACTIVE = (1 << 5) }; }; struct InteractionDirtyFlag { enum Enum { eFILTER_STATE = (1 << 0), // All changes filtering related eMATERIAL = (1 << 1), eBODY_KINEMATIC = (1 << 2) | eFILTER_STATE, // A transition between dynamic and kinematic (and vice versa) require a refiltering eDOMINANCE = (1 << 3), eREST_OFFSET = (1 << 4), eVISUALIZATION = (1 << 5) }; }; } // namespace Sc } // namespace physx #endif
2,692
C
35.391891
133
0.71471
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBroadphase.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScBroadphase.h" #include "BpAABBManagerBase.h" #include "ScShapeSim.h" using namespace physx; using namespace Sc; using namespace Bp; /////////////////////////////////////////////////////////////////////////////// BroadphaseManager::BroadphaseManager() : mBroadPhaseCallback (NULL), mOutOfBoundsIDs ("sceneOutOfBoundsIds") { } BroadphaseManager::~BroadphaseManager() { } void BroadphaseManager::prepareOutOfBoundsCallbacks(AABBManagerBase* aabbManager) { AABBManagerBase::OutOfBoundsData data; if(!aabbManager->getOutOfBoundsObjects(data)) return; PxU32 nbOut = data.mNbOutOfBoundsObjects; void** outObjects = data.mOutOfBoundsObjects; mOutOfBoundsIDs.clear(); while(nbOut--) { const ElementSim* volume = reinterpret_cast<const ElementSim*>(*outObjects++); const Sc::ShapeSim* sim = static_cast<const Sc::ShapeSim*>(volume); mOutOfBoundsIDs.pushBack(sim->getElementID()); } } bool BroadphaseManager::fireOutOfBoundsCallbacks(Bp::AABBManagerBase* aabbManager, const ObjectIDTracker& tracker) { AABBManagerBase::OutOfBoundsData data; if(!aabbManager->getOutOfBoundsObjects(data)) return false; bool outputWarning = false; PxBroadPhaseCallback* cb = mBroadPhaseCallback; // Actors { PxU32 nbOut = data.mNbOutOfBoundsObjects; void** outObjects = data.mOutOfBoundsObjects; for(PxU32 i=0;i<nbOut;i++) { ElementSim* volume = reinterpret_cast<ElementSim*>(outObjects[i]); Sc::ShapeSim* sim = static_cast<Sc::ShapeSim*>(volume); // PT: TODO: I'm not sure the split between prepareOutOfBoundsCallbacks / fireOutOfBoundsCallbacks // and the test for deletion is still needed after the removal of SCB if(tracker.isDeletedID(mOutOfBoundsIDs[i])) continue; if(cb) { ActorSim& actor = volume->getActor(); RigidSim& rigidSim = static_cast<RigidSim&>(actor); PxActor* pxActor = rigidSim.getPxActor(); PxShape* px = sim->getPxShape(); cb->onObjectOutOfBounds(*px, *pxActor); } else outputWarning = true; } } // Aggregates { PxU32 nbOut = data.mNbOutOfBoundsAggregates; void** outAgg = data.mOutOfBoundsAggregates; for(PxU32 i=0;i<nbOut;i++) { PxAggregate* px = reinterpret_cast<PxAggregate*>(outAgg[i]); if(cb) cb->onObjectOutOfBounds(*px); else outputWarning = true; } } aabbManager->clearOutOfBoundsObjects(); return outputWarning; } void BroadphaseManager::flush(Bp::AABBManagerBase* /*aabbManager*/) { mOutOfBoundsIDs.reset(); }
4,172
C++
30.37594
114
0.731064
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScKinematics.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/PxProfileZone.h" #include "ScScene.h" #include "ScBodySim.h" #include "ScShapeSim.h" #include "PxsSimulationController.h" #include "BpAABBManagerBase.h" using namespace physx; using namespace Sc; //PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// // PT: TODO: consider using a non-member function for this one void BodySim::calculateKinematicVelocity(PxReal oneOverDt) { PX_ASSERT(isKinematic()); /*------------------------------------------------\ | kinematic bodies are moved directly by the user and are not influenced by external forces | we simply determine the distance moved since the last simulation frame and | assign the appropriate delta to the velocity. This vel will be used to shove dynamic | objects in the solver. | We have to do this like so in a delayed way, because when the user sets the target pos the dt is not | yet known. \------------------------------------------------*/ PX_ASSERT(isActive()); BodyCore& core = getBodyCore(); if (readInternalFlag(BF_KINEMATIC_MOVED)) { clearInternalFlag(InternalFlags(BF_KINEMATIC_SETTLING | BF_KINEMATIC_SETTLING_2)); const SimStateData* kData = getSimStateData(true); PX_ASSERT(kData); PX_ASSERT(kData->isKine()); PX_ASSERT(kData->getKinematicData()->targetValid); PxVec3 linVelLL, angVelLL; const PxTransform targetPose = kData->getKinematicData()->targetPose; const PxTransform& currBody2World = getBody2World(); //the kinematic target pose is now the target of the body (CoM) and not the actor. PxVec3 deltaPos = targetPose.p; deltaPos -= currBody2World.p; linVelLL = deltaPos * oneOverDt; PxQuat q = targetPose.q * currBody2World.q.getConjugate(); if (q.w < 0) //shortest angle. q = -q; PxReal angle; PxVec3 axis; q.toRadiansAndUnitAxis(angle, axis); angVelLL = axis * angle * oneOverDt; core.getCore().linearVelocity = linVelLL; core.getCore().angularVelocity = angVelLL; // Moving a kinematic should trigger a wakeUp call on a higher level. PX_ASSERT(core.getWakeCounter()>0); PX_ASSERT(isActive()); } else if (!readInternalFlag(BF_KINEMATIC_SURFACE_VELOCITY)) { core.setLinearVelocity(PxVec3(0.0f), true); core.setAngularVelocity(PxVec3(0.0f), true); } } namespace { class ScKinematicUpdateTask : public Cm::Task { Sc::BodyCore*const* mKinematics; const PxU32 mNbKinematics; const PxReal mOneOverDt; PX_NOCOPY(ScKinematicUpdateTask) public: static const PxU32 NbKinematicsPerTask = 1024; ScKinematicUpdateTask(Sc::BodyCore*const* kinematics, PxU32 nbKinematics, PxReal oneOverDt, PxU64 contextID) : Cm::Task(contextID), mKinematics(kinematics), mNbKinematics(nbKinematics), mOneOverDt(oneOverDt) { } virtual void runInternal() { Sc::BodyCore*const* kinematics = mKinematics; PxU32 nb = mNbKinematics; const float oneOverDt = mOneOverDt; while(nb--) { Sc::BodyCore* b = *kinematics++; PX_ASSERT(b->getSim()->isKinematic()); PX_ASSERT(b->getSim()->isActive()); b->getSim()->calculateKinematicVelocity(oneOverDt); } } virtual const char* getName() const { return "ScScene.KinematicUpdateTask"; } }; } void Sc::Scene::kinematicsSetup(PxBaseTask* continuation) { const PxU32 nbKinematics = getActiveKinematicBodiesCount(); if(!nbKinematics) return; BodyCore*const* kinematics = getActiveKinematicBodies(); // PT: create a copy of active bodies for the taks to operate on while the main array is // potentially resized by operations running in parallel. if(mActiveKinematicsCopyCapacity<nbKinematics) { PX_FREE(mActiveKinematicsCopy); mActiveKinematicsCopy = PX_ALLOCATE(BodyCore*, nbKinematics, "Sc::Scene::mActiveKinematicsCopy"); mActiveKinematicsCopyCapacity = nbKinematics; } PxMemCopy(mActiveKinematicsCopy, kinematics, nbKinematics*sizeof(BodyCore*)); kinematics = mActiveKinematicsCopy; Cm::FlushPool& flushPool = mLLContext->getTaskPool(); // PT: TASK-CREATION TAG // PT: TODO: better load balancing? This will be single threaded for less than 1K kinematics for(PxU32 i = 0; i < nbKinematics; i += ScKinematicUpdateTask::NbKinematicsPerTask) { ScKinematicUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicUpdateTask)), ScKinematicUpdateTask) (kinematics + i, PxMin(ScKinematicUpdateTask::NbKinematicsPerTask, nbKinematics - i), mOneOverDt, mContextId); task->setContinuation(continuation); task->removeReference(); } if((mPublicFlags & PxSceneFlag::eENABLE_GPU_DYNAMICS)) { // PT: running this serially for now because it's unsafe: mNPhaseCore->updateDirtyInteractions() (called after this) // can also call mSimulationController.updateDynamic() via BodySim::internalWakeUpBase PxU32 nb = nbKinematics; while(nb--) { Sc::BodyCore* b = *kinematics++; Sc::BodySim* bodySim = b->getSim(); PX_ASSERT(!bodySim->getArticulation()); mSimulationController->updateDynamic(NULL, bodySim->getNodeIndex()); } } } /////////////////////////////////////////////////////////////////////////////// // PT: TODO: consider using a non-member function for this one void BodySim::updateKinematicPose() { /*------------------------------------------------\ | kinematic bodies are moved directly by the user and are not influenced by external forces | we simply determine the distance moved since the last simulation frame and | assign the appropriate delta to the velocity. This vel will be used to shove dynamic | objects in the solver. | We have to do this like so in a delayed way, because when the user sets the target pos the dt is not | yet known. \------------------------------------------------*/ PX_ASSERT(isKinematic()); PX_ASSERT(isActive()); if(readInternalFlag(BF_KINEMATIC_MOVED)) { clearInternalFlag(InternalFlags(BF_KINEMATIC_SETTLING | BF_KINEMATIC_SETTLING_2)); const SimStateData* kData = getSimStateData(true); PX_ASSERT(kData); PX_ASSERT(kData->isKine()); PX_ASSERT(kData->getKinematicData()->targetValid); const PxTransform targetPose = kData->getKinematicData()->targetPose; getBodyCore().getCore().body2World = targetPose; } } namespace { class ScKinematicPoseUpdateTask : public Cm::Task { Sc::BodyCore*const* mKinematics; const PxU32 mNbKinematics; PX_NOCOPY(ScKinematicPoseUpdateTask) public: static const PxU32 NbKinematicsPerTask = 1024; ScKinematicPoseUpdateTask(Sc::BodyCore*const* kinematics, PxU32 nbKinematics, PxU64 contextID) : Cm::Task(contextID), mKinematics(kinematics), mNbKinematics(nbKinematics) { } virtual void runInternal() { const PxU32 nb = mNbKinematics; for(PxU32 a=0; a<nb; ++a) { if ((a + 16) < nb) { PxPrefetchLine(static_cast<Sc::BodyCore* const>(mKinematics[a + 16])); if ((a + 4) < nb) { PxPrefetchLine(static_cast<Sc::BodyCore* const>(mKinematics[a + 4])->getSim()); PxPrefetchLine(static_cast<Sc::BodyCore* const>(mKinematics[a + 4])->getSim()->getSimStateData_Unchecked()); } } Sc::BodyCore* b = static_cast<Sc::BodyCore* const>(mKinematics[a]); PX_ASSERT(b->getSim()->isKinematic()); PX_ASSERT(b->getSim()->isActive()); b->getSim()->updateKinematicPose(); } } virtual const char* getName() const { return "ScScene.ScKinematicPoseUpdateTask"; } }; } void Sc::Scene::integrateKinematicPose() { PX_PROFILE_ZONE("Sim.integrateKinematicPose", mContextId); const PxU32 nbKinematics = getActiveKinematicBodiesCount(); BodyCore*const* kinematics = getActiveKinematicBodies(); Cm::FlushPool& flushPool = mLLContext->getTaskPool(); // PT: TASK-CREATION TAG for(PxU32 i=0; i<nbKinematics; i+= ScKinematicPoseUpdateTask::NbKinematicsPerTask) { ScKinematicPoseUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicPoseUpdateTask)), ScKinematicPoseUpdateTask) (kinematics + i, PxMin(nbKinematics - i, ScKinematicPoseUpdateTask::NbKinematicsPerTask), mContextId); task->setContinuation(&mAfterIntegration); task->removeReference(); } } /////////////////////////////////////////////////////////////////////////////// namespace { class ScKinematicShapeUpdateTask : public Cm::Task { Sc::BodyCore*const* mKinematics; const PxU32 mNbKinematics; PxsTransformCache& mCache; Bp::BoundsArray& mBoundsArray; PX_NOCOPY(ScKinematicShapeUpdateTask) public: static const PxU32 NbKinematicsShapesPerTask = 1024; ScKinematicShapeUpdateTask(Sc::BodyCore*const* kinematics, PxU32 nbKinematics, PxsTransformCache& cache, Bp::BoundsArray& boundsArray, PxU64 contextID) : Cm::Task(contextID), mKinematics(kinematics), mNbKinematics(nbKinematics), mCache(cache), mBoundsArray(boundsArray) { } virtual void runInternal() { const PxU32 nb = mNbKinematics; for(PxU32 a=0; a<nb; ++a) { Sc::BodyCore* b = static_cast<Sc::BodyCore*>(mKinematics[a]); PX_ASSERT(b->getSim()->isKinematic()); PX_ASSERT(b->getSim()->isActive()); b->getSim()->updateCached(mCache, mBoundsArray); } } virtual const char* getName() const { return "ScScene.KinematicShapeUpdateTask"; } }; } void Sc::Scene::updateKinematicCached(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.updateKinematicCached", mContextId); const PxU32 nbKinematics = getActiveKinematicBodiesCount(); if(!nbKinematics) return; BodyCore*const* kinematics = getActiveKinematicBodies(); Cm::FlushPool& flushPool = mLLContext->getTaskPool(); PxU32 startIndex = 0; PxU32 nbShapes = 0; { PX_PROFILE_ZONE("ShapeUpdate", mContextId); // PT: TASK-CREATION TAG for(PxU32 i=0; i<nbKinematics; i++) { Sc::BodySim* sim = static_cast<Sc::BodyCore*>(kinematics[i])->getSim(); PX_ASSERT(sim->isKinematic()); PX_ASSERT(sim->isActive()); nbShapes += sim->getNbShapes(); if (nbShapes >= ScKinematicShapeUpdateTask::NbKinematicsShapesPerTask) { ScKinematicShapeUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicShapeUpdateTask)), ScKinematicShapeUpdateTask) (kinematics + startIndex, (i + 1) - startIndex, mLLContext->getTransformCache(), *mBoundsArray, mContextId); task->setContinuation(continuation); task->removeReference(); startIndex = i + 1; nbShapes = 0; } } if(nbShapes) { ScKinematicShapeUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicShapeUpdateTask)), ScKinematicShapeUpdateTask) (kinematics + startIndex, nbKinematics - startIndex, mLLContext->getTransformCache(), *mBoundsArray, mContextId); task->setContinuation(continuation); task->removeReference(); } } { PxBitMapPinned& changedAABBMap = mAABBManager->getChangedAABBMgActorHandleMap(); mLLContext->getTransformCache().setChangedState(); mBoundsArray->setChangedState(); for (PxU32 i = 0; i < nbKinematics; ++i) { Sc::BodySim* bodySim = static_cast<Sc::BodyCore*>(kinematics[i])->getSim(); if ((i+16) < nbKinematics) { PxPrefetchLine(kinematics[i + 16]); if ((i + 8) < nbKinematics) { PxPrefetchLine(kinematics[i + 8]->getSim()); } } // PT: ### changedMap pattern #1 PxU32 nbElems = bodySim->getNbElements(); Sc::ElementSim** elems = bodySim->getElements(); while (nbElems--) { Sc::ShapeSim* sim = static_cast<Sc::ShapeSim*>(*elems++); //KS - TODO - can we parallelize this? The problem with parallelizing is that it's a bit operation, //so we would either need to use atomic operations or have some high-level concept that guarantees //that threads don't write to the same word in the map simultaneously if (sim->getFlags()&PxU32(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) changedAABBMap.set(sim->getElementID()); } mSimulationController->updateDynamic(NULL, bodySim->getNodeIndex()); } } } /////////////////////////////////////////////////////////////////////////////// // PT: TODO: consider using a non-member function for this one bool BodySim::deactivateKinematic() { BodyCore& core = getBodyCore(); if(readInternalFlag(BF_KINEMATIC_SETTLING_2)) { clearInternalFlag(BF_KINEMATIC_SETTLING_2); core.setWakeCounterFromSim(0); // For sleeping objects the wake counter must be 0. This needs to hold for kinematics too. notifyReadyForSleeping(); notifyPutToSleep(); setActive(false); return true; } else if (readInternalFlag(BF_KINEMATIC_SETTLING)) { clearInternalFlag(BF_KINEMATIC_SETTLING); raiseInternalFlag(BF_KINEMATIC_SETTLING_2); } else if (!readInternalFlag(BF_KINEMATIC_SURFACE_VELOCITY)) { clearInternalFlag(BF_KINEMATIC_MOVED); raiseInternalFlag(BF_KINEMATIC_SETTLING); } return false; } // PT: called during fetchResults() void Sc::Scene::postCallbacksPreSyncKinematics() { PX_PROFILE_ZONE("Sim.postCallbacksPreSyncKinematics", mContextId); // Put/prepare kinematics to/for sleep and invalidate target pose // note: this needs to get done after the contact callbacks because // the target might get read there. // PxU32 nbKinematics = getActiveKinematicBodiesCount(); BodyCore*const* kinematics = getActiveKinematicBodies(); //KS - this method must run over the kinematic actors in reverse. while(nbKinematics--) { if(nbKinematics > 16) { PxPrefetchLine(static_cast<BodyCore*>(kinematics[nbKinematics-16])); } if (nbKinematics > 4) { PxPrefetchLine((static_cast<BodyCore*>(kinematics[nbKinematics - 4]))->getSim()); PxPrefetchLine((static_cast<BodyCore*>(kinematics[nbKinematics - 4]))->getSim()->getSimStateData_Unchecked()); } BodyCore* b = static_cast<BodyCore*>(kinematics[nbKinematics]); //kinematics++; PX_ASSERT(b->getSim()->isKinematic()); PX_ASSERT(b->getSim()->isActive()); b->invalidateKinematicTarget(); b->getSim()->deactivateKinematic(); } }
15,400
C++
31.698514
154
0.709545
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScScene.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScPhysics.h" #include "ScScene.h" #include "BpBroadPhase.h" #include "ScConstraintSim.h" #include "ScConstraintCore.h" #include "ScArticulationJointCore.h" #include "ScArticulationTendonCore.h" #include "ScArticulationSensor.h" #include "ScArticulationSim.h" #include "ScArticulationJointSim.h" #include "ScArticulationTendonSim.h" #include "ScArticulationSensorSim.h" #include "ScConstraintInteraction.h" #include "ScTriggerInteraction.h" #include "ScSimStats.h" #include "PxvGlobals.h" #include "PxsCCD.h" #include "ScSimulationController.h" #include "ScSqBoundsManager.h" #if defined(__APPLE__) && defined(__POWERPC__) #include <ppc_intrinsics.h> #endif #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXGpu.h" #include "PxsKernelWrangler.h" #include "PxsHeapMemoryAllocator.h" #include "cudamanager/PxCudaContextManager.h" #endif #include "PxsMemoryManager.h" #include "ScShapeInteraction.h" #if PX_SUPPORT_GPU_PHYSX #include "PxSoftBody.h" #include "ScSoftBodySim.h" #include "DySoftBody.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxFEMCloth.h" #include "PxHairSystem.h" #endif #include "ScFEMClothSim.h" #include "DyFEMCloth.h" #include "ScParticleSystemSim.h" #include "DyParticleSystem.h" #include "ScHairSystemSim.h" #include "DyHairSystem.h" #endif using namespace physx; using namespace Cm; using namespace Dy; using namespace Sc; PX_IMPLEMENT_OUTPUT_ERROR namespace physx { namespace Sc { class LLArticulationRCPool : public PxPool<FeatherstoneArticulation, PxAlignedAllocator<64> > { public: LLArticulationRCPool() {} }; #if PX_SUPPORT_GPU_PHYSX class LLSoftBodyPool : public PxPool<SoftBody, PxAlignedAllocator<64> > { public: LLSoftBodyPool() {} }; class LLFEMClothPool : public PxPool<FEMCloth, PxAlignedAllocator<64> > { public: LLFEMClothPool() {} }; class LLParticleSystemPool : public PxPool<ParticleSystem, PxAlignedAllocator<64> > { public: LLParticleSystemPool() {} }; class LLHairSystemPool : public PxPool<HairSystem, PxAlignedAllocator<64> > { public: LLHairSystemPool() {} }; #endif static const char* sFilterShaderDataMemAllocId = "SceneDesc filterShaderData"; }} void PxcDisplayContactCacheStats(); static const bool gUseNewTaskAllocationScheme = false; namespace { class ScAfterIntegrationTask : public Cm::Task { public: static const PxU32 MaxTasks = 256; private: const PxNodeIndex* const mIndices; const PxU32 mNumBodies; PxsContext* mContext; Context* mDynamicsContext; PxsTransformCache& mCache; Sc::Scene& mScene; public: ScAfterIntegrationTask(const PxNodeIndex* const indices, PxU32 numBodies, PxsContext* context, Context* dynamicsContext, PxsTransformCache& cache, Sc::Scene& scene) : Cm::Task (scene.getContextId()), mIndices (indices), mNumBodies (numBodies), mContext (context), mDynamicsContext(dynamicsContext), mCache (cache), mScene (scene) { } virtual void runInternal() { const PxU32 rigidBodyOffset = Sc::BodySim::getRigidBodyOffset(); Sc::BodySim* bpUpdates[MaxTasks]; Sc::BodySim* ccdBodies[MaxTasks]; Sc::BodySim* activateBodies[MaxTasks]; Sc::BodySim* deactivateBodies[MaxTasks]; PxU32 nbBpUpdates = 0, nbCcdBodies = 0; IG::SimpleIslandManager& manager = *mScene.getSimpleIslandManager(); const IG::IslandSim& islandSim = manager.getAccurateIslandSim(); Bp::BoundsArray& boundsArray = mScene.getBoundsArray(); Sc::BodySim* frozen[MaxTasks], * unfrozen[MaxTasks]; PxU32 nbFrozen = 0, nbUnfrozen = 0; PxU32 nbActivated = 0, nbDeactivated = 0; for(PxU32 i = 0; i < mNumBodies; i++) { PxsRigidBody* rigid = islandSim.getRigidBody(mIndices[i]); Sc::BodySim* bodySim = reinterpret_cast<Sc::BodySim*>(reinterpret_cast<PxU8*>(rigid) - rigidBodyOffset); //This move to PxgPostSolveWorkerTask for the gpu dynamic //bodySim->sleepCheck(mDt, mOneOverDt, mEnableStabilization); PxsBodyCore& bodyCore = bodySim->getBodyCore().getCore(); //If we got in this code, then this is an active object this frame. The solver computed the new wakeCounter and we //commit it at this stage. We need to do it this way to avoid a race condition between the solver and the island gen, where //the island gen may have deactivated a body while the solver decided to change its wake counter. bodyCore.wakeCounter = bodyCore.solverWakeCounter; PxsRigidBody& llBody = bodySim->getLowLevelBody(); const PxIntBool isFrozen = bodySim->isFrozen(); if(!isFrozen) { bpUpdates[nbBpUpdates++] = bodySim; // PT: TODO: remove duplicate "isFrozen" test inside updateCached // bodySim->updateCached(NULL); bodySim->updateCached(mCache, boundsArray); } if(llBody.isFreezeThisFrame() && isFrozen) frozen[nbFrozen++] = bodySim; else if(llBody.isUnfreezeThisFrame()) unfrozen[nbUnfrozen++] = bodySim; if(bodyCore.mFlags & PxRigidBodyFlag::eENABLE_CCD) ccdBodies[nbCcdBodies++] = bodySim; if(llBody.isActivateThisFrame()) { PX_ASSERT(!llBody.isDeactivateThisFrame()); activateBodies[nbActivated++] = bodySim; } else if(llBody.isDeactivateThisFrame()) { deactivateBodies[nbDeactivated++] = bodySim; } llBody.clearAllFrameFlags(); } if(nbBpUpdates) { mCache.setChangedState(); boundsArray.setChangedState(); } if(nbBpUpdates>0 || nbFrozen > 0 || nbCcdBodies>0 || nbActivated>0 || nbDeactivated>0) { //Write active bodies to changed actor map mContext->getLock().lock(); PxBitMapPinned& changedAABBMgrHandles = mScene.getAABBManager()->getChangedAABBMgActorHandleMap(); for(PxU32 i = 0; i < nbBpUpdates; i++) { // PT: ### changedMap pattern #1 PxU32 nbElems = bpUpdates[i]->getNbElements(); Sc::ElementSim** elems = bpUpdates[i]->getElements(); while (nbElems--) { Sc::ShapeSim* sim = static_cast<Sc::ShapeSim*>(*elems++); // PT: TODO: what's the difference between this test and "isInBroadphase" as used in bodySim->updateCached ? // PT: Also, shouldn't it be "isInAABBManager" rather than BP ? if (sim->getFlags()&PxU32(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) // TODO: need trigger shape here? changedAABBMgrHandles.growAndSet(sim->getElementID()); } } PxArray<Sc::BodySim*>& sceneCcdBodies = mScene.getCcdBodies(); for (PxU32 i = 0; i < nbCcdBodies; i++) sceneCcdBodies.pushBack(ccdBodies[i]); for(PxU32 i=0;i<nbFrozen;i++) { PX_ASSERT(frozen[i]->isFrozen()); frozen[i]->freezeTransforms(&changedAABBMgrHandles); } for(PxU32 i=0;i<nbUnfrozen;i++) { PX_ASSERT(!unfrozen[i]->isFrozen()); unfrozen[i]->createSqBounds(); } for(PxU32 i = 0; i < nbActivated; ++i) activateBodies[i]->notifyNotReadyForSleeping(); for(PxU32 i = 0; i < nbDeactivated; ++i) deactivateBodies[i]->notifyReadyForSleeping(); mContext->getLock().unlock(); } } virtual const char* getName() const { return "ScScene.afterIntegrationTask"; } private: PX_NOCOPY(ScAfterIntegrationTask) }; class ScSimulationControllerCallback : public PxsSimulationControllerCallback { Sc::Scene* mScene; public: ScSimulationControllerCallback(Sc::Scene* scene) : mScene(scene) { } virtual void updateScBodyAndShapeSim(PxBaseTask* continuation) { PxsContext* contextLL = mScene->getLowLevelContext(); IG::SimpleIslandManager* islandManager = mScene->getSimpleIslandManager(); Dy::Context* dynamicContext = mScene->getDynamicsContext(); Cm::FlushPool& flushPool = contextLL->getTaskPool(); const PxU32 MaxBodiesPerTask = ScAfterIntegrationTask::MaxTasks; PxsTransformCache& cache = contextLL->getTransformCache(); const IG::IslandSim& islandSim = islandManager->getAccurateIslandSim(); /*const*/ PxU32 numBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); const PxNodeIndex*const nodeIndices = islandSim.getActiveNodes(IG::Node::eRIGID_BODY_TYPE); const PxU32 rigidBodyOffset = Sc::BodySim::getRigidBodyOffset(); // PT: TASK-CREATION TAG if(!gUseNewTaskAllocationScheme) { PxU32 nbShapes = 0; PxU32 startIdx = 0; for (PxU32 i = 0; i < numBodies; i++) { if (nbShapes >= MaxBodiesPerTask) { ScAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScAfterIntegrationTask)), ScAfterIntegrationTask(nodeIndices + startIdx, i - startIdx, contextLL, dynamicContext, cache, *mScene)); startTask(task, continuation); startIdx = i; nbShapes = 0; } PxsRigidBody* rigid = islandSim.getRigidBody(nodeIndices[i]); Sc::BodySim* bodySim = reinterpret_cast<Sc::BodySim*>(reinterpret_cast<PxU8*>(rigid) - rigidBodyOffset); nbShapes += PxMax(1u, bodySim->getNbShapes()); //Always add at least 1 shape in, even if the body has zero shapes because there is still some per-body overhead } if (nbShapes) { ScAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScAfterIntegrationTask)), ScAfterIntegrationTask(nodeIndices + startIdx, numBodies - startIdx, contextLL, dynamicContext, cache, *mScene)); startTask(task, continuation); } } else { // PT: const PxU32 numCpuTasks = continuation->getTaskManager()->getCpuDispatcher()->getWorkerCount(); PxU32 nbPerTask; if(numCpuTasks) nbPerTask = numBodies > numCpuTasks ? numBodies / numCpuTasks : numBodies; else nbPerTask = numBodies; // PT: we need to respect that limit even with a single thread, because of hardcoded buffer limits in ScAfterIntegrationTask. if(nbPerTask>MaxBodiesPerTask) nbPerTask = MaxBodiesPerTask; PxU32 start = 0; while(numBodies) { const PxU32 nb = numBodies < nbPerTask ? numBodies : nbPerTask; ScAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScAfterIntegrationTask)), ScAfterIntegrationTask(nodeIndices+start, nb, contextLL, dynamicContext, cache, *mScene)); start += nb; numBodies -= nb; startTask(task, continuation); } } } virtual PxU32 getNbCcdBodies() { return mScene->getCcdBodies().size(); } }; // PT: TODO: what is this Pxg class doing here? class PxgUpdateBodyAndShapeStatusTask : public Cm::Task { public: static const PxU32 MaxTasks = 2048; private: const PxNodeIndex* const mNodeIndices; const PxU32 mNumBodies; Sc::Scene& mScene; void** mRigidBodyLL; PxU32* mActivatedBodies; PxU32* mDeactivatedBodies; PxI32& mCCDBodyWriteIndex; public: PxgUpdateBodyAndShapeStatusTask(const PxNodeIndex* const indices, PxU32 numBodies, void** rigidBodyLL, PxU32* activatedBodies, PxU32* deactivatedBodies, Sc::Scene& scene, PxI32& ccdBodyWriteIndex) : Cm::Task (scene.getContextId()), mNodeIndices (indices), mNumBodies (numBodies), mScene (scene), mRigidBodyLL (rigidBodyLL), mActivatedBodies (activatedBodies), mDeactivatedBodies (deactivatedBodies), mCCDBodyWriteIndex (ccdBodyWriteIndex) { } virtual void runInternal() { IG::SimpleIslandManager& islandManager = *mScene.getSimpleIslandManager(); const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim(); PxU32 nbCcdBodies = 0; PxArray<Sc::BodySim*>& sceneCcdBodies = mScene.getCcdBodies(); Sc::BodySim* ccdBodies[MaxTasks]; const size_t bodyOffset = PX_OFFSET_OF_RT(Sc::BodySim, getLowLevelBody()); for(PxU32 i=0; i<mNumBodies; ++i) { const PxU32 nodeIndex = mNodeIndices[i].index(); PxsRigidBody* rigidLL = reinterpret_cast<PxsRigidBody*>(mRigidBodyLL[nodeIndex]); PxsBodyCore* bodyCore = &rigidLL->getCore(); bodyCore->wakeCounter = bodyCore->solverWakeCounter; //we can set the frozen/unfrozen flag in GPU, but we have copied the internalflags //from the solverbodysleepdata to pxsbodycore, so we just need to clear the frozen flag in here rigidLL->clearAllFrameFlags(); PX_ASSERT(mActivatedBodies[nodeIndex] <= 1); PX_ASSERT(mDeactivatedBodies[nodeIndex] <= 1); if(mActivatedBodies[nodeIndex]) { PX_ASSERT(bodyCore->wakeCounter > 0.0f); islandManager.activateNode(mNodeIndices[i]); } else if(mDeactivatedBodies[nodeIndex]) { //KS - the CPU code can reset the wake counter due to lost touches in parallel with the solver, so we need to verify //that the wakeCounter is still 0 before deactivating the node if (bodyCore->wakeCounter == 0.0f) { islandManager.deactivateNode(mNodeIndices[i]); } } if (bodyCore->mFlags & PxRigidBodyFlag::eENABLE_CCD) { PxsRigidBody* rigidBody = islandSim.getRigidBody(mNodeIndices[i]); Sc::BodySim* bodySim = reinterpret_cast<Sc::BodySim*>(reinterpret_cast<PxU8*>(rigidBody) - bodyOffset); ccdBodies[nbCcdBodies++] = bodySim; } } if(nbCcdBodies > 0) { PxI32 startIndex = PxAtomicAdd(&mCCDBodyWriteIndex, PxI32(nbCcdBodies)) - PxI32(nbCcdBodies); for(PxU32 a = 0; a < nbCcdBodies; ++a) { sceneCcdBodies[startIndex + a] = ccdBodies[a]; } } } virtual const char* getName() const { return "ScScene.PxgUpdateBodyAndShapeStatusTask"; } private: PX_NOCOPY(PxgUpdateBodyAndShapeStatusTask) }; #if PX_SUPPORT_GPU_PHYSX // PT: TODO: what is this Pxg class doing here? class PxgSimulationControllerCallback : public PxsSimulationControllerCallback { Sc::Scene* mScene; PxI32 mCcdBodyWriteIndex; public: PxgSimulationControllerCallback(Sc::Scene* scene) : mScene(scene), mCcdBodyWriteIndex(0) { } virtual void updateScBodyAndShapeSim(PxBaseTask* continuation) { IG::SimpleIslandManager* islandManager = mScene->getSimpleIslandManager(); PxsSimulationController* simulationController = mScene->getSimulationController(); PxsContext* contextLL = mScene->getLowLevelContext(); IG::IslandSim& islandSim = islandManager->getAccurateIslandSim(); const PxU32 numBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); const PxNodeIndex*const nodeIndices = islandSim.getActiveNodes(IG::Node::eRIGID_BODY_TYPE); PxU32* activatedBodies = simulationController->getActiveBodies(); PxU32* deactivatedBodies = simulationController->getDeactiveBodies(); //PxsRigidBody** rigidBodyLL = simulationController->getRigidBodies(); void** rigidBodyLL = simulationController->getRigidBodies(); Cm::FlushPool& flushPool = contextLL->getTaskPool(); PxArray<Sc::BodySim*>& ccdBodies = mScene->getCcdBodies(); ccdBodies.forceSize_Unsafe(0); ccdBodies.reserve(numBodies); ccdBodies.forceSize_Unsafe(numBodies); mCcdBodyWriteIndex = 0; // PT: TASK-CREATION TAG for(PxU32 i = 0; i < numBodies; i+=PxgUpdateBodyAndShapeStatusTask::MaxTasks) { PxgUpdateBodyAndShapeStatusTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(PxgUpdateBodyAndShapeStatusTask)), PxgUpdateBodyAndShapeStatusTask(nodeIndices + i, PxMin(PxgUpdateBodyAndShapeStatusTask::MaxTasks, numBodies - i), rigidBodyLL, activatedBodies, deactivatedBodies, *mScene, mCcdBodyWriteIndex)); task->setContinuation(continuation); task->removeReference(); } PxU32* unfrozenShapeIndices = simulationController->getUnfrozenShapes(); PxU32* frozenShapeIndices = simulationController->getFrozenShapes(); const PxU32 nbFrozenShapes = simulationController->getNbFrozenShapes(); const PxU32 nbUnfrozenShapes = simulationController->getNbUnfrozenShapes(); PxsShapeSim** shapeSimsLL = simulationController->getShapeSims(); const size_t shapeOffset = PX_OFFSET_OF_RT(Sc::ShapeSim, getLLShapeSim()); for(PxU32 i=0; i<nbFrozenShapes; ++i) { const PxU32 shapeIndex = frozenShapeIndices[i]; PxsShapeSim* shapeLL = shapeSimsLL[shapeIndex]; Sc::ShapeSim* shape = reinterpret_cast<Sc::ShapeSim*>(reinterpret_cast<PxU8*>(shapeLL) - shapeOffset); shape->destroySqBounds(); } for(PxU32 i=0; i<nbUnfrozenShapes; ++i) { const PxU32 shapeIndex = unfrozenShapeIndices[i]; PxsShapeSim* shapeLL = shapeSimsLL[shapeIndex]; Sc::ShapeSim* shape = reinterpret_cast<Sc::ShapeSim*>(reinterpret_cast<PxU8*>(shapeLL) - shapeOffset); shape->createSqBounds(); } if (simulationController->hasFEMCloth()) { //KS - technically, there's a race condition calling activateNode/deactivateNode, but we know that it is //safe because these deactivate/activate calls came from the solver. This means that we know that the //actors are active currently, so at most we are just clearing/setting the ready for sleeping flag. //None of the more complex logic that touching shared state will be executed. const PxU32 nbActivatedCloth = simulationController->getNbActivatedFEMCloth(); Dy::FEMCloth** activatedCloths = simulationController->getActivatedFEMCloths(); for (PxU32 i = 0; i < nbActivatedCloth; ++i) { PxNodeIndex nodeIndex = activatedCloths[i]->getFEMClothSim()->getNodeIndex(); islandManager->activateNode(nodeIndex); } const PxU32 nbDeactivatedCloth = simulationController->getNbDeactivatedFEMCloth(); Dy::FEMCloth** deactivatedCloths = simulationController->getDeactivatedFEMCloths(); for (PxU32 i = 0; i < nbDeactivatedCloth; ++i) { PxNodeIndex nodeIndex = deactivatedCloths[i]->getFEMClothSim()->getNodeIndex(); islandManager->deactivateNode(nodeIndex); } } if (simulationController->hasSoftBodies()) { //KS - technically, there's a race condition calling activateNode/deactivateNode, but we know that it is //safe because these deactivate/activate calls came from the solver. This means that we know that the //actors are active currently, so at most we are just clearing/setting the ready for sleeping flag. //None of the more complex logic that touching shared state will be executed. const PxU32 nbDeactivatedSB = simulationController->getNbDeactivatedSoftbodies(); Dy::SoftBody** deactivatedSB = simulationController->getDeactivatedSoftbodies(); for (PxU32 i = 0; i < nbDeactivatedSB; ++i) { PxNodeIndex nodeIndex = deactivatedSB[i]->getSoftBodySim()->getNodeIndex(); islandManager->deactivateNode(nodeIndex); } const PxU32 nbActivatedSB = simulationController->getNbActivatedSoftbodies(); Dy::SoftBody** activatedSB = simulationController->getActivatedSoftbodies(); for (PxU32 i = 0; i < nbActivatedSB; ++i) { PxNodeIndex nodeIndex = activatedSB[i]->getSoftBodySim()->getNodeIndex(); islandManager->activateNode(nodeIndex); } } if (simulationController->hasHairSystems()) { // comment from KS regarding race condition applies here, too const PxU32 nbDeactivatedHS = simulationController->getNbDeactivatedHairSystems(); Dy::HairSystem** deactivatedHS = simulationController->getDeactivatedHairSystems(); for (PxU32 i = 0; i < nbDeactivatedHS; ++i) { PxNodeIndex nodeIndex = deactivatedHS[i]->getHairSystemSim()->getNodeIndex(); islandManager->deactivateNode(nodeIndex); } const PxU32 nbActivatedHS = simulationController->getNbActivatedHairSystems(); Dy::HairSystem** activatedHS = simulationController->getActivatedHairSystems(); for (PxU32 i = 0; i < nbActivatedHS; ++i) { PxNodeIndex nodeIndex = activatedHS[i]->getHairSystemSim()->getNodeIndex(); islandManager->activateNode(nodeIndex); } } } virtual PxU32 getNbCcdBodies() { return PxU32(mCcdBodyWriteIndex); } }; #endif } static Bp::AABBManagerBase* createAABBManagerCPU(const PxSceneDesc& desc, Bp::BroadPhase* broadPhase, Bp::BoundsArray* boundsArray, PxFloatArrayPinned* contactDistances, PxVirtualAllocator& allocator, PxU64 contextID) { return PX_NEW(Bp::AABBManager)(*broadPhase, *boundsArray, *contactDistances, desc.limits.maxNbAggregates, desc.limits.maxNbStaticShapes + desc.limits.maxNbDynamicShapes, allocator, contextID, desc.kineKineFilteringMode, desc.staticKineFilteringMode); } #if PX_SUPPORT_GPU_PHYSX static Bp::AABBManagerBase* createAABBManagerGPU(PxsKernelWranglerManager* kernelWrangler, PxCudaContextManager* cudaContextManager, PxsHeapMemoryAllocatorManager* heapMemoryAllocationManager, const PxSceneDesc& desc, Bp::BroadPhase* broadPhase, Bp::BoundsArray* boundsArray, PxFloatArrayPinned* contactDistances, PxVirtualAllocator& allocator, PxU64 contextID) { return PxvGetPhysXGpu(true)->createGpuAABBManager( kernelWrangler, cudaContextManager, desc.gpuComputeVersion, desc.gpuDynamicsConfig, heapMemoryAllocationManager, *broadPhase, *boundsArray, *contactDistances, desc.limits.maxNbAggregates, desc.limits.maxNbStaticShapes + desc.limits.maxNbDynamicShapes, allocator, contextID, desc.kineKineFilteringMode, desc.staticKineFilteringMode); } #endif Sc::Scene::Scene(const PxSceneDesc& desc, PxU64 contextID) : mContextId (contextID), mActiveBodies ("sceneActiveBodies"), mActiveKinematicBodyCount (0), mActiveDynamicBodyCount (0), mActiveKinematicsCopy (NULL), mActiveKinematicsCopyCapacity (0), mPointerBlock8Pool ("scenePointerBlock8Pool"), mPointerBlock16Pool ("scenePointerBlock16Pool"), mPointerBlock32Pool ("scenePointerBlock32Pool"), mLLContext (NULL), mAABBManager (NULL), mCCDContext (NULL), mNumFastMovingShapes (0), mCCDPass (0), mSimpleIslandManager (NULL), mDynamicsContext (NULL), mMemoryManager (NULL), #if PX_SUPPORT_GPU_PHYSX mGpuWranglerManagers (NULL), mHeapMemoryAllocationManager (NULL), #endif mSimulationController (NULL), mSimulationControllerCallback (NULL), mGravity (PxVec3(0.0f)), mDt (0), mOneOverDt (0), mTimeStamp (1), // PT: has to start to 1 to fix determinism bug. I don't know why yet but it works. mReportShapePairTimeStamp (0), mTriggerBufferAPI ("sceneTriggerBufferAPI"), mArticulations ("sceneArticulations"), mBrokenConstraints ("sceneBrokenConstraints"), mActiveBreakableConstraints ("sceneActiveBreakableConstraints"), mMemBlock128Pool ("PxsContext ConstraintBlock128Pool"), mMemBlock256Pool ("PxsContext ConstraintBlock256Pool"), mMemBlock384Pool ("PxsContext ConstraintBlock384Pool"), mNPhaseCore (NULL), mKineKineFilteringMode (desc.kineKineFilteringMode), mStaticKineFilteringMode (desc.staticKineFilteringMode), mSleepBodies ("sceneSleepBodies"), mWokeBodies ("sceneWokeBodies"), mEnableStabilization (desc.flags & PxSceneFlag::eENABLE_STABILIZATION), mActiveActors ("clientActiveActors"), mFrozenActors ("clientFrozenActors"), mClientPosePreviewBodies ("clientPosePreviewBodies"), mClientPosePreviewBuffer ("clientPosePreviewBuffer"), mSimulationEventCallback (NULL), mInternalFlags (SceneInternalFlag::eSCENE_DEFAULT), mPublicFlags (desc.flags), mAnchorCore (PxTransform(PxIdentity)), mStaticAnchor (NULL), mBatchRemoveState (NULL), mLostTouchPairs ("sceneLostTouchPairs"), mVisualizationParameterChanged (false), mMaxNbArticulationLinks (0), mNbRigidStatics (0), mNbRigidDynamics (0), mNbRigidKinematic (0), mSecondPassNarrowPhase (contextID, this, "ScScene.secondPassNarrowPhase"), mPostNarrowPhase (contextID, this, "ScScene.postNarrowPhase"), mFinalizationPhase (contextID, this, "ScScene.finalizationPhase"), mUpdateCCDMultiPass (contextID, this, "ScScene.updateCCDMultiPass"), mAfterIntegration (contextID, this, "ScScene.afterIntegration"), mPostSolver (contextID, this, "ScScene.postSolver"), mSolver (contextID, this, "ScScene.rigidBodySolver"), mUpdateBodies (contextID, this, "ScScene.updateBodies"), mUpdateShapes (contextID, this, "ScScene.updateShapes"), mUpdateSimulationController (contextID, this, "ScScene.updateSimulationController"), mUpdateDynamics (contextID, this, "ScScene.updateDynamics"), mProcessLostContactsTask (contextID, this, "ScScene.processLostContact"), mProcessLostContactsTask2 (contextID, this, "ScScene.processLostContact2"), mProcessLostContactsTask3 (contextID, this, "ScScene.processLostContact3"), mDestroyManagersTask (contextID, this, "ScScene.destroyManagers"), mLostTouchReportsTask (contextID, this, "ScScene.lostTouchReports"), mUnregisterInteractionsTask (contextID, this, "ScScene.unregisterInteractions"), mProcessNarrowPhaseLostTouchTasks(contextID, this, "ScScene.processNpLostTouchTask"), mProcessNPLostTouchEvents (contextID, this, "ScScene.processNPLostTouchEvents"), mPostThirdPassIslandGenTask (contextID, this, "ScScene.postThirdPassIslandGenTask"), mPostIslandGen (contextID, this, "ScScene.postIslandGen"), mIslandGen (contextID, this, "ScScene.islandGen"), mPreRigidBodyNarrowPhase (contextID, this, "ScScene.preRigidBodyNarrowPhase"), mSetEdgesConnectedTask (contextID, this, "ScScene.setEdgesConnectedTask"), mProcessLostPatchesTask (contextID, this, "ScScene.processLostSolverPatchesTask"), mProcessFoundPatchesTask (contextID, this, "ScScene.processFoundSolverPatchesTask"), mUpdateBoundAndShapeTask (contextID, this, "ScScene.updateBoundsAndShapesTask"), mRigidBodyNarrowPhase (contextID, this, "ScScene.rigidBodyNarrowPhase"), mRigidBodyNPhaseUnlock (contextID, this, "ScScene.unblockNarrowPhase"), mPostBroadPhase (contextID, this, "ScScene.postBroadPhase"), mPostBroadPhaseCont (contextID, this, "ScScene.postBroadPhaseCont"), mPostBroadPhase2 (contextID, this, "ScScene.postBroadPhase2"), mPostBroadPhase3 (contextID, this, "ScScene.postBroadPhase3"), mPreallocateContactManagers (contextID, this, "ScScene.preallocateContactManagers"), mIslandInsertion (contextID, this, "ScScene.islandInsertion"), mRegisterContactManagers (contextID, this, "ScScene.registerContactManagers"), mRegisterInteractions (contextID, this, "ScScene.registerInteractions"), mRegisterSceneInteractions (contextID, this, "ScScene.registerSceneInteractions"), mBroadPhase (contextID, this, "ScScene.broadPhase"), mAdvanceStep (contextID, this, "ScScene.advanceStep"), mCollideStep (contextID, this, "ScScene.collideStep"), mBpFirstPass (contextID, this, "ScScene.broadPhaseFirstPass"), mBpSecondPass (contextID, this, "ScScene.broadPhaseSecondPass"), mBpUpdate (contextID, this, "ScScene.updateBroadPhase"), mPreIntegrate (contextID, this, "ScScene.preIntegrate"), mTaskPool (16384), mTaskManager (NULL), mCudaContextManager (desc.cudaContextManager), mContactReportsNeedPostSolverVelocity(false), mUseGpuDynamics(false), mUseGpuBp (false), mCCDBp (false), mSimulationStage (SimulationStage::eCOMPLETE), mPosePreviewBodies ("scenePosePreviewBodies"), mOverlapFilterTaskHead (NULL), mIsCollisionPhaseActive (false), mIsDirectGPUAPIInitialized (false), mOnSleepingStateChanged (NULL) #if PX_SUPPORT_GPU_PHYSX ,mSoftBodies ("sceneSoftBodies"), mFEMCloths ("sceneFEMCloths"), mParticleSystems ("sceneParticleSystems"), mHairSystems ("sceneHairSystems") #endif { #if PX_SUPPORT_GPU_PHYSX mLLSoftBodyPool = PX_NEW(LLSoftBodyPool); mLLFEMClothPool = PX_NEW(LLFEMClothPool); mLLParticleSystemPool = PX_NEW(LLParticleSystemPool); mLLHairSystemPool = PX_NEW(LLHairSystemPool); mWokeSoftBodyListValid = true; mSleepSoftBodyListValid = true; mWokeHairSystemListValid = true; mSleepHairSystemListValid = true; #endif for(PxU32 type = 0; type < InteractionType::eTRACKED_IN_SCENE_COUNT; ++type) mInteractions[type].reserve(64); for (int i=0; i < InteractionType::eTRACKED_IN_SCENE_COUNT; ++i) mActiveInteractionCount[i] = 0; mStats = PX_NEW(SimStats); mConstraintIDTracker = PX_NEW(ObjectIDTracker); mActorIDTracker = PX_NEW(ObjectIDTracker); mElementIDPool = PX_NEW(ObjectIDTracker); mTriggerBufferExtraData = reinterpret_cast<TriggerBufferExtraData*>(PX_ALLOC(sizeof(TriggerBufferExtraData), "ScScene::TriggerBufferExtraData")); PX_PLACEMENT_NEW(mTriggerBufferExtraData, TriggerBufferExtraData("ScScene::TriggerPairExtraData")); mStaticSimPool = PX_NEW(PreallocatingPool<StaticSim>)(64, "StaticSim"); mBodySimPool = PX_NEW(PreallocatingPool<BodySim>)(64, "BodySim"); mShapeSimPool = PX_NEW(PreallocatingPool<ShapeSim>)(64, "ShapeSim"); mConstraintSimPool = PX_NEW(PxPool<ConstraintSim>)("ScScene::ConstraintSim"); mConstraintInteractionPool = PX_NEW(PxPool<ConstraintInteraction>)("ScScene::ConstraintInteraction"); mLLArticulationRCPool = PX_NEW(LLArticulationRCPool); mSimStateDataPool = PX_NEW(PxPool<SimStateData>)("ScScene::SimStateData"); mSqBoundsManager = PX_NEW(SqBoundsManager); mTaskManager = physx::PxTaskManager::createTaskManager(*PxGetErrorCallback(), desc.cpuDispatcher); for(PxU32 i=0; i<PxGeometryType::eGEOMETRY_COUNT; i++) mNbGeometries[i] = 0; bool useGpuDynamics = false; bool useGpuBroadphase = false; #if PX_SUPPORT_GPU_PHYSX if(desc.flags & PxSceneFlag::eENABLE_GPU_DYNAMICS) { if(!mCudaContextManager) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "GPU solver pipeline failed, switching to software"); else if(mCudaContextManager->supportsArchSM30()) useGpuDynamics = true; } if(desc.broadPhaseType == PxBroadPhaseType::eGPU) { if(!mCudaContextManager) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "GPU Bp pipeline failed, switching to software"); else if(mCudaContextManager->supportsArchSM30()) useGpuBroadphase = true; } #endif mUseGpuDynamics = useGpuDynamics; mUseGpuBp = useGpuBroadphase; mLLContext = PX_NEW(PxsContext)(desc, mTaskManager, mTaskPool, mCudaContextManager, desc.contactPairSlabSize, contextID); if (mLLContext == 0) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Failed to create context!"); return; } mLLContext->setMaterialManager(&getMaterialManager()); #if PX_SUPPORT_GPU_PHYSX if (useGpuBroadphase || useGpuDynamics) { PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); // PT: this creates a PxgMemoryManager, whose host memory allocator is a PxgCudaHostMemoryAllocatorCallback mMemoryManager = physxGpu->createGpuMemoryManager(mLLContext->getCudaContextManager()); mGpuWranglerManagers = physxGpu->getGpuKernelWranglerManager(mLLContext->getCudaContextManager()); // PT: this creates a PxgHeapMemoryAllocatorManager mHeapMemoryAllocationManager = physxGpu->createGpuHeapMemoryAllocatorManager(desc.gpuDynamicsConfig.heapCapacity, mMemoryManager, desc.gpuComputeVersion); } else #endif { // PT: this creates a PxsDefaultMemoryManager mMemoryManager = createDefaultMemoryManager(); } Bp::BroadPhase* broadPhase = NULL; //Note: broadphase should be independent of AABBManager. MBP uses it to call getBPBounds but it has //already been passed all bounds in BroadPhase::update() so should use that instead. // PT: above comment is obsolete: MBP now doesn't call getBPBounds anymore (except in commented out code) // and it is instead the GPU broadphase which is not independent from the GPU AABB manager....... if(!useGpuBroadphase) { PxBroadPhaseType::Enum broadPhaseType = desc.broadPhaseType; if (broadPhaseType == PxBroadPhaseType::eGPU) broadPhaseType = PxBroadPhaseType::eABP; broadPhase = Bp::BroadPhase::create( broadPhaseType, desc.limits.maxNbRegions, desc.limits.maxNbBroadPhaseOverlaps, desc.limits.maxNbStaticShapes, desc.limits.maxNbDynamicShapes, contextID); } #if PX_SUPPORT_GPU_PHYSX else { broadPhase = PxvGetPhysXGpu(true)->createGpuBroadPhase( mGpuWranglerManagers, mLLContext->getCudaContextManager(), desc.gpuComputeVersion, desc.gpuDynamicsConfig, mHeapMemoryAllocationManager, contextID); } #endif //create allocator PxVirtualAllocatorCallback* allocatorCallback = mMemoryManager->getHostMemoryAllocator(); PxVirtualAllocator allocator(allocatorCallback); mBoundsArray = PX_NEW(Bp::BoundsArray)(allocator); mContactDistance = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(PxFloatArrayPinned), "ContactDistance"), PxFloatArrayPinned)(allocator); mHasContactDistanceChanged = false; const bool useEnhancedDeterminism = mPublicFlags & PxSceneFlag::eENABLE_ENHANCED_DETERMINISM; mSimpleIslandManager = PX_NEW(IG::SimpleIslandManager)(useEnhancedDeterminism, contextID); PxvNphaseImplementationContextUsableAsFallback* cpuNphaseImplementation = createNphaseImplementationContext(*mLLContext, &mSimpleIslandManager->getAccurateIslandSim(), allocatorCallback, useGpuDynamics); if (!useGpuDynamics) { if (desc.solverType == PxSolverType::ePGS) { mDynamicsContext = createDynamicsContext (&mLLContext->getNpMemBlockPool(), mLLContext->getScratchAllocator(), mLLContext->getTaskPool(), mLLContext->getSimStats(), &mLLContext->getTaskManager(), allocatorCallback, &getMaterialManager(), mSimpleIslandManager, contextID, mEnableStabilization, useEnhancedDeterminism, desc.maxBiasCoefficient, !!(desc.flags & PxSceneFlag::eENABLE_FRICTION_EVERY_ITERATION), desc.getTolerancesScale().length); } else { mDynamicsContext = createTGSDynamicsContext (&mLLContext->getNpMemBlockPool(), mLLContext->getScratchAllocator(), mLLContext->getTaskPool(), mLLContext->getSimStats(), &mLLContext->getTaskManager(), allocatorCallback, &getMaterialManager(), mSimpleIslandManager, contextID, mEnableStabilization, useEnhancedDeterminism, desc.getTolerancesScale().length); } mLLContext->setNphaseImplementationContext(cpuNphaseImplementation); mSimulationControllerCallback = PX_NEW(ScSimulationControllerCallback)(this); mSimulationController = PX_NEW(SimulationController)(mSimulationControllerCallback); if (!useGpuBroadphase) mAABBManager = createAABBManagerCPU(desc, broadPhase, mBoundsArray, mContactDistance, allocator, contextID); #if PX_SUPPORT_GPU_PHYSX else mAABBManager = createAABBManagerGPU(mGpuWranglerManagers, mLLContext->getCudaContextManager(), mHeapMemoryAllocationManager, desc, broadPhase, mBoundsArray, mContactDistance, allocator, contextID); #endif } else { #if PX_SUPPORT_GPU_PHYSX bool directAPI = mPublicFlags & PxSceneFlag::eENABLE_DIRECT_GPU_API; mDynamicsContext = PxvGetPhysXGpu(true)->createGpuDynamicsContext(mLLContext->getTaskPool(), mGpuWranglerManagers, mLLContext->getCudaContextManager(), desc.gpuDynamicsConfig, mSimpleIslandManager, desc.gpuMaxNumPartitions, desc.gpuMaxNumStaticPartitions, mEnableStabilization, useEnhancedDeterminism, desc.maxBiasCoefficient, desc.gpuComputeVersion, mLLContext->getSimStats(), mHeapMemoryAllocationManager, !!(desc.flags & PxSceneFlag::eENABLE_FRICTION_EVERY_ITERATION), desc.solverType, desc.getTolerancesScale().length, directAPI); void* contactStreamBase = NULL; void* patchStreamBase = NULL; void* forceAndIndiceStreamBase = NULL; mDynamicsContext->getDataStreamBase(contactStreamBase, patchStreamBase, forceAndIndiceStreamBase); mLLContext->setNphaseFallbackImplementationContext(cpuNphaseImplementation); PxvNphaseImplementationContext* gpuNphaseImplementation = PxvGetPhysXGpu(true)->createGpuNphaseImplementationContext(*mLLContext, mGpuWranglerManagers, cpuNphaseImplementation, desc.gpuDynamicsConfig, contactStreamBase, patchStreamBase, forceAndIndiceStreamBase, getBoundsArray().getBounds(), &mSimpleIslandManager->getAccurateIslandSim(), mDynamicsContext, desc.gpuComputeVersion, mHeapMemoryAllocationManager, useGpuBroadphase); mSimulationControllerCallback = PX_NEW(PxgSimulationControllerCallback)(this); mSimulationController = PxvGetPhysXGpu(true)->createGpuSimulationController(mGpuWranglerManagers, mLLContext->getCudaContextManager(), mDynamicsContext, gpuNphaseImplementation, broadPhase, useGpuBroadphase, mSimpleIslandManager, mSimulationControllerCallback, desc.gpuComputeVersion, mHeapMemoryAllocationManager, desc.gpuDynamicsConfig.maxSoftBodyContacts, desc.gpuDynamicsConfig.maxFemClothContacts, desc.gpuDynamicsConfig.maxParticleContacts, desc.gpuDynamicsConfig.maxHairContacts); mSimulationController->setBounds(mBoundsArray); mDynamicsContext->setSimulationController(mSimulationController); mLLContext->setNphaseImplementationContext(gpuNphaseImplementation); mLLContext->mContactStreamPool = &mDynamicsContext->getContactStreamPool(); mLLContext->mPatchStreamPool = &mDynamicsContext->getPatchStreamPool(); mLLContext->mForceAndIndiceStreamPool = &mDynamicsContext->getForceStreamPool(); // PT: TODO: what's the difference between this allocator and "allocator" above? PxVirtualAllocator tAllocator(mHeapMemoryAllocationManager->mMappedMemoryAllocators, PxsHeapStats::eBROADPHASE); if (!useGpuBroadphase) // PT: TODO: we're using a CUDA allocator in the CPU broadphase, and a different allocator for the bounds array? mAABBManager = createAABBManagerCPU(desc, broadPhase, mBoundsArray, mContactDistance, tAllocator, contextID); else mAABBManager = createAABBManagerGPU(mGpuWranglerManagers, mLLContext->getCudaContextManager(), mHeapMemoryAllocationManager, desc, broadPhase, mBoundsArray, mContactDistance, tAllocator, contextID); #endif } //Construct the bitmap of updated actors required as input to the broadphase update if(desc.limits.maxNbBodies) { // PT: TODO: revisit this. Why do we handle the added/removed and updated bitmaps entirely differently, in different places? And what is this weird formula here? mAABBManager->getChangedAABBMgActorHandleMap().resize((2*desc.limits.maxNbBodies + 256) & ~255); } //mLLContext->createTransformCache(mDynamicsContext->getAllocatorCallback()); mLLContext->createTransformCache(*allocatorCallback); mLLContext->setContactDistance(mContactDistance); mCCDContext = PX_NEW(PxsCCDContext)(mLLContext, mDynamicsContext->getThresholdStream(), *mLLContext->getNphaseImplementationContext(), desc.ccdThreshold); setSolverBatchSize(desc.solverBatchSize); setSolverArticBatchSize(desc.solverArticulationBatchSize); mDynamicsContext->setFrictionOffsetThreshold(desc.frictionOffsetThreshold); mDynamicsContext->setCCDSeparationThreshold(desc.ccdMaxSeparation); mDynamicsContext->setCorrelationDistance(desc.frictionCorrelationDistance); const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); mLLContext->setMeshContactMargin(0.01f * scale.length); mLLContext->setToleranceLength(scale.length); // the original descriptor uses // bounce iff impact velocity > threshold // but LL use // bounce iff separation velocity < -threshold // hence we negate here. mDynamicsContext->setBounceThreshold(-desc.bounceThresholdVelocity); mStaticAnchor = mStaticSimPool->construct(*this, mAnchorCore); mNPhaseCore = PX_NEW(NPhaseCore)(*this, desc); // Init dominance matrix { //init all dominance pairs such that: //if g1 == g2, then (1.0f, 1.0f) is returned //if g1 < g2, then (0.0f, 1.0f) is returned //if g1 > g2, then (1.0f, 0.0f) is returned PxU32 mask = ~PxU32(1); for (unsigned i = 0; i < PX_MAX_DOMINANCE_GROUP; ++i, mask <<= 1) mDominanceBitMatrix[i] = ~mask; } // DeterminismDebugger::begin(); mWokeBodyListValid = true; mSleepBodyListValid = true; //load from desc: setLimits(desc.limits); // Create broad phase mBroadphaseManager.setBroadPhaseCallback(desc.broadPhaseCallback); setGravity(desc.gravity); setFrictionType(desc.frictionType); setPCM(desc.flags & PxSceneFlag::eENABLE_PCM); setContactCache(!(desc.flags & PxSceneFlag::eDISABLE_CONTACT_CACHE)); setSimulationEventCallback(desc.simulationEventCallback); setContactModifyCallback(desc.contactModifyCallback); setCCDContactModifyCallback(desc.ccdContactModifyCallback); setCCDMaxPasses(desc.ccdMaxPasses); PX_ASSERT(mNPhaseCore); // refactor paranoia PX_ASSERT( ((desc.filterShaderData) && (desc.filterShaderDataSize > 0)) || (!(desc.filterShaderData) && (desc.filterShaderDataSize == 0)) ); if (desc.filterShaderData) { mFilterShaderData = PX_ALLOC(desc.filterShaderDataSize, sFilterShaderDataMemAllocId); PxMemCopy(mFilterShaderData, desc.filterShaderData, desc.filterShaderDataSize); mFilterShaderDataSize = desc.filterShaderDataSize; mFilterShaderDataCapacity = desc.filterShaderDataSize; } else { mFilterShaderData = NULL; mFilterShaderDataSize = 0; mFilterShaderDataCapacity = 0; } mFilterShader = desc.filterShader; mFilterCallback = desc.filterCallback; } void Sc::Scene::release() { // TODO: PT: check virtual stuff mTimeStamp++; //collisionSpace.purgeAllPairs(); //purgePairs(); //releaseTagData(); // We know release all the shapes before the collision space //collisionSpace.deleteAllShapes(); //collisionSpace.release(); //DeterminismDebugger::end(); PX_FREE(mActiveKinematicsCopy); PX_DELETE(mNPhaseCore); PX_FREE(mFilterShaderData); if(mStaticAnchor) mStaticSimPool->destroy(mStaticAnchor); // Free object IDs and the deleted object id map postReportsCleanup(); //before the task manager if (mLLContext) { if(mLLContext->getNphaseFallbackImplementationContext()) { mLLContext->getNphaseFallbackImplementationContext()->destroy(); mLLContext->setNphaseFallbackImplementationContext(NULL); } if(mLLContext->getNphaseImplementationContext()) { mLLContext->getNphaseImplementationContext()->destroy(); mLLContext->setNphaseImplementationContext(NULL); } } PX_DELETE(mSqBoundsManager); PX_DELETE(mBoundsArray); PX_DELETE(mConstraintInteractionPool); PX_DELETE(mConstraintSimPool); PX_DELETE(mSimStateDataPool); PX_DELETE(mStaticSimPool); PX_DELETE(mShapeSimPool); PX_DELETE(mBodySimPool); PX_DELETE(mLLArticulationRCPool); #if PX_SUPPORT_GPU_PHYSX gpu_releasePools(); #endif mTriggerBufferExtraData->~TriggerBufferExtraData(); PX_FREE(mTriggerBufferExtraData); PX_DELETE(mElementIDPool); PX_DELETE(mActorIDTracker); PX_DELETE(mConstraintIDTracker); PX_DELETE(mStats); Bp::BroadPhase* broadPhase = mAABBManager->getBroadPhase(); mAABBManager->destroy(); PX_RELEASE(broadPhase); PX_DELETE(mSimulationControllerCallback); PX_DELETE(mSimulationController); mDynamicsContext->destroy(); PX_DELETE(mCCDContext); PX_DELETE(mSimpleIslandManager); #if PX_SUPPORT_GPU_PHYSX gpu_release(); #endif PX_RELEASE(mTaskManager); PX_DELETE(mLLContext); mContactDistance->~PxArray(); PX_FREE(mContactDistance); PX_DELETE(mMemoryManager); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::preAllocate(PxU32 nbStatics, PxU32 nbBodies, PxU32 nbStaticShapes, PxU32 nbDynamicShapes) { // PT: TODO: this is only used for my addActors benchmark for now. Pre-allocate more arrays here. mActiveBodies.reserve(PxMax<PxU32>(64,nbBodies)); mStaticSimPool->preAllocate(nbStatics); mBodySimPool->preAllocate(nbBodies); mShapeSimPool->preAllocate(nbStaticShapes + nbDynamicShapes); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::addDirtyArticulationSim(Sc::ArticulationSim* artiSim) { artiSim->setDirtyFlag(ArticulationSimDirtyFlag::eUPDATE); mDirtyArticulationSims.insert(artiSim); } void Sc::Scene::removeDirtyArticulationSim(Sc::ArticulationSim* artiSim) { artiSim->setDirtyFlag(ArticulationSimDirtyFlag::eNONE); mDirtyArticulationSims.erase(artiSim); } void Sc::Scene::addToActiveList(ActorSim& actorSim) { PX_ASSERT(actorSim.getActiveListIndex() >= SC_NOT_IN_ACTIVE_LIST_INDEX); ActorCore* appendedActorCore = &actorSim.getActorCore(); if (actorSim.isDynamicRigid()) { // Sort: kinematic before dynamic const PxU32 size = mActiveBodies.size(); PxU32 incomingBodyActiveListIndex = size; // PT: by default we append the incoming body at the end of the current array. BodySim& bodySim = static_cast<BodySim&>(actorSim); if (bodySim.isKinematic()) // PT: Except if incoming body is kinematic, in which case: { const PxU32 nbKinematics = mActiveKinematicBodyCount++; // PT: - we increase their number if (nbKinematics != size) // PT: - if there's at least one dynamic in the array... { PX_ASSERT(appendedActorCore != mActiveBodies[nbKinematics]); appendedActorCore = mActiveBodies[nbKinematics]; // PT: ...then we grab the first dynamic after the kinematics... appendedActorCore->getSim()->setActiveListIndex(size); // PT: ...and we move that one back to the end of the array... mActiveBodies[nbKinematics] = static_cast<BodyCore*>(&actorSim.getActorCore()); // PT: ...while the incoming kine replaces the dynamic we moved out. incomingBodyActiveListIndex = nbKinematics; // PT: ...thus the incoming kine's index is the prev #kines. } } // for active compound rigids add to separate array, so we dont have to traverse all active actors if (bodySim.readInternalFlag(BodySim::BF_IS_COMPOUND_RIGID)) { PX_ASSERT(actorSim.getActiveCompoundListIndex() >= SC_NOT_IN_ACTIVE_LIST_INDEX); const PxU32 compoundIndex = mActiveCompoundBodies.size(); mActiveCompoundBodies.pushBack(static_cast<BodyCore*>(appendedActorCore)); actorSim.setActiveCompoundListIndex(compoundIndex); } actorSim.setActiveListIndex(incomingBodyActiveListIndex); // PT: will be 'size' or 'nbKinematics', 'dynamicIndex' mActiveBodies.pushBack(static_cast<BodyCore*>(appendedActorCore)); // PT: will be the incoming object or the first dynamic we moved out. } #if PX_SUPPORT_GPU_PHYSX else gpu_addToActiveList(actorSim, appendedActorCore); #endif } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void removeFromActiveCompoundBodyList(Sc::ActorSim& actorSim, PxArray<Sc::BodyCore*>& activeCompoundBodies) { const PxU32 removedCompoundIndex = actorSim.getActiveCompoundListIndex(); PX_ASSERT(removedCompoundIndex < SC_NOT_IN_ACTIVE_LIST_INDEX); actorSim.setActiveCompoundListIndex(SC_NOT_IN_ACTIVE_LIST_INDEX); const PxU32 newCompoundSize = activeCompoundBodies.size() - 1; if(removedCompoundIndex != newCompoundSize) { Sc::BodyCore* lastBody = activeCompoundBodies[newCompoundSize]; activeCompoundBodies[removedCompoundIndex] = lastBody; lastBody->getSim()->setActiveCompoundListIndex(removedCompoundIndex); } activeCompoundBodies.forceSize_Unsafe(newCompoundSize); } void Sc::Scene::removeFromActiveCompoundBodyList(BodySim& body) { ::removeFromActiveCompoundBodyList(body, mActiveCompoundBodies); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::removeFromActiveList(ActorSim& actorSim) { PxU32 removedActiveIndex = actorSim.getActiveListIndex(); PX_ASSERT(removedActiveIndex < SC_NOT_IN_ACTIVE_LIST_INDEX); actorSim.setActiveListIndex(SC_NOT_IN_ACTIVE_LIST_INDEX); if (actorSim.isDynamicRigid()) { PX_ASSERT(mActiveBodies[removedActiveIndex] == &actorSim.getActorCore()); const PxU32 newSize = mActiveBodies.size() - 1; BodySim& bodySim = static_cast<BodySim&>(actorSim); // Sort: kinematic before dynamic, if (removedActiveIndex < mActiveKinematicBodyCount) // PT: same as 'body.isKinematic()' but without accessing the Core data { PX_ASSERT(mActiveKinematicBodyCount); PX_ASSERT(bodySim.isKinematic()); const PxU32 swapIndex = --mActiveKinematicBodyCount; if (newSize != swapIndex // PT: equal if the array only contains kinematics && removedActiveIndex < swapIndex) // PT: i.e. "if we don't remove the last kinematic" { BodyCore* swapBody = mActiveBodies[swapIndex]; swapBody->getSim()->setActiveListIndex(removedActiveIndex); mActiveBodies[removedActiveIndex] = swapBody; removedActiveIndex = swapIndex; } } // for active compound rigids add to separate array, so we dont have to traverse all active actors // A.B. TODO we should handle kinematic switch, no need to hold kinematic rigids in compound list if(bodySim.readInternalFlag(BodySim::BF_IS_COMPOUND_RIGID)) ::removeFromActiveCompoundBodyList(actorSim, mActiveCompoundBodies); if (removedActiveIndex != newSize) { Sc::BodyCore* lastBody = mActiveBodies[newSize]; mActiveBodies[removedActiveIndex] = lastBody; lastBody->getSim()->setActiveListIndex(removedActiveIndex); } mActiveBodies.forceSize_Unsafe(newSize); } #if PX_SUPPORT_GPU_PHYSX else gpu_removeFromActiveList(actorSim, removedActiveIndex); #endif } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::swapInActiveBodyList(BodySim& body) { PX_ASSERT(!body.isStaticRigid() && !body.isSoftBody() && !body.isFEMCloth() && !body.isParticleSystem() && !body.isHairSystem()); const PxU32 activeListIndex = body.getActiveListIndex(); PX_ASSERT(activeListIndex < SC_NOT_IN_ACTIVE_LIST_INDEX); PxU32 swapIndex; PxU32 newActiveKinematicBodyCount; if(activeListIndex < mActiveKinematicBodyCount) { // kinematic -> dynamic PX_ASSERT(!body.isKinematic()); // the corresponding flag gets switched before this call PX_ASSERT(mActiveKinematicBodyCount > 0); // there has to be at least one kinematic body swapIndex = mActiveKinematicBodyCount - 1; newActiveKinematicBodyCount = swapIndex; } else { // dynamic -> kinematic PX_ASSERT(body.isKinematic()); // the corresponding flag gets switched before this call PX_ASSERT(mActiveKinematicBodyCount < mActiveBodies.size()); // there has to be at least one dynamic body swapIndex = mActiveKinematicBodyCount; newActiveKinematicBodyCount = swapIndex + 1; } BodyCore*& swapBodyRef = mActiveBodies[swapIndex]; body.setActiveListIndex(swapIndex); BodyCore* swapBody = swapBodyRef; swapBodyRef = &body.getBodyCore(); swapBody->getSim()->setActiveListIndex(activeListIndex); mActiveBodies[activeListIndex] = swapBody; mActiveKinematicBodyCount = newActiveKinematicBodyCount; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::registerInteraction(ElementSimInteraction* interaction, bool active) { const InteractionType::Enum type = interaction->getType(); const PxU32 sceneArrayIndex = mInteractions[type].size(); interaction->setInteractionId(sceneArrayIndex); mInteractions[type].pushBack(interaction); if (active) { if (sceneArrayIndex > mActiveInteractionCount[type]) swapInteractionArrayIndices(sceneArrayIndex, mActiveInteractionCount[type], type); mActiveInteractionCount[type]++; } mNPhaseCore->registerInteraction(interaction); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::unregisterInteraction(ElementSimInteraction* interaction) { const InteractionType::Enum type = interaction->getType(); const PxU32 sceneArrayIndex = interaction->getInteractionId(); PX_ASSERT(sceneArrayIndex != PX_INVALID_INTERACTION_SCENE_ID); // if(sceneArrayIndex==PX_INVALID_INTERACTION_SCENE_ID) // return; mInteractions[type].replaceWithLast(sceneArrayIndex); interaction->setInteractionId(PX_INVALID_INTERACTION_SCENE_ID); if (sceneArrayIndex<mInteractions[type].size()) // The removed interaction was the last one, do not reset its sceneArrayIndex mInteractions[type][sceneArrayIndex]->setInteractionId(sceneArrayIndex); if (sceneArrayIndex<mActiveInteractionCount[type]) { mActiveInteractionCount[type]--; if (mActiveInteractionCount[type]<mInteractions[type].size()) swapInteractionArrayIndices(sceneArrayIndex, mActiveInteractionCount[type], type); } mNPhaseCore->unregisterInteraction(interaction); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::swapInteractionArrayIndices(PxU32 id1, PxU32 id2, InteractionType::Enum type) { PxArray<ElementSimInteraction*>& interArray = mInteractions[type]; ElementSimInteraction* interaction1 = interArray[id1]; ElementSimInteraction* interaction2 = interArray[id2]; interArray[id1] = interaction2; interArray[id2] = interaction1; interaction1->setInteractionId(id2); interaction2->setInteractionId(id1); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::notifyInteractionActivated(Interaction* interaction) { PX_ASSERT((interaction->getType() == InteractionType::eOVERLAP) || (interaction->getType() == InteractionType::eTRIGGER)); PX_ASSERT(interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)); PX_ASSERT(interaction->getInteractionId() != PX_INVALID_INTERACTION_SCENE_ID); const InteractionType::Enum type = interaction->getType(); PX_ASSERT(interaction->getInteractionId() >= mActiveInteractionCount[type]); if (mActiveInteractionCount[type] < mInteractions[type].size()) swapInteractionArrayIndices(mActiveInteractionCount[type], interaction->getInteractionId(), type); mActiveInteractionCount[type]++; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::notifyInteractionDeactivated(Interaction* interaction) { PX_ASSERT((interaction->getType() == InteractionType::eOVERLAP) || (interaction->getType() == InteractionType::eTRIGGER)); PX_ASSERT(!interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)); PX_ASSERT(interaction->getInteractionId() != PX_INVALID_INTERACTION_SCENE_ID); const InteractionType::Enum type = interaction->getType(); PX_ASSERT(interaction->getInteractionId() < mActiveInteractionCount[type]); if (mActiveInteractionCount[type] > 1) swapInteractionArrayIndices(mActiveInteractionCount[type]-1, interaction->getInteractionId(), type); mActiveInteractionCount[type]--; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void** Sc::Scene::allocatePointerBlock(PxU32 size) { PX_ASSERT(size>32 || size == 32 || size == 16 || size == 8); void* ptr; if(size==8) ptr = mPointerBlock8Pool.construct(); else if(size == 16) ptr = mPointerBlock16Pool.construct(); else if(size == 32) ptr = mPointerBlock32Pool.construct(); else ptr = PX_ALLOC(size * sizeof(void*), "void*"); return reinterpret_cast<void**>(ptr); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::deallocatePointerBlock(void** block, PxU32 size) { PX_ASSERT(size>32 || size == 32 || size == 16 || size == 8); if(size==8) mPointerBlock8Pool.destroy(reinterpret_cast<PointerBlock8*>(block)); else if(size == 16) mPointerBlock16Pool.destroy(reinterpret_cast<PointerBlock16*>(block)); else if(size == 32) mPointerBlock32Pool.destroy(reinterpret_cast<PointerBlock32*>(block)); else PX_FREE(block); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::setFilterShaderData(const void* data, PxU32 dataSize) { PX_UNUSED(sFilterShaderDataMemAllocId); if (data) { PX_ASSERT(dataSize > 0); void* buffer; if (dataSize <= mFilterShaderDataCapacity) buffer = mFilterShaderData; else { buffer = PX_ALLOC(dataSize, sFilterShaderDataMemAllocId); if (buffer) { mFilterShaderDataCapacity = dataSize; PX_FREE(mFilterShaderData); } else { outputError<PxErrorCode::eOUT_OF_MEMORY>(__LINE__, "Failed to allocate memory for filter shader data!"); return; } } PxMemCopy(buffer, data, dataSize); mFilterShaderData = buffer; mFilterShaderDataSize = dataSize; } else { PX_ASSERT(dataSize == 0); PX_FREE(mFilterShaderData); mFilterShaderDataSize = 0; mFilterShaderDataCapacity = 0; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //stepSetup is called in solve, but not collide void Sc::Scene::stepSetupSolve(PxBaseTask* continuation) { PX_PROFILE_ZONE("Sim.stepSetupSolve", mContextId); kinematicsSetup(continuation); } void Sc::Scene::advance(PxReal timeStep, PxBaseTask* continuation) { if(timeStep != 0.0f) { setElapsedTime(timeStep); mAdvanceStep.setContinuation(continuation); stepSetupSolve(&mAdvanceStep); mAdvanceStep.removeReference(); } } void Sc::Scene::collide(PxReal timeStep, PxBaseTask* continuation) { mDt = timeStep; stepSetupCollide(continuation); mLLContext->beginUpdate(); mCollideStep.setContinuation(continuation); mCollideStep.removeReference(); } void Sc::Scene::endSimulation() { // Handle user contact filtering // Note: Do this before the contact callbacks get fired since the filter callback might // trigger contact reports (touch lost due to re-filtering) mBroadphaseManager.prepareOutOfBoundsCallbacks(mAABBManager); PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); mNPhaseCore->fireCustomFilteringCallbacks(outputs); mNPhaseCore->preparePersistentContactEventListForNextFrame(); mSimulationController->releaseDeferredArticulationIds(); #if PX_SUPPORT_GPU_PHYSX mSimulationController->releaseDeferredSoftBodyIds(); mSimulationController->releaseDeferredFEMClothIds(); mSimulationController->releaseDeferredParticleSystemIds(); mSimulationController->releaseDeferredHairSystemIds(); mAABBManager->releaseDeferredAggregateIds(); #endif // End step / update time stamps { mTimeStamp++; // INVALID_SLEEP_COUNTER is 0xffffffff. Therefore the last bit is masked. Look at Body::isForcedToSleep() for example. // if(timeStamp==PX_INVALID_U32) timeStamp = 0; // Reserve INVALID_ID for something else mTimeStamp &= 0x7fffffff; mReportShapePairTimeStamp++; // to make sure that deleted shapes/actors after fetchResults() create new report pairs } PxcDisplayContactCacheStats(); } void Sc::Scene::flush(bool sendPendingReports) { if (sendPendingReports) { fireQueuedContactCallbacks(); mNPhaseCore->clearContactReportStream(); mNPhaseCore->clearContactReportActorPairs(true); fireTriggerCallbacks(); } else { mNPhaseCore->clearContactReportActorPairs(true); // To clear the actor pair set } postReportsCleanup(); mNPhaseCore->freeContactReportStreamMemory(); mTriggerBufferAPI.reset(); mTriggerBufferExtraData->reset(); mBrokenConstraints.reset(); mBroadphaseManager.flush(mAABBManager); clearSleepWakeBodies(); //!!! If we send out these reports on flush then this would not be necessary mActorIDTracker->reset(); mElementIDPool->reset(); processLostTouchPairs(); // Processes the lost touch bodies PX_ASSERT(mLostTouchPairs.size() == 0); mLostTouchPairs.reset(); // Does not seem worth deleting the bitmap for the lost touch pair list mActiveBodies.shrink(); for(PxU32 i=0; i < InteractionType::eTRACKED_IN_SCENE_COUNT; i++) { mInteractions[i].shrink(); } //!!! TODO: look into retrieving memory from the NPhaseCore & Broadphase class (all the pools in there etc.) mLLContext->getNpMemBlockPool().releaseUnusedBlocks(); } // User callbacks void Sc::Scene::setSimulationEventCallback(PxSimulationEventCallback* callback) { if(!mSimulationEventCallback && callback) { // if there was no callback before, the sleeping bodies have to be prepared for potential notification events (no shortcut possible anymore) BodyCore* const* sleepingBodies = mSleepBodies.getEntries(); for (PxU32 i = 0; i < mSleepBodies.size(); i++) { sleepingBodies[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY); } #if PX_SUPPORT_GPU_PHYSX gpu_setSimulationEventCallback(callback); #endif } mSimulationEventCallback = callback; } PxSimulationEventCallback* Sc::Scene::getSimulationEventCallback() const { return mSimulationEventCallback; } void Sc::Scene::removeBody(BodySim& body) //this also notifies any connected joints! { BodyCore& core = body.getBodyCore(); // Remove from sleepBodies array mSleepBodies.erase(&core); PX_ASSERT(!mSleepBodies.contains(&core)); // Remove from wokeBodies array mWokeBodies.erase(&core); PX_ASSERT(!mWokeBodies.contains(&core)); if (body.isActive() && (core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW)) removeFromPosePreviewList(body); else PX_ASSERT(!isInPosePreviewList(body)); markReleasedBodyIDForLostTouch(body.getActorID()); } void Sc::Scene::addConstraint(ConstraintCore& constraint, RigidCore* body0, RigidCore* body1) { ConstraintSim* sim = mConstraintSimPool->construct(constraint, body0, body1, *this); PX_UNUSED(sim); PxNodeIndex nodeIndex0, nodeIndex1; ActorSim* sim0 = NULL; ActorSim* sim1 = NULL; if (body0) { sim0 = body0->getSim(); nodeIndex0 = sim0->getNodeIndex(); } if (body1) { sim1 = body1->getSim(); nodeIndex1 = sim1->getNodeIndex(); } if (nodeIndex1 < nodeIndex0) PxSwap(sim0, sim1); mConstraintMap.insert(PxPair<const Sc::ActorSim*, const Sc::ActorSim*>(sim0, sim1), &constraint); mConstraints.insert(&constraint); } void Sc::Scene::removeConstraint(ConstraintCore& constraint) { ConstraintSim* cSim = constraint.getSim(); if (cSim) { { PxNodeIndex nodeIndex0, nodeIndex1; const ConstraintInteraction* interaction = cSim->getInteraction(); Sc::ActorSim* bSim = &interaction->getActorSim0(); Sc::ActorSim* bSim1 = &interaction->getActorSim1(); if (bSim) nodeIndex0 = bSim->getNodeIndex(); if (bSim1) nodeIndex1 = bSim1->getNodeIndex(); if (nodeIndex1 < nodeIndex0) PxSwap(bSim, bSim1); mConstraintMap.erase(PxPair<const Sc::ActorSim*, const Sc::ActorSim*>(bSim, bSim1)); } mConstraintSimPool->destroy(cSim); } mConstraints.erase(&constraint); } void Sc::Scene::addArticulation(ArticulationCore& articulation, BodyCore& root) { ArticulationSim* sim = PX_NEW(ArticulationSim)(articulation, *this, root); if (sim && (sim->getLowLevelArticulation() == NULL)) { PX_DELETE(sim); return; } mArticulations.insert(&articulation); addDirtyArticulationSim(sim); } void Sc::Scene::removeArticulation(ArticulationCore& articulation) { ArticulationSim* a = articulation.getSim(); Sc::ArticulationSimDirtyFlags dirtyFlags = a->getDirtyFlag(); const bool isDirty = (dirtyFlags & Sc::ArticulationSimDirtyFlag::eUPDATE); if(isDirty) removeDirtyArticulationSim(a); PX_DELETE(a); mArticulations.erase(&articulation); } void Sc::Scene::addArticulationJoint(ArticulationJointCore& joint, BodyCore& parent, BodyCore& child) { ArticulationJointSim* sim = PX_NEW(ArticulationJointSim)(joint, *parent.getSim(), *child.getSim()); PX_UNUSED(sim); } void Sc::Scene::removeArticulationJoint(ArticulationJointCore& joint) { ArticulationJointSim* sim = joint.getSim(); PX_DELETE(sim); } void Sc::Scene::addArticulationTendon(ArticulationSpatialTendonCore& tendon) { ArticulationSpatialTendonSim* sim = PX_NEW(ArticulationSpatialTendonSim)(tendon, *this); PX_UNUSED(sim); } void Sc::Scene::removeArticulationTendon(ArticulationSpatialTendonCore& tendon) { ArticulationSpatialTendonSim* sim = tendon.getSim(); PX_DELETE(sim); } void Sc::Scene::addArticulationTendon(ArticulationFixedTendonCore& tendon) { ArticulationFixedTendonSim* sim = PX_NEW(ArticulationFixedTendonSim)(tendon, *this); PX_UNUSED(sim); } void Sc::Scene::removeArticulationTendon(ArticulationFixedTendonCore& tendon) { ArticulationFixedTendonSim* sim = tendon.getSim(); PX_DELETE(sim); } void Sc::Scene::addArticulationSensor(ArticulationSensorCore& sensor) { ArticulationSensorSim* sim = PX_NEW(ArticulationSensorSim)(sensor, *this); PX_UNUSED(sim); } void Sc::Scene::removeArticulationSensor(ArticulationSensorCore& sensor) { ArticulationSensorSim* sim = sensor.getSim(); PX_DELETE(sim); } void Sc::Scene::addArticulationSimControl(Sc::ArticulationCore& core) { Sc::ArticulationSim* sim = core.getSim(); if (sim) mSimulationController->addArticulation(sim->getLowLevelArticulation(), sim->getIslandNodeIndex()); } void Sc::Scene::removeArticulationSimControl(Sc::ArticulationCore& core) { Sc::ArticulationSim* sim = core.getSim(); if (sim) mSimulationController->releaseArticulation(sim->getLowLevelArticulation(), sim->getIslandNodeIndex()); } void* Sc::Scene::allocateConstraintBlock(PxU32 size) { if(size<=128) return mMemBlock128Pool.construct(); else if(size<=256) return mMemBlock256Pool.construct(); else if(size<=384) return mMemBlock384Pool.construct(); else return PX_ALLOC(size, "ConstraintBlock"); } void Sc::Scene::deallocateConstraintBlock(void* ptr, PxU32 size) { if(size<=128) mMemBlock128Pool.destroy(reinterpret_cast<MemBlock128*>(ptr)); else if(size<=256) mMemBlock256Pool.destroy(reinterpret_cast<MemBlock256*>(ptr)); else if(size<=384) mMemBlock384Pool.destroy(reinterpret_cast<MemBlock384*>(ptr)); else PX_FREE(ptr); } void Sc::Scene::postReportsCleanup() { mElementIDPool->processPendingReleases(); mElementIDPool->clearDeletedIDMap(); mActorIDTracker->processPendingReleases(); mActorIDTracker->clearDeletedIDMap(); mConstraintIDTracker->processPendingReleases(); mConstraintIDTracker->clearDeletedIDMap(); mSimulationController->flush(); } PX_COMPILE_TIME_ASSERT(sizeof(PxTransform32)==sizeof(PxsCachedTransform)); // PT: TODO: move this out of Sc? this is only called by Np void Sc::Scene::syncSceneQueryBounds(SqBoundsSync& sync, SqRefFinder& finder) { const PxsTransformCache& cache = mLLContext->getTransformCache(); mSqBoundsManager->syncBounds(sync, finder, mBoundsArray->begin(), reinterpret_cast<const PxTransform32*>(cache.getTransforms()), mContextId, mDirtyShapeSimMap); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::Scene::resizeReleasedBodyIDMaps(PxU32 maxActors, PxU32 numActors) { mLostTouchPairsDeletedBodyIDs.resize(maxActors); mActorIDTracker->resizeDeletedIDMap(maxActors,numActors); mElementIDPool->resizeDeletedIDMap(maxActors,numActors); } void Sc::Scene::finalizeContactStreamAndCreateHeader(PxContactPairHeader& header, const ActorPairReport& aPair, ContactStreamManager& cs, PxU32 removedShapeTestMask) { PxU8* stream = mNPhaseCore->getContactReportPairData(cs.bufferIndex); PxU32 streamManagerFlag = cs.getFlags(); ContactShapePair* contactPairs = cs.getShapePairs(stream); const PxU16 nbShapePairs = cs.currentPairCount; PX_ASSERT(nbShapePairs > 0); if (streamManagerFlag & removedShapeTestMask) { // At least one shape of this actor pair has been deleted. Need to traverse the contact buffer, // find the pairs which contain deleted shapes and set the flags accordingly. ContactStreamManager::convertDeletedShapesInContactStream(contactPairs, nbShapePairs, getElementIDPool()); } PX_ASSERT(contactPairs); ObjectIDTracker& ActorIDTracker = getActorIDTracker(); header.actors[0] = aPair.getPxActorA(); header.actors[1] = aPair.getPxActorB(); PxU16 headerFlags = 0; if (ActorIDTracker.isDeletedID(aPair.getActorAID())) headerFlags |= PxContactPairHeaderFlag::eREMOVED_ACTOR_0; if (ActorIDTracker.isDeletedID(aPair.getActorBID())) headerFlags |= PxContactPairHeaderFlag::eREMOVED_ACTOR_1; header.flags = PxContactPairHeaderFlags(headerFlags); header.pairs = reinterpret_cast<PxContactPair*>(contactPairs); header.nbPairs = nbShapePairs; PxU16 extraDataSize = cs.extraDataSize; if (!extraDataSize) header.extraDataStream = NULL; else { PX_ASSERT(extraDataSize >= sizeof(ContactStreamHeader)); extraDataSize -= sizeof(ContactStreamHeader); header.extraDataStream = stream + sizeof(ContactStreamHeader); if (streamManagerFlag & ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY) { PX_ASSERT(!(headerFlags & PxTo16(PxContactPairHeaderFlag::eREMOVED_ACTOR_0 | PxContactPairHeaderFlag::eREMOVED_ACTOR_1))); cs.setContactReportPostSolverVelocity(stream, aPair.getActorA(), aPair.getActorB()); } } header.extraDataStreamSize = extraDataSize; } const PxArray<PxContactPairHeader>& Sc::Scene::getQueuedContactPairHeaders() { const PxU32 removedShapeTestMask = PxU32(ContactStreamManagerFlag::eTEST_FOR_REMOVED_SHAPES); ActorPairReport*const* actorPairs = mNPhaseCore->getContactReportActorPairs(); PxU32 nbActorPairs = mNPhaseCore->getNbContactReportActorPairs(); mQueuedContactPairHeaders.reserve(nbActorPairs); mQueuedContactPairHeaders.clear(); for (PxU32 i = 0; i < nbActorPairs; i++) { if (i < (nbActorPairs - 1)) PxPrefetchLine(actorPairs[i + 1]); ActorPairReport* aPair = actorPairs[i]; ContactStreamManager& cs = aPair->getContactStreamManager(); if (cs.getFlags() & ContactStreamManagerFlag::eINVALID_STREAM) continue; if (i + 1 < nbActorPairs) PxPrefetch(&(actorPairs[i + 1]->getContactStreamManager())); PxContactPairHeader &pairHeader = mQueuedContactPairHeaders.insert(); finalizeContactStreamAndCreateHeader(pairHeader, *aPair, cs, removedShapeTestMask); cs.maxPairCount = cs.currentPairCount; cs.setMaxExtraDataSize(cs.extraDataSize); } return mQueuedContactPairHeaders; } /* Threading: called in the context of the user thread, but only after the physics thread has finished its run */ void Sc::Scene::fireQueuedContactCallbacks() { if(mSimulationEventCallback) { const PxU32 removedShapeTestMask = PxU32(ContactStreamManagerFlag::eTEST_FOR_REMOVED_SHAPES); ActorPairReport*const* actorPairs = mNPhaseCore->getContactReportActorPairs(); PxU32 nbActorPairs = mNPhaseCore->getNbContactReportActorPairs(); for(PxU32 i=0; i < nbActorPairs; i++) { if (i < (nbActorPairs - 1)) PxPrefetchLine(actorPairs[i+1]); ActorPairReport* aPair = actorPairs[i]; ContactStreamManager* cs = &aPair->getContactStreamManager(); if (cs == NULL || cs->getFlags() & ContactStreamManagerFlag::eINVALID_STREAM) continue; if (i + 1 < nbActorPairs) PxPrefetch(&(actorPairs[i+1]->getContactStreamManager())); PxContactPairHeader pairHeader; finalizeContactStreamAndCreateHeader(pairHeader, *aPair, *cs, removedShapeTestMask); mSimulationEventCallback->onContact(pairHeader, pairHeader.pairs, pairHeader.nbPairs); // estimates for next frame cs->maxPairCount = cs->currentPairCount; cs->setMaxExtraDataSize(cs->extraDataSize); } } } PX_FORCE_INLINE void markDeletedShapes(Sc::ObjectIDTracker& idTracker, Sc::TriggerPairExtraData& tped, PxTriggerPair& pair) { PxTriggerPairFlags::InternalType flags = 0; if (idTracker.isDeletedID(tped.shape0ID)) flags |= PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER; if (idTracker.isDeletedID(tped.shape1ID)) flags |= PxTriggerPairFlag::eREMOVED_SHAPE_OTHER; pair.flags = PxTriggerPairFlags(flags); } void Sc::Scene::fireTriggerCallbacks() { // triggers const PxU32 nbTriggerPairs = mTriggerBufferAPI.size(); PX_ASSERT(nbTriggerPairs == mTriggerBufferExtraData->size()); if(nbTriggerPairs) { // cases to take into account: // - no simulation/trigger shape has been removed -> no need to test shape references for removed shapes // - simulation/trigger shapes have been removed -> test the events that have // a marker for removed shapes set // const bool hasRemovedShapes = mElementIDPool->getDeletedIDCount() > 0; if(mSimulationEventCallback) { if (!hasRemovedShapes) mSimulationEventCallback->onTrigger(mTriggerBufferAPI.begin(), nbTriggerPairs); else { for(PxU32 i = 0; i < nbTriggerPairs; i++) { PxTriggerPair& triggerPair = mTriggerBufferAPI[i]; if ((PxTriggerPairFlags::InternalType(triggerPair.flags) & TriggerPairFlag::eTEST_FOR_REMOVED_SHAPES)) markDeletedShapes(*mElementIDPool, (*mTriggerBufferExtraData)[i], triggerPair); } mSimulationEventCallback->onTrigger(mTriggerBufferAPI.begin(), nbTriggerPairs); } } } // PT: clear the buffer **even when there's no simulationEventCallback**. mTriggerBufferAPI.clear(); mTriggerBufferExtraData->clear(); } /* Threading: called in the context of the user thread, but only after the physics thread has finished its run */ void Sc::Scene::fireCallbacksPostSync() { // // Fire sleep & woken callbacks // // A body should be either in the sleep or the woken list. If it is in both, remove it from the list it was // least recently added to. if(!mSleepBodyListValid) cleanUpSleepBodies(); if(!mWokeBodyListValid) cleanUpWokenBodies(); #if PX_SUPPORT_GPU_PHYSX const PxU32 maxGpuSizeNeeded = gpu_cleanUpSleepAndWokenBodies(); #endif if(mSimulationEventCallback || mOnSleepingStateChanged) { // allocate temporary data const PxU32 nbSleep = mSleepBodies.size(); const PxU32 nbWoken = mWokeBodies.size(); #if PX_SUPPORT_GPU_PHYSX const PxU32 arrSize = PxMax(PxMax(nbSleep, nbWoken), maxGpuSizeNeeded); #else const PxU32 arrSize = PxMax(nbSleep, nbWoken); #endif PxActor** actors = arrSize ? reinterpret_cast<PxActor**>(PX_ALLOC(arrSize*sizeof(PxActor*), "PxActor*")) : NULL; if(actors) { if(nbSleep) { PxU32 destSlot = 0; BodyCore* const* sleepingBodies = mSleepBodies.getEntries(); for(PxU32 i=0; i<nbSleep; i++) { BodyCore* body = sleepingBodies[i]; if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES) actors[destSlot++] = body->getPxActor(); if (mOnSleepingStateChanged) mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), true); } if(destSlot && mSimulationEventCallback) mSimulationEventCallback->onSleep(actors, destSlot); //if (PX_DBG_IS_CONNECTED()) //{ // for (PxU32 i = 0; i < nbSleep; ++i) // { // BodyCore* body = mSleepBodies[i]; // PX_ASSERT(body->getActorType() == PxActorType::eRIGID_DYNAMIC); // } //} } #if PX_SUPPORT_GPU_PHYSX gpu_fireOnSleepCallback(actors); #endif // do the same thing for bodies that have just woken up if(nbWoken) { PxU32 destSlot = 0; BodyCore* const* wokenBodies = mWokeBodies.getEntries(); for(PxU32 i=0; i<nbWoken; i++) { BodyCore* body = wokenBodies[i]; if(body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES) actors[destSlot++] = body->getPxActor(); if (mOnSleepingStateChanged) mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), false); } if(destSlot && mSimulationEventCallback) mSimulationEventCallback->onWake(actors, destSlot); } #if PX_SUPPORT_GPU_PHYSX gpu_fireOnWakeCallback(actors); #endif PX_FREE(actors); } } clearSleepWakeBodies(); } void Sc::Scene::postCallbacksPreSync() { PX_PROFILE_ZONE("Sim.postCallbackPreSync", mContextId); // clear contact stream data mNPhaseCore->clearContactReportStream(); mNPhaseCore->clearContactReportActorPairs(false); postCallbacksPreSyncKinematics(); releaseConstraints(true); //release constraint blocks at the end of the frame, so user can retrieve the blocks } void Sc::Scene::getStats(PxSimulationStatistics& s) const { mStats->readOut(s, mLLContext->getSimStats()); s.nbStaticBodies = mNbRigidStatics; s.nbDynamicBodies = mNbRigidDynamics; s.nbKinematicBodies = mNbRigidKinematic; s.nbArticulations = mArticulations.size(); s.nbAggregates = mAABBManager->getNbActiveAggregates(); for(PxU32 i=0; i<PxGeometryType::eGEOMETRY_COUNT; i++) s.nbShapes[i] = mNbGeometries[i]; #if PX_SUPPORT_GPU_PHYSX if (mHeapMemoryAllocationManager) { s.gpuMemHeap = mHeapMemoryAllocationManager->getDeviceMemorySize(); const PxsHeapStats& deviceHeapStats = mHeapMemoryAllocationManager->getDeviceHeapStats(); s.gpuMemHeapBroadPhase = deviceHeapStats.stats[PxsHeapStats::eBROADPHASE]; s.gpuMemHeapNarrowPhase = deviceHeapStats.stats[PxsHeapStats::eNARROWPHASE]; s.gpuMemHeapSolver = deviceHeapStats.stats[PxsHeapStats::eSOLVER]; s.gpuMemHeapArticulation = deviceHeapStats.stats[PxsHeapStats::eARTICULATION]; s.gpuMemHeapSimulation = deviceHeapStats.stats[PxsHeapStats::eSIMULATION]; s.gpuMemHeapSimulationArticulation = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_ARTICULATION]; s.gpuMemHeapSimulationParticles = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_PARTICLES]; s.gpuMemHeapSimulationSoftBody = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_SOFTBODY]; s.gpuMemHeapSimulationFEMCloth = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_FEMCLOTH]; s.gpuMemHeapSimulationHairSystem = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_HAIRSYSTEM]; s.gpuMemHeapParticles = deviceHeapStats.stats[PxsHeapStats::eSHARED_PARTICLES]; s.gpuMemHeapFEMCloths = deviceHeapStats.stats[PxsHeapStats::eSHARED_FEMCLOTH]; s.gpuMemHeapSoftBodies = deviceHeapStats.stats[PxsHeapStats::eSHARED_SOFTBODY]; s.gpuMemHeapHairSystems = deviceHeapStats.stats[PxsHeapStats::eSHARED_HAIRSYSTEM]; s.gpuMemHeapOther = deviceHeapStats.stats[PxsHeapStats::eOTHER]; } else #endif { s.gpuMemHeap = 0; s.gpuMemParticles = 0; s.gpuMemSoftBodies = 0; s.gpuMemFEMCloths = 0; s.gpuMemHairSystems = 0; s.gpuMemHeapBroadPhase = 0; s.gpuMemHeapNarrowPhase = 0; s.gpuMemHeapSolver = 0; s.gpuMemHeapArticulation = 0; s.gpuMemHeapSimulation = 0; s.gpuMemHeapSimulationArticulation = 0; s.gpuMemHeapSimulationParticles = 0; s.gpuMemHeapSimulationSoftBody = 0; s.gpuMemHeapSimulationFEMCloth = 0; s.gpuMemHeapSimulationHairSystem = 0; s.gpuMemHeapParticles = 0; s.gpuMemHeapSoftBodies = 0; s.gpuMemHeapFEMCloths = 0; s.gpuMemHeapHairSystems = 0; s.gpuMemHeapOther = 0; } } void Sc::Scene::addShapes(NpShape *const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& bodySim, PxBounds3* outBounds) { const PxNodeIndex nodeIndex = bodySim.getNodeIndex(); PxvNphaseImplementationContext* context = mLLContext->getNphaseImplementationContext(); for(PxU32 i=0;i<nbShapes;i++) { // PT: TODO: drop the offsets and let me include NpShape.h from here! This is just NpShape::getCore().... ShapeCore& sc = *reinterpret_cast<ShapeCore*>(size_t(shapes[i])+ptrOffset); //PxBounds3* target = uninflatedBounds ? uninflatedBounds + i : uninflatedBounds; //mShapeSimPool->construct(sim, sc, llBody, target); ShapeSim* shapeSim = mShapeSimPool->construct(bodySim, sc); mNbGeometries[sc.getGeometryType()]++; mSimulationController->addShape(&shapeSim->getLLShapeSim(), shapeSim->getElementID()); if (outBounds) outBounds[i] = mBoundsArray->getBounds(shapeSim->getElementID()); //I register the shape if its either not an articulation link or if the nodeIndex has already been //assigned. On insertion, the articulation will not have this nodeIndex correctly assigned at this stage if (bodySim.getActorType() != PxActorType::eARTICULATION_LINK || !nodeIndex.isStaticBody()) context->registerShape(nodeIndex, sc.getCore(), shapeSim->getElementID(), bodySim.getPxActor()); } } void Sc::Scene::removeShapes(Sc::RigidSim& sim, PxInlineArray<Sc::ShapeSim*, 64>& shapesBuffer , PxInlineArray<const Sc::ShapeCore*,64>& removedShapes, bool wakeOnLostTouch) { PxU32 nbElems = sim.getNbElements(); Sc::ElementSim** elems = sim.getElements(); while (nbElems--) { Sc::ShapeSim* s = static_cast<Sc::ShapeSim*>(*elems++); // can do two 2x the allocs in the worst case, but actors with >64 shapes are not common shapesBuffer.pushBack(s); removedShapes.pushBack(&s->getCore()); } for(PxU32 i=0;i<shapesBuffer.size();i++) removeShape_(*shapesBuffer[i], wakeOnLostTouch); } void Sc::Scene::addStatic(StaticCore& ro, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* uninflatedBounds) { PX_ASSERT(ro.getActorCoreType() == PxActorType::eRIGID_STATIC); // sim objects do all the necessary work of adding themselves to broad phase, // activation, registering with the interaction system, etc StaticSim* sim = mStaticSimPool->construct(*this, ro); mNbRigidStatics++; addShapes(shapes, nbShapes, shapePtrOffset, *sim, uninflatedBounds); } void Sc::Scene::removeStatic(StaticCore& ro, PxInlineArray<const Sc::ShapeCore*,64>& removedShapes, bool wakeOnLostTouch) { PX_ASSERT(ro.getActorCoreType() == PxActorType::eRIGID_STATIC); StaticSim* sim = ro.getSim(); if(sim) { if(mBatchRemoveState) { removeShapes(*sim, mBatchRemoveState->bufferedShapes ,removedShapes, wakeOnLostTouch); } else { PxInlineArray<Sc::ShapeSim*, 64> shapesBuffer; removeShapes(*sim, shapesBuffer ,removedShapes, wakeOnLostTouch); } mStaticSimPool->destroy(static_cast<Sc::StaticSim*>(ro.getSim())); mNbRigidStatics--; } } void Sc::Scene::addBody(BodyCore& body, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* outBounds, bool compound) { // sim objects do all the necessary work of adding themselves to broad phase, // activation, registering with the interaction system, etc BodySim* sim = mBodySimPool->construct(*this, body, compound); const bool isArticulationLink = sim->isArticulationLink(); if (sim->getLowLevelBody().mCore->mFlags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD && sim->isActive()) { if (isArticulationLink) { if (sim->getNodeIndex().isValid()) mSpeculativeCDDArticulationBitMap.growAndSet(sim->getNodeIndex().index()); } else mSpeculativeCCDRigidBodyBitMap.growAndSet(sim->getNodeIndex().index()); } //if rigid body is articulation link, the node index will be invalid. We should add the link to the scene after we add the //articulation for gpu if(sim->getNodeIndex().isValid()) mSimulationController->addDynamic(&sim->getLowLevelBody(), sim->getNodeIndex()); if(sim->getSimStateData(true) && sim->getSimStateData(true)->isKine()) mNbRigidKinematic++; else mNbRigidDynamics++; addShapes(shapes, nbShapes, shapePtrOffset, *sim, outBounds); mDynamicsContext->setStateDirty(true); } void Sc::Scene::removeBody(BodyCore& body, PxInlineArray<const Sc::ShapeCore*,64>& removedShapes, bool wakeOnLostTouch) { BodySim *sim = body.getSim(); if(sim) { if(mBatchRemoveState) { removeShapes(*sim, mBatchRemoveState->bufferedShapes, removedShapes, wakeOnLostTouch); } else { PxInlineArray<Sc::ShapeSim*, 64> shapesBuffer; removeShapes(*sim,shapesBuffer, removedShapes, wakeOnLostTouch); } if(!sim->isArticulationLink()) { //clear bit map if(sim->getLowLevelBody().mCore->mFlags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) sim->getScene().resetSpeculativeCCDRigidBody(sim->getNodeIndex().index()); } else { // PT: TODO: missing call to resetSpeculativeCCDArticulationLink ? sim->getArticulation()->removeBody(*sim); } if(sim->getSimStateData(true) && sim->getSimStateData(true)->isKine()) { body.onRemoveKinematicFromScene(); mNbRigidKinematic--; } else mNbRigidDynamics--; mBodySimPool->destroy(sim); mDynamicsContext->setStateDirty(true); } } // PT: TODO: refactor with addShapes void Sc::Scene::addShape_(RigidSim& owner, ShapeCore& shapeCore) { ShapeSim* sim = mShapeSimPool->construct(owner, shapeCore); mNbGeometries[shapeCore.getGeometryType()]++; //register shape mSimulationController->addShape(&sim->getLLShapeSim(), sim->getElementID()); registerShapeInNphase(&owner.getRigidCore(), shapeCore, sim->getElementID()); } // PT: TODO: refactor with removeShapes void Sc::Scene::removeShape_(ShapeSim& shape, bool wakeOnLostTouch) { //BodySim* body = shape.getBodySim(); //if(body) // body->postShapeDetach(); unregisterShapeFromNphase(shape.getCore(), shape.getElementID()); mSimulationController->removeShape(shape.getElementID()); mNbGeometries[shape.getCore().getGeometryType()]--; shape.removeFromBroadPhase(wakeOnLostTouch); mShapeSimPool->destroy(&shape); } void Sc::Scene::registerShapeInNphase(Sc::RigidCore* rigidCore, const ShapeCore& shape, const PxU32 transformCacheID) { RigidSim* sim = rigidCore->getSim(); if(sim) mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), shape.getCore(), transformCacheID, sim->getPxActor()); } void Sc::Scene::unregisterShapeFromNphase(const ShapeCore& shape, const PxU32 transformCacheID) { mLLContext->getNphaseImplementationContext()->unregisterShape(shape.getCore(), transformCacheID); } void Sc::Scene::notifyNphaseOnUpdateShapeMaterial(const ShapeCore& shapeCore) { mLLContext->getNphaseImplementationContext()->updateShapeMaterial(shapeCore.getCore()); } void Sc::Scene::startBatchInsertion(BatchInsertionState&state) { state.shapeSim = mShapeSimPool->allocateAndPrefetch(); state.staticSim = mStaticSimPool->allocateAndPrefetch(); state.bodySim = mBodySimPool->allocateAndPrefetch(); } void Sc::Scene::addShapes(NpShape*const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& rigidSim, ShapeSim*& prefetchedShapeSim, PxBounds3* outBounds) { for(PxU32 i=0;i<nbShapes;i++) { if(i+1<nbShapes) PxPrefetch(shapes[i+1], PxU32(ptrOffset+sizeof(Sc::ShapeCore))); ShapeSim* nextShapeSim = mShapeSimPool->allocateAndPrefetch(); ShapeCore& sc = *PxPointerOffset<ShapeCore*>(shapes[i], ptrdiff_t(ptrOffset)); PX_PLACEMENT_NEW(prefetchedShapeSim, ShapeSim(rigidSim, sc)); const PxU32 elementID = prefetchedShapeSim->getElementID(); outBounds[i] = mBoundsArray->getBounds(elementID); mSimulationController->addShape(&prefetchedShapeSim->getLLShapeSim(), elementID); mLLContext->getNphaseImplementationContext()->registerShape(rigidSim.getNodeIndex(), sc.getCore(), elementID, rigidSim.getPxActor()); prefetchedShapeSim = nextShapeSim; mNbGeometries[sc.getGeometryType()]++; } } void Sc::Scene::addStatic(PxActor* actor, BatchInsertionState& s, PxBounds3* outBounds) { // static core has been prefetched by caller Sc::StaticSim* sim = s.staticSim; // static core has been prefetched by the caller const Cm::PtrTable* shapeTable = PxPointerOffset<const Cm::PtrTable*>(actor, s.staticShapeTableOffset); void*const* shapes = shapeTable->getPtrs(); mStaticSimPool->construct(sim, *this, *PxPointerOffset<Sc::StaticCore*>(actor, s.staticActorOffset)); s.staticSim = mStaticSimPool->allocateAndPrefetch(); addShapes(reinterpret_cast<NpShape*const*>(shapes), shapeTable->getCount(), size_t(s.shapeOffset), *sim, s.shapeSim, outBounds); mNbRigidStatics++; } void Sc::Scene::addBody(PxActor* actor, BatchInsertionState& s, PxBounds3* outBounds, bool compound) { Sc::BodySim* sim = s.bodySim; // body core has been prefetched by the caller const Cm::PtrTable* shapeTable = PxPointerOffset<const Cm::PtrTable*>(actor, s.dynamicShapeTableOffset); void*const* shapes = shapeTable->getPtrs(); Sc::BodyCore* bodyCore = PxPointerOffset<Sc::BodyCore*>(actor, s.dynamicActorOffset); mBodySimPool->construct(sim, *this, *bodyCore, compound); s.bodySim = mBodySimPool->allocateAndPrefetch(); if(sim->getLowLevelBody().mCore->mFlags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) { if(sim->isArticulationLink()) mSpeculativeCDDArticulationBitMap.growAndSet(sim->getNodeIndex().index()); else mSpeculativeCCDRigidBodyBitMap.growAndSet(sim->getNodeIndex().index()); } if(sim->getNodeIndex().isValid()) mSimulationController->addDynamic(&sim->getLowLevelBody(), sim->getNodeIndex()); addShapes(reinterpret_cast<NpShape*const*>(shapes), shapeTable->getCount(), size_t(s.shapeOffset), *sim, s.shapeSim, outBounds); const SimStateData* simStateData = bodyCore->getSim()->getSimStateData(true); if(simStateData && simStateData->isKine()) mNbRigidKinematic++; else mNbRigidDynamics++; mDynamicsContext->setStateDirty(true); } void Sc::Scene::finishBatchInsertion(BatchInsertionState& state) { // a little bit lazy - we could deal with the last one in the batch specially to avoid overallocating by one. mStaticSimPool->releasePreallocated(static_cast<Sc::StaticSim*>(state.staticSim)); mBodySimPool->releasePreallocated(static_cast<Sc::BodySim*>(state.bodySim)); mShapeSimPool->releasePreallocated(state.shapeSim); } // PT: TODO: why is this in Sc? void Sc::Scene::initContactsIterator(ContactIterator& contactIterator, PxsContactManagerOutputIterator& outputs) { outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs(); ElementSimInteraction** first = mInteractions[Sc::InteractionType::eOVERLAP].begin(); contactIterator = ContactIterator(first, first + mActiveInteractionCount[Sc::InteractionType::eOVERLAP], outputs); } void Sc::Scene::setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance) { struct { void operator()(PxU32& bits, PxDominanceGroup shift, PxReal weight) { if(weight != PxReal(0)) bits |= (PxU32(1) << shift); else bits &= ~(PxU32(1) << shift); } } bitsetter; bitsetter(mDominanceBitMatrix[group1], group2, dominance.dominance0); bitsetter(mDominanceBitMatrix[group2], group1, dominance.dominance1); mInternalFlags |= SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_DOMINANCE; //force an update on all interactions on matrix change -- very expensive but we have no choice!! } PxDominanceGroupPair Sc::Scene::getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const { const PxU8 dom0 = PxU8((mDominanceBitMatrix[group1]>>group2) & 0x1 ? 1u : 0u); const PxU8 dom1 = PxU8((mDominanceBitMatrix[group2]>>group1) & 0x1 ? 1u : 0u); return PxDominanceGroupPair(dom0, dom1); } PxU32 Sc::Scene::getDefaultContactReportStreamBufferSize() const { return mNPhaseCore->getDefaultContactReportStreamBufferSize(); } void Sc::Scene::buildActiveActors() { { PxU32 numActiveBodies = 0; BodyCore*const* PX_RESTRICT activeBodies; if (!(getFlags() & PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS)) { numActiveBodies = getNumActiveBodies(); activeBodies = getActiveBodiesArray(); } else { numActiveBodies = getActiveDynamicBodiesCount(); activeBodies = getActiveDynamicBodies(); } mActiveActors.clear(); for (PxU32 i = 0; i < numActiveBodies; i++) { if (!activeBodies[i]->isFrozen()) { PxRigidActor* ra = static_cast<PxRigidActor*>(activeBodies[i]->getPxActor()); PX_ASSERT(ra); mActiveActors.pushBack(ra); } } } #if PX_SUPPORT_GPU_PHYSX gpu_buildActiveActors(); #endif } // PT: TODO: unify buildActiveActors & buildActiveAndFrozenActors void Sc::Scene::buildActiveAndFrozenActors() { { PxU32 numActiveBodies = 0; BodyCore*const* PX_RESTRICT activeBodies; if (!(getFlags() & PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS)) { numActiveBodies = getNumActiveBodies(); activeBodies = getActiveBodiesArray(); } else { numActiveBodies = getActiveDynamicBodiesCount(); activeBodies = getActiveDynamicBodies(); } mActiveActors.clear(); mFrozenActors.clear(); for (PxU32 i = 0; i < numActiveBodies; i++) { PxRigidActor* ra = static_cast<PxRigidActor*>(activeBodies[i]->getPxActor()); PX_ASSERT(ra); if (!activeBodies[i]->isFrozen()) mActiveActors.pushBack(ra); else mFrozenActors.pushBack(ra); } } #if PX_SUPPORT_GPU_PHYSX gpu_buildActiveAndFrozenActors(); #endif } PxActor** Sc::Scene::getActiveActors(PxU32& nbActorsOut) { nbActorsOut = mActiveActors.size(); if(!nbActorsOut) return NULL; return mActiveActors.begin(); } void Sc::Scene::setActiveActors(PxActor** actors, PxU32 nbActors) { mActiveActors.forceSize_Unsafe(0); mActiveActors.resize(nbActors); PxMemCopy(mActiveActors.begin(), actors, sizeof(PxActor*) * nbActors); } PxActor** Sc::Scene::getFrozenActors(PxU32& nbActorsOut) { nbActorsOut = mFrozenActors.size(); if(!nbActorsOut) return NULL; return mFrozenActors.begin(); } void Sc::Scene::reserveTriggerReportBufferSpace(const PxU32 pairCount, PxTriggerPair*& triggerPairBuffer, TriggerPairExtraData*& triggerPairExtraBuffer) { const PxU32 oldSize = mTriggerBufferAPI.size(); const PxU32 newSize = oldSize + pairCount; const PxU32 newCapacity = PxU32(newSize * 1.5f); mTriggerBufferAPI.reserve(newCapacity); mTriggerBufferAPI.forceSize_Unsafe(newSize); triggerPairBuffer = mTriggerBufferAPI.begin() + oldSize; PX_ASSERT(oldSize == mTriggerBufferExtraData->size()); mTriggerBufferExtraData->reserve(newCapacity); mTriggerBufferExtraData->forceSize_Unsafe(newSize); triggerPairExtraBuffer = mTriggerBufferExtraData->begin() + oldSize; } template<const bool sleepOrWoke, class T> static void clearBodies(PxCoalescedHashSet<T*>& bodies) { T* const* sleepingOrWokenBodies = bodies.getEntries(); const PxU32 nb = bodies.size(); for(PxU32 i=0; i<nb; i++) { ActorSim* body = sleepingOrWokenBodies[i]->getSim(); if(sleepOrWoke) { PX_ASSERT(!body->readInternalFlag(ActorSim::BF_WAKEUP_NOTIFY)); body->clearInternalFlag(ActorSim::BF_SLEEP_NOTIFY); } else { PX_ASSERT(!body->readInternalFlag(ActorSim::BF_SLEEP_NOTIFY)); body->clearInternalFlag(ActorSim::BF_WAKEUP_NOTIFY); } // A body can be in both lists depending on the sequence of events body->clearInternalFlag(ActorSim::BF_IS_IN_SLEEP_LIST); body->clearInternalFlag(ActorSim::BF_IS_IN_WAKEUP_LIST); } bodies.clear(); } void Sc::Scene::clearSleepWakeBodies() { // Clear sleep/woken marker flags clearBodies<true>(mSleepBodies); clearBodies<false>(mWokeBodies); mSleepBodies.clear(); mWokeBodies.clear(); mWokeBodyListValid = true; mSleepBodyListValid = true; #if PX_SUPPORT_GPU_PHYSX gpu_clearSleepWakeBodies(); #endif } void Sc::Scene::onBodySleep(BodySim* body) { if (!mSimulationEventCallback && !mOnSleepingStateChanged) return; if (body->readInternalFlag(ActorSim::BF_WAKEUP_NOTIFY)) { PX_ASSERT(!body->readInternalFlag(ActorSim::BF_SLEEP_NOTIFY)); // Body is in the list of woken bodies, hence, mark this list as dirty such that it gets cleaned up before // being sent to the user body->clearInternalFlag(ActorSim::BF_WAKEUP_NOTIFY); mWokeBodyListValid = false; } body->raiseInternalFlag(ActorSim::BF_SLEEP_NOTIFY); // Avoid multiple insertion (the user can do multiple transitions between asleep and awake) if (!body->readInternalFlag(ActorSim::BF_IS_IN_SLEEP_LIST)) { PX_ASSERT(!mSleepBodies.contains(&body->getBodyCore())); mSleepBodies.insert(&body->getBodyCore()); body->raiseInternalFlag(ActorSim::BF_IS_IN_SLEEP_LIST); } } void Sc::Scene::onBodyWakeUp(BodySim* body) { if(!mSimulationEventCallback && !mOnSleepingStateChanged) return; if (body->readInternalFlag(BodySim::BF_SLEEP_NOTIFY)) { PX_ASSERT(!body->readInternalFlag(BodySim::BF_WAKEUP_NOTIFY)); // Body is in the list of sleeping bodies, hence, mark this list as dirty such it gets cleaned up before // being sent to the user body->clearInternalFlag(BodySim::BF_SLEEP_NOTIFY); mSleepBodyListValid = false; } body->raiseInternalFlag(BodySim::BF_WAKEUP_NOTIFY); // Avoid multiple insertion (the user can do multiple transitions between asleep and awake) if (!body->readInternalFlag(BodySim::BF_IS_IN_WAKEUP_LIST)) { PX_ASSERT(!mWokeBodies.contains(&body->getBodyCore())); mWokeBodies.insert(&body->getBodyCore()); body->raiseInternalFlag(BodySim::BF_IS_IN_WAKEUP_LIST); } } PX_INLINE void Sc::Scene::cleanUpSleepBodies() { BodyCore* const* bodyArray = mSleepBodies.getEntries(); PxU32 bodyCount = mSleepBodies.size(); IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); while (bodyCount--) { ActorSim* actor = bodyArray[bodyCount]->getSim(); BodySim* body = static_cast<BodySim*>(actor); if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_WAKEUP_NOTIFY))) { body->clearInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_IS_IN_WAKEUP_LIST)); mSleepBodies.erase(bodyArray[bodyCount]); } else if (islandSim.getNode(body->getNodeIndex()).isActive()) { //This body is still active in the island simulation, so the request to deactivate the actor by the application must have failed. Recover by undoing this mSleepBodies.erase(bodyArray[bodyCount]); actor->internalWakeUp(); } } mSleepBodyListValid = true; } PX_INLINE void Sc::Scene::cleanUpWokenBodies() { cleanUpSleepOrWokenBodies(mWokeBodies, BodySim::BF_SLEEP_NOTIFY, mWokeBodyListValid); } PX_INLINE void Sc::Scene::cleanUpSleepOrWokenBodies(PxCoalescedHashSet<BodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker) { // With our current logic it can happen that a body is added to the sleep as well as the woken body list in the // same frame. // // Examples: // - Kinematic is created (added to woken list) but has not target (-> deactivation -> added to sleep list) // - Dynamic is created (added to woken list) but is forced to sleep by user (-> deactivation -> added to sleep list) // // This code traverses the sleep/woken body list and removes bodies which have been initially added to the given // list but do not belong to it anymore. BodyCore* const* bodyArray = bodyList.getEntries(); PxU32 bodyCount = bodyList.size(); while (bodyCount--) { BodySim* body = bodyArray[bodyCount]->getSim(); if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(removeFlag))) bodyList.erase(bodyArray[bodyCount]); } validMarker = true; } FeatherstoneArticulation* Sc::Scene::createLLArticulation(Sc::ArticulationSim* sim) { return mLLArticulationRCPool->construct(sim); } void Sc::Scene::destroyLLArticulation(FeatherstoneArticulation& articulation) { mLLArticulationRCPool->destroy(static_cast<Dy::FeatherstoneArticulation*>(&articulation)); } PxU32 Sc::Scene::createAggregate(void* userData, PxU32 maxNumShapes, PxAggregateFilterHint filterHint) { const physx::Bp::BoundsIndex index = getElementIDPool().createID(); mBoundsArray->initEntry(index); mLLContext->getNphaseImplementationContext()->registerAggregate(index); #ifdef BP_USE_AGGREGATE_GROUP_TAIL return mAABBManager->createAggregate(index, Bp::FilterGroup::eINVALID, userData, maxNumShapes, filterHint); #else // PT: TODO: ideally a static compound would have a static group const PxU32 rigidId = getRigidIDTracker().createID(); const Bp::FilterGroup::Enum bpGroup = Bp::FilterGroup::Enum(rigidId + Bp::FilterGroup::eDYNAMICS_BASE); return mAABBManager->createAggregate(index, bpGroup, userData, selfCollisions); #endif } void Sc::Scene::deleteAggregate(PxU32 id) { Bp::BoundsIndex index; Bp::FilterGroup::Enum bpGroup; #ifdef BP_USE_AGGREGATE_GROUP_TAIL if(mAABBManager->destroyAggregate(index, bpGroup, id)) { getElementIDPool().releaseID(index); } #else if(mAABBManager->destroyAggregate(index, bpGroup, id)) { getElementIDPool().releaseID(index); // PT: this is clumsy.... const PxU32 rigidId = PxU32(bpGroup) - Bp::FilterGroup::eDYNAMICS_BASE; getRigidIDTracker().releaseID(rigidId); } #endif } void Sc::Scene::shiftOrigin(const PxVec3& shift) { // adjust low level context mLLContext->shiftOrigin(shift); // adjust bounds array mBoundsArray->shiftOrigin(shift); // adjust broadphase mAABBManager->shiftOrigin(shift); // adjust constraints ConstraintCore*const * constraints = mConstraints.getEntries(); for(PxU32 i=0, size = mConstraints.size(); i < size; i++) constraints[i]->getPxConnector()->onOriginShift(shift); } /////////////////////////////////////////////////////////////////////////////// // PT: onActivate() functions should be called when an interaction is activated or created, and return true if activation // should proceed else return false (for example: joint interaction between two kinematics should not get activated) bool Sc::activateInteraction(Sc::Interaction* interaction, void* data) { switch(interaction->getType()) { case InteractionType::eOVERLAP: return static_cast<Sc::ShapeInteraction*>(interaction)->onActivate(data); case InteractionType::eTRIGGER: return static_cast<Sc::TriggerInteraction*>(interaction)->onActivate(data); case InteractionType::eMARKER: // PT: ElementInteractionMarker::onActivate() always returns false (always inactive). return false; case InteractionType::eCONSTRAINTSHADER: return static_cast<Sc::ConstraintInteraction*>(interaction)->onActivate(data); case InteractionType::eARTICULATION: return static_cast<Sc::ArticulationJointSim*>(interaction)->onActivate(data); case InteractionType::eTRACKED_IN_SCENE_COUNT: case InteractionType::eINVALID: PX_ASSERT(0); break; } return false; } // PT: onDeactivate() functions should be called when an interaction is deactivated, and return true if deactivation should proceed // else return false (for example: joint interaction between two kinematics can ignore deactivation because it always is deactivated) /*static*/ bool deactivateInteraction(Sc::Interaction* interaction, const Sc::InteractionType::Enum type) { switch(type) { case InteractionType::eOVERLAP: return static_cast<Sc::ShapeInteraction*>(interaction)->onDeactivate(); case InteractionType::eTRIGGER: return static_cast<Sc::TriggerInteraction*>(interaction)->onDeactivate(); case InteractionType::eMARKER: // PT: ElementInteractionMarker::onDeactivate() always returns true. return true; case InteractionType::eCONSTRAINTSHADER: return static_cast<Sc::ConstraintInteraction*>(interaction)->onDeactivate(); case InteractionType::eARTICULATION: return static_cast<Sc::ArticulationJointSim*>(interaction)->onDeactivate(); case InteractionType::eTRACKED_IN_SCENE_COUNT: case InteractionType::eINVALID: PX_ASSERT(0); break; } return false; } void Sc::activateInteractions(Sc::ActorSim& actorSim) { const PxU32 nbInteractions = actorSim.getActorInteractionCount(); if(!nbInteractions) return; Interaction** interactions = actorSim.getActorInteractions(); Scene& scene = actorSim.getScene(); for(PxU32 i=0; i<nbInteractions; ++i) { PxPrefetchLine(interactions[PxMin(i+1,nbInteractions-1)]); Interaction* interaction = interactions[i]; if(!interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)) { const InteractionType::Enum type = interaction->getType(); const bool isNotIGControlled = type != InteractionType::eOVERLAP && type != InteractionType::eMARKER; if(isNotIGControlled) { const bool proceed = activateInteraction(interaction, NULL); if(proceed && (type < InteractionType::eTRACKED_IN_SCENE_COUNT)) scene.notifyInteractionActivated(interaction); // PT: we can reach this line for trigger interactions } } } } void Sc::deactivateInteractions(Sc::ActorSim& actorSim) { const PxU32 nbInteractions = actorSim.getActorInteractionCount(); if(!nbInteractions) return; Interaction** interactions = actorSim.getActorInteractions(); Scene& scene = actorSim.getScene(); for(PxU32 i=0; i<nbInteractions; ++i) { PxPrefetchLine(interactions[PxMin(i+1,nbInteractions-1)]); Interaction* interaction = interactions[i]; if(interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE)) { const InteractionType::Enum type = interaction->getType(); const bool isNotIGControlled = type != InteractionType::eOVERLAP && type != InteractionType::eMARKER; if(isNotIGControlled) { const bool proceed = deactivateInteraction(interaction, type); if(proceed && (type < InteractionType::eTRACKED_IN_SCENE_COUNT)) scene.notifyInteractionDeactivated(interaction); // PT: we can reach this line for trigger interactions } } } } Sc::ConstraintCore* Sc::Scene::findConstraintCore(const Sc::ActorSim* sim0, const Sc::ActorSim* sim1) { const PxNodeIndex ind0 = sim0->getNodeIndex(); const PxNodeIndex ind1 = sim1->getNodeIndex(); if(ind1 < ind0) PxSwap(sim0, sim1); const PxHashMap<PxPair<const Sc::ActorSim*, const Sc::ActorSim*>, Sc::ConstraintCore*>::Entry* entry = mConstraintMap.find(PxPair<const Sc::ActorSim*, const Sc::ActorSim*>(sim0, sim1)); return entry ? entry->second : NULL; } void Sc::Scene::updateBodySim(Sc::BodySim& bodySim) { Dy::FeatherstoneArticulation* arti = NULL; Sc::ArticulationSim* artiSim = bodySim.getArticulation(); if (artiSim) arti = artiSim->getLowLevelArticulation(); mSimulationController->updateDynamic(arti, bodySim.getNodeIndex()); } // PT: start moving PX_SUPPORT_GPU_PHYSX bits to the end of the file. Ideally/eventually they would move to a separate class or file, // to clearly decouple the CPU and GPU parts of the scene/pipeline. #if PX_SUPPORT_GPU_PHYSX void Sc::Scene::gpu_releasePools() { PX_DELETE(mLLSoftBodyPool); PX_DELETE(mLLFEMClothPool); PX_DELETE(mLLParticleSystemPool); PX_DELETE(mLLHairSystemPool); } void Sc::Scene::gpu_release() { PX_DELETE(mHeapMemoryAllocationManager); } template<class T> static void addToActiveArray(PxArray<T*>& activeArray, ActorSim& actorSim, ActorCore* core) { const PxU32 activeListIndex = activeArray.size(); actorSim.setActiveListIndex(activeListIndex); activeArray.pushBack(static_cast<T*>(core)); } void Sc::Scene::gpu_addToActiveList(ActorSim& actorSim, ActorCore* appendedActorCore) { if (actorSim.isSoftBody()) addToActiveArray(mActiveSoftBodies, actorSim, appendedActorCore); else if (actorSim.isFEMCloth()) addToActiveArray(mActiveFEMCloths, actorSim, appendedActorCore); else if (actorSim.isParticleSystem()) addToActiveArray(mActiveParticleSystems, actorSim, appendedActorCore); else if (actorSim.isHairSystem()) addToActiveArray(mActiveHairSystems, actorSim, appendedActorCore); } template<class T> static void removeFromActiveArray(PxArray<T*>& activeArray, PxU32 removedActiveIndex) { const PxU32 newSize = activeArray.size() - 1; if(removedActiveIndex != newSize) { T* lastBody = activeArray[newSize]; activeArray[removedActiveIndex] = lastBody; lastBody->getSim()->setActiveListIndex(removedActiveIndex); } activeArray.forceSize_Unsafe(newSize); } void Sc::Scene::gpu_removeFromActiveList(ActorSim& actorSim, PxU32 removedActiveIndex) { if(actorSim.isSoftBody()) removeFromActiveArray(mActiveSoftBodies, removedActiveIndex); else if(actorSim.isFEMCloth()) removeFromActiveArray(mActiveFEMCloths, removedActiveIndex); else if(actorSim.isParticleSystem()) removeFromActiveArray(mActiveParticleSystems, removedActiveIndex); else if(actorSim.isHairSystem()) removeFromActiveArray(mActiveHairSystems, removedActiveIndex); } void Sc::Scene::gpu_clearSleepWakeBodies() { clearBodies<true>(mSleepSoftBodies); clearBodies<true>(mSleepHairSystems); clearBodies<false>(mWokeSoftBodies); clearBodies<false>(mWokeHairSystems); mWokeSoftBodyListValid = true; mSleepSoftBodyListValid = true; mWokeHairSystemListValid = true; mSleepHairSystemListValid = true; } void Sc::Scene::gpu_buildActiveActors() { { PxU32 numActiveSoftBodies = getNumActiveSoftBodies(); SoftBodyCore*const* PX_RESTRICT activeSoftBodies = getActiveSoftBodiesArray(); mActiveSoftBodyActors.clear(); for (PxU32 i = 0; i < numActiveSoftBodies; i++) { PxActor* ra = activeSoftBodies[i]->getPxActor(); mActiveSoftBodyActors.pushBack(ra); } } { PxU32 numActiveHairSystems = getNumActiveHairSystems(); HairSystemCore*const* PX_RESTRICT activeHairSystems = getActiveHairSystemsArray(); mActiveHairSystemActors.clear(); for (PxU32 i = 0; i < numActiveHairSystems; i++) { PxActor* ra = activeHairSystems[i]->getPxActor(); mActiveHairSystemActors.pushBack(ra); } } } void Sc::Scene::gpu_buildActiveAndFrozenActors() { { PxU32 numActiveSoftBodies = getNumActiveSoftBodies(); SoftBodyCore*const* PX_RESTRICT activeSoftBodies = getActiveSoftBodiesArray(); mActiveSoftBodyActors.clear(); for (PxU32 i = 0; i < numActiveSoftBodies; i++) { PxActor* ra = activeSoftBodies[i]->getPxActor(); mActiveSoftBodyActors.pushBack(ra); } } { PxU32 numActiveHairSystems = getNumActiveHairSystems(); HairSystemCore*const* PX_RESTRICT activeHairSystems = getActiveHairSystemsArray(); mActiveHairSystemActors.clear(); for (PxU32 i = 0; i < numActiveHairSystems; i++) { PxActor* ra = activeHairSystems[i]->getPxActor(); mActiveHairSystemActors.pushBack(ra); } } } void Sc::Scene::gpu_setSimulationEventCallback(PxSimulationEventCallback* /*callback*/) { SoftBodyCore* const* sleepingSoftBodies = mSleepSoftBodies.getEntries(); for (PxU32 i = 0; i < mSleepSoftBodies.size(); i++) { sleepingSoftBodies[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY); } //FEMClothCore* const* sleepingFEMCloths = mSleepFEMCloths.getEntries(); //for (PxU32 i = 0; i < mSleepFEMCloths.size(); i++) //{ // sleepingFEMCloths[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY); //} HairSystemCore* const* sleepingHairSystems = mSleepHairSystems.getEntries(); for (PxU32 i = 0; i < mSleepHairSystems.size(); i++) { sleepingHairSystems[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY); } } PxU32 Sc::Scene::gpu_cleanUpSleepAndWokenBodies() { if (!mSleepSoftBodyListValid) cleanUpSleepSoftBodies(); if (!mWokeBodyListValid) cleanUpWokenSoftBodies(); if (!mSleepHairSystemListValid) cleanUpSleepHairSystems(); if (!mWokeHairSystemListValid) // TODO(jcarius) should this be mWokeBodyListValid? cleanUpWokenHairSystems(); const PxU32 nbHairSystemSleep = mSleepHairSystems.size(); const PxU32 nbHairSystemWoken = mWokeHairSystems.size(); const PxU32 nbSoftBodySleep = mSleepSoftBodies.size(); const PxU32 nbSoftBodyWoken = mWokeSoftBodies.size(); return PxMax(PxMax(nbSoftBodyWoken, nbHairSystemWoken), PxMax(nbSoftBodySleep, nbHairSystemSleep)); } void Sc::Scene::gpu_fireOnSleepCallback(PxActor** actors) { //ML: need to create and API for the onSleep for softbody const PxU32 nbSoftBodySleep = mSleepSoftBodies.size(); if (nbSoftBodySleep) { PxU32 destSlot = 0; SoftBodyCore* const* sleepingSoftBodies = mSleepSoftBodies.getEntries(); for (PxU32 i = 0; i<nbSoftBodySleep; i++) { SoftBodyCore* body = sleepingSoftBodies[i]; if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES) actors[destSlot++] = body->getPxActor(); if (mOnSleepingStateChanged) mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), true); } if (destSlot && mSimulationEventCallback) mSimulationEventCallback->onSleep(actors, destSlot); } const PxU32 nbHairSystemSleep = mSleepHairSystems.size(); if (nbHairSystemSleep) { PxU32 destSlot = 0; HairSystemCore* const* sleepingHairSystems = mSleepHairSystems.getEntries(); for (PxU32 i = 0; i<nbHairSystemSleep; i++) { HairSystemCore* body = sleepingHairSystems[i]; if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES) actors[destSlot++] = body->getPxActor(); if (mOnSleepingStateChanged) mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), true); } if (destSlot && mSimulationEventCallback) mSimulationEventCallback->onSleep(actors, destSlot); } } void Sc::Scene::gpu_fireOnWakeCallback(PxActor** actors) { //ML: need to create an API for woken soft body const PxU32 nbSoftBodyWoken = mWokeSoftBodies.size(); if (nbSoftBodyWoken) { PxU32 destSlot = 0; SoftBodyCore* const* wokenSoftBodies = mWokeSoftBodies.getEntries(); for (PxU32 i = 0; i<nbSoftBodyWoken; i++) { SoftBodyCore* body = wokenSoftBodies[i]; if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES) actors[destSlot++] = body->getPxActor(); if (mOnSleepingStateChanged) mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), false); } if (destSlot && mSimulationEventCallback) mSimulationEventCallback->onWake(actors, destSlot); } const PxU32 nbHairSystemWoken = mWokeHairSystems.size(); if (nbHairSystemWoken) { PxU32 destSlot = 0; HairSystemCore* const* wokenHairSystems = mWokeHairSystems.getEntries(); for (PxU32 i = 0; i<nbHairSystemWoken; i++) { HairSystemCore* body = wokenHairSystems[i]; if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES) actors[destSlot++] = body->getPxActor(); if (mOnSleepingStateChanged) mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), false); } if (destSlot && mSimulationEventCallback) mSimulationEventCallback->onWake(actors, destSlot); } } void Sc::Scene::gpu_updateBounds() { //update soft bodies world bound Sc::SoftBodyCore* const* softBodies = mSoftBodies.getEntries(); PxU32 size = mSoftBodies.size(); if (mUseGpuBp) { for (PxU32 i = 0; i < size; ++i) softBodies[i]->getSim()->updateBoundsInAABBMgr(); } else { for (PxU32 i = 0; i < size; ++i) softBodies[i]->getSim()->updateBounds(); } // update FEM-cloth world bound Sc::FEMClothCore* const* femCloths = mFEMCloths.getEntries(); size = mFEMCloths.size(); if (mUseGpuBp) { for (PxU32 i = 0; i < size; ++i) femCloths[i]->getSim()->updateBoundsInAABBMgr(); } else { for (PxU32 i = 0; i < size; ++i) femCloths[i]->getSim()->updateBounds(); } //upate the actor handle of particle system in AABB manager Sc::ParticleSystemCore* const* particleSystems = mParticleSystems.getEntries(); size = mParticleSystems.size(); if (mUseGpuBp) { for (PxU32 i = 0; i < size; ++i) particleSystems[i]->getSim()->updateBoundsInAABBMgr(); } else { for (PxU32 i = 0; i < size; ++i) particleSystems[i]->getSim()->updateBounds(); } //update hair system world bound Sc::HairSystemCore* const* hairSystems = mHairSystems.getEntries(); PxU32 nHairSystems = mHairSystems.size(); if (mUseGpuBp) { for (PxU32 i = 0; i < nHairSystems; ++i) hairSystems[i]->getSim()->updateBoundsInAABBMgr(); } else { for (PxU32 i = 0; i < nHairSystems; ++i) hairSystems[i]->getSim()->updateBounds(); } } void Sc::Scene::addSoftBody(SoftBodyCore& softBody) { SoftBodySim* sim = PX_NEW(SoftBodySim)(softBody, *this); if (sim && (sim->getLowLevelSoftBody() == NULL)) { PX_DELETE(sim); return; } mSoftBodies.insert(&softBody); mStats->gpuMemSizeSoftBodies += softBody.getGpuMemStat(); } void Sc::Scene::removeSoftBody(SoftBodyCore& softBody) { SoftBodySim* a = softBody.getSim(); PX_DELETE(a); mSoftBodies.erase(&softBody); mStats->gpuMemSizeSoftBodies -= softBody.getGpuMemStat(); } void Sc::Scene::addFEMCloth(FEMClothCore& femCloth) { FEMClothSim* sim = PX_NEW(FEMClothSim)(femCloth, *this); if (sim && (sim->getLowLevelFEMCloth() == NULL)) { PX_DELETE(sim); return; } mFEMCloths.insert(&femCloth); mStats->gpuMemSizeFEMCloths += femCloth.getGpuMemStat(); } void Sc::Scene::removeFEMCloth(FEMClothCore& femCloth) { FEMClothSim* a = femCloth.getSim(); PX_DELETE(a); mFEMCloths.erase(&femCloth); mStats->gpuMemSizeFEMCloths -= femCloth.getGpuMemStat(); } void Sc::Scene::addParticleSystem(ParticleSystemCore& particleSystem) { ParticleSystemSim* sim = PX_NEW(ParticleSystemSim)(particleSystem, *this); Dy::ParticleSystem* dyParticleSystem = sim->getLowLevelParticleSystem(); if (sim && (dyParticleSystem == NULL)) { PX_DELETE(sim); return; } mParticleSystems.insert(&particleSystem); mStats->gpuMemSizeParticles += particleSystem.getShapeCore().getGpuMemStat(); } void Sc::Scene::removeParticleSystem(ParticleSystemCore& particleSystem) { ParticleSystemSim* a = particleSystem.getSim(); PX_DELETE(a); mParticleSystems.erase(&particleSystem); mStats->gpuMemSizeParticles -= particleSystem.getShapeCore().getGpuMemStat(); } void Sc::Scene::addHairSystem(HairSystemCore& hairSystem) { HairSystemSim* sim = PX_NEW(HairSystemSim)(hairSystem, *this); if (sim && (sim->getLowLevelHairSystem() == NULL)) { PX_DELETE(sim); return; } mHairSystems.insert(&hairSystem); mStats->gpuMemSizeHairSystems += hairSystem.getShapeCore().getGpuMemStat(); } void Sc::Scene::removeHairSystem(HairSystemCore& hairSystem) { HairSystemSim* sim = hairSystem.getSim(); PX_DELETE(sim); mHairSystems.erase(&hairSystem); mStats->gpuMemSizeHairSystems -= hairSystem.getShapeCore().getGpuMemStat(); } Dy::SoftBody* Sc::Scene::createLLSoftBody(Sc::SoftBodySim* sim) { return mLLSoftBodyPool->construct(sim, sim->getCore().getCore()); } void Sc::Scene::destroyLLSoftBody(Dy::SoftBody& softBody) { mLLSoftBodyPool->destroy(&softBody); } Dy::FEMCloth* Sc::Scene::createLLFEMCloth(Sc::FEMClothSim* sim) { return mLLFEMClothPool->construct(sim, sim->getCore().getCore()); } void Sc::Scene::destroyLLFEMCloth(Dy::FEMCloth& femCloth) { mLLFEMClothPool->destroy(&femCloth); } Dy::ParticleSystem* Sc::Scene::createLLParticleSystem(Sc::ParticleSystemSim* sim) { return mLLParticleSystemPool->construct(sim->getCore().getShapeCore().getLLCore()); } void Sc::Scene::destroyLLParticleSystem(Dy::ParticleSystem& particleSystem) { return mLLParticleSystemPool->destroy(&particleSystem); } Dy::HairSystem* Sc::Scene::createLLHairSystem(Sc::HairSystemSim* sim) { return mLLHairSystemPool->construct(sim, sim->getCore().getShapeCore().getLLCore()); } void Sc::Scene::destroyLLHairSystem(Dy::HairSystem& hairSystem) { mLLHairSystemPool->destroy(&hairSystem); } void Sc::Scene::cleanUpSleepHairSystems() { HairSystemCore* const* hairSystemArray = mSleepHairSystems.getEntries(); PxU32 bodyCount = mSleepBodies.size(); IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); while (bodyCount--) { HairSystemSim* hairSystem = hairSystemArray[bodyCount]->getSim(); if (hairSystem->readInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_WAKEUP_NOTIFY))) { hairSystem->clearInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_IS_IN_WAKEUP_LIST)); mSleepHairSystems.erase(hairSystemArray[bodyCount]); } else if (islandSim.getNode(hairSystem->getNodeIndex()).isActive()) { //This hairSystem is still active in the island simulation, so the request to deactivate the actor by the application must have failed. Recover by undoing this mSleepHairSystems.erase(hairSystemArray[bodyCount]); hairSystem->internalWakeUp(); } } mSleepBodyListValid = true; } void Sc::Scene::cleanUpWokenHairSystems() { cleanUpSleepOrWokenHairSystems(mWokeHairSystems, BodySim::BF_SLEEP_NOTIFY, mWokeHairSystemListValid); } void Sc::Scene::cleanUpSleepOrWokenHairSystems(PxCoalescedHashSet<HairSystemCore*>& bodyList, PxU32 removeFlag, bool& validMarker) { HairSystemCore* const* hairSystemArray = bodyList.getEntries(); PxU32 bodyCount = bodyList.size(); while (bodyCount--) { HairSystemSim* hairSystem = hairSystemArray[bodyCount]->getSim(); if (hairSystem->readInternalFlag(static_cast<BodySim::InternalFlags>(removeFlag))) bodyList.erase(hairSystemArray[bodyCount]); } validMarker = true; } PX_INLINE void Sc::Scene::cleanUpSleepSoftBodies() { SoftBodyCore* const* bodyArray = mSleepSoftBodies.getEntries(); PxU32 bodyCount = mSleepBodies.size(); IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim(); while (bodyCount--) { SoftBodySim* body = bodyArray[bodyCount]->getSim(); if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_WAKEUP_NOTIFY))) { body->clearInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_IS_IN_WAKEUP_LIST)); mSleepSoftBodies.erase(bodyArray[bodyCount]); } else if (islandSim.getNode(body->getNodeIndex()).isActive()) { //This body is still active in the island simulation, so the request to deactivate the actor by the application must have failed. Recover by undoing this mSleepSoftBodies.erase(bodyArray[bodyCount]); body->internalWakeUp(); } } mSleepBodyListValid = true; } PX_INLINE void Sc::Scene::cleanUpWokenSoftBodies() { cleanUpSleepOrWokenSoftBodies(mWokeSoftBodies, BodySim::BF_SLEEP_NOTIFY, mWokeSoftBodyListValid); } PX_INLINE void Sc::Scene::cleanUpSleepOrWokenSoftBodies(PxCoalescedHashSet<SoftBodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker) { // With our current logic it can happen that a body is added to the sleep as well as the woken body list in the // same frame. // // Examples: // - Kinematic is created (added to woken list) but has not target (-> deactivation -> added to sleep list) // - Dynamic is created (added to woken list) but is forced to sleep by user (-> deactivation -> added to sleep list) // // This code traverses the sleep/woken body list and removes bodies which have been initially added to the given // list but do not belong to it anymore. SoftBodyCore* const* bodyArray = bodyList.getEntries(); PxU32 bodyCount = bodyList.size(); while (bodyCount--) { SoftBodySim* body = bodyArray[bodyCount]->getSim(); if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(removeFlag))) bodyList.erase(bodyArray[bodyCount]); } validMarker = true; } void Sc::Scene::addSoftBodySimControl(Sc::SoftBodyCore& core) { Sc::SoftBodySim* sim = core.getSim(); if (sim) { mSimulationController->addSoftBody(sim->getLowLevelSoftBody(), sim->getNodeIndex()); mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), sim->getPxActor()); } } void Sc::Scene::removeSoftBodySimControl(Sc::SoftBodyCore& core) { Sc::SoftBodySim* sim = core.getSim(); if (sim) { mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID()); mSimulationController->releaseSoftBody(sim->getLowLevelSoftBody()); } } void Sc::Scene::addFEMClothSimControl(Sc::FEMClothCore& core) { Sc::FEMClothSim* sim = core.getSim(); if (sim) { mSimulationController->addFEMCloth(sim->getLowLevelFEMCloth(), sim->getNodeIndex()); mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), sim->getPxActor(), true); } } void Sc::Scene::removeFEMClothSimControl(Sc::FEMClothCore& core) { Sc::FEMClothSim* sim = core.getSim(); if (sim) { mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), true); mSimulationController->releaseFEMCloth(sim->getLowLevelFEMCloth()); } } void Sc::Scene::addParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId) { mSimulationController->addParticleFilter(sim.getLowLevelSoftBody(), core->getSim()->getLowLevelParticleSystem(), particleId, userBufferId, tetId); } void Sc::Scene::removeParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId) { mSimulationController->removeParticleFilter(sim.getLowLevelSoftBody(), core->getSim()->getLowLevelParticleSystem(), particleId, userBufferId, tetId); } PxU32 Sc::Scene::addParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric) { PxNodeIndex nodeIndex = core->getSim()->getNodeIndex(); PxU32 handle = mSimulationController->addParticleAttachment(sim.getLowLevelSoftBody(), core->getSim()->getLowLevelParticleSystem(), particleId, userBufferId, tetId, barycentric, sim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eSOFT_BODY_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 handle) { PxNodeIndex nodeIndex = core->getSim()->getNodeIndex(); mSimulationController->removeParticleAttachment(sim.getLowLevelSoftBody(), handle); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addAttachment(const Sc::SoftBodySim& sbSim, const Sc::HairSystemSim& hairSim) { const PxPair<PxU32, PxU32> pair(sbSim.getNodeIndex().index(), hairSim.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sbSim.getNodeIndex(), hairSim.getNodeIndex(), NULL, IG::Edge::eHAIR_SYSTEM_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eHAIR_SYSTEM_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; } void Sc::Scene::removeAttachment(const Sc::SoftBodySim& sbSim, const Sc::HairSystemSim& hairSim) { const PxPair<PxU32, PxU32> pair(sbSim.getNodeIndex().index(), hairSim.getNodeIndex().index()); if(mParticleOrSoftBodyRigidInteractionMap.find(pair)) // find returns pointer to const so we cannot use it directly { ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; PX_ASSERT(interaction.mCount > 0); interaction.mCount--; if(interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } } void Sc::Scene::addRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 vertId) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->addRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, vertId); } void Sc::Scene::removeRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 vertId) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, vertId); } PxU32 Sc::Scene::addRigidAttachment(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { PxNodeIndex nodeIndex; PxsRigidBody* body = NULL; if (core) { nodeIndex = core->getSim()->getNodeIndex(); body = &core->getSim()->getLowLevelBody(); } PxU32 handle = mSimulationController->addRigidAttachment(sim.getLowLevelSoftBody(), sim.getNodeIndex(), body, nodeIndex, vertId, actorSpacePose, constraint, sim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eSOFT_BODY_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeRigidAttachment(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 handle) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeRigidAttachment(sim.getLowLevelSoftBody(), handle); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addTetRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 tetIdx) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->addTetRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, tetIdx); } void Sc::Scene::removeTetRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 tetIdx) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeTetRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, tetIdx); } PxU32 Sc::Scene::addTetRigidAttachment(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { PxNodeIndex nodeIndex; PxsRigidBody* body = NULL; if (core) { nodeIndex = core->getSim()->getNodeIndex(); body = &core->getSim()->getLowLevelBody(); } PxU32 handle = mSimulationController->addTetRigidAttachment(sim.getLowLevelSoftBody(), body, nodeIndex, tetIdx, barycentric, actorSpacePose, constraint, sim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eSOFT_BODY_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::addSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1) { Sc::SoftBodySim& bSim = *core.getSim(); mSimulationController->addSoftBodyFilter(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIdx0, tetIdx1); } void Sc::Scene::removeSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1) { Sc::SoftBodySim& bSim = *core.getSim(); mSimulationController->removeSoftBodyFilter(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIdx0, tetIdx1); } void Sc::Scene::addSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize) { Sc::SoftBodySim& bSim = *core.getSim(); mSimulationController->addSoftBodyFilters(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIndices0, tetIndices1, tetIndicesSize); } void Sc::Scene::removeSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize) { Sc::SoftBodySim& bSim = *core.getSim(); mSimulationController->removeSoftBodyFilters(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIndices0, tetIndices1, tetIndicesSize); } PxU32 Sc::Scene::addSoftBodyAttachment(SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& tetBarycentric0, Sc::SoftBodySim& sim, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset) { Sc::SoftBodySim& bSim = *core.getSim(); PxU32 handle = mSimulationController->addSoftBodyAttachment(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIdx0, tetIdx1, tetBarycentric0, tetBarycentric1, constraint, constraintOffset, sim.isActive() || bSim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), bSim.getNodeIndex(), NULL, IG::Edge::eSOFT_BODY_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeSoftBodyAttachment(SoftBodyCore& core, Sc::SoftBodySim& sim, PxU32 handle) { Sc::SoftBodySim& bSim = *core.getSim(); mSimulationController->removeSoftBodyAttachment(bSim.getLowLevelSoftBody(), handle); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx) { Sc::FEMClothSim& bSim = *core.getSim(); mSimulationController->addClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), triIdx,tetIdx); } void Sc::Scene::removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx) { Sc::FEMClothSim& bSim = *core.getSim(); mSimulationController->removeClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), triIdx, tetIdx); } void Sc::Scene::addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx) { Sc::FEMClothSim& bSim = *core.getSim(); mSimulationController->addVertClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), vertIdx, tetIdx); } void Sc::Scene::removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx) { Sc::FEMClothSim& bSim = *core.getSim(); mSimulationController->removeVertClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), vertIdx, tetIdx); } PxU32 Sc::Scene::addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, Sc::SoftBodySim& sim, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset) { Sc::FEMClothSim& bSim = *core.getSim(); PxU32 handle = mSimulationController->addClothAttachment(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), triIdx, triBarycentric, tetIdx, tetBarycentric, constraint, constraintOffset, sim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), bSim.getNodeIndex(), NULL, IG::Edge::eFEM_CLOTH_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeClothAttachment(Sc::FEMClothCore& core, Sc::SoftBodySim& sim, PxU32 handle) { PX_UNUSED(core); Sc::FEMClothSim& bSim = *core.getSim(); mSimulationController->removeClothAttachment(sim.getLowLevelSoftBody(), handle); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 vertId) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->addRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, vertId); } void Sc::Scene::removeRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 vertId) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, vertId); } PxU32 Sc::Scene::addRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { PxNodeIndex nodeIndex; PxsRigidBody* body = NULL; if (core) { nodeIndex = core->getSim()->getNodeIndex(); body = &core->getSim()->getLowLevelBody(); } PxU32 handle = mSimulationController->addRigidAttachment(sim.getLowLevelFEMCloth(), sim.getNodeIndex(), body, nodeIndex, vertId, actorSpacePose, constraint, sim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eFEM_CLOTH_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 handle) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeRigidAttachment(sim.getLowLevelFEMCloth(), handle); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addTriRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 triIdx) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->addTriRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, triIdx); } void Sc::Scene::removeTriRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 triIdx) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeTriRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, triIdx); } PxU32 Sc::Scene::addTriRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint) { PxNodeIndex nodeIndex; PxsRigidBody* body = NULL; if (core) { nodeIndex = core->getSim()->getNodeIndex(); body = &core->getSim()->getLowLevelBody(); } PxU32 handle = mSimulationController->addTriRigidAttachment(sim.getLowLevelFEMCloth(), body, nodeIndex, triIdx, barycentric, actorSpacePose, constraint, sim.isActive()); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eFEM_CLOTH_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeTriRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 handle) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } mSimulationController->removeTriRigidAttachment(sim.getLowLevelFEMCloth(), handle); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addClothFilter(FEMClothCore& core0, PxU32 triIdx0, Sc::FEMClothSim& sim1, PxU32 triIdx1) { Sc::FEMClothSim& sim0 = *core0.getSim(); mSimulationController->addClothFilter(sim0.getLowLevelFEMCloth(), sim1.getLowLevelFEMCloth(), triIdx0, triIdx1); } void Sc::Scene::removeClothFilter(FEMClothCore& core, PxU32 triIdx0, FEMClothSim& sim1, PxU32 triIdx1) { Sc::FEMClothSim& sim0 = *core.getSim(); mSimulationController->removeClothFilter(sim0.getLowLevelFEMCloth(), sim1.getLowLevelFEMCloth(), triIdx0, triIdx1); } PxU32 Sc::Scene::addTriClothAttachment(FEMClothCore& core, PxU32 triIdx0, const PxVec4& barycentric0, Sc::FEMClothSim& sim1, PxU32 triIdx1, const PxVec4& barycentric1) { Sc::FEMClothSim& sim0 = *core.getSim(); PxU32 handle = mSimulationController->addTriClothAttachment(sim0.getLowLevelFEMCloth(), sim1.getLowLevelFEMCloth(), triIdx0, triIdx1, barycentric0, barycentric1, sim1.isActive() || sim0.isActive()); //return handle; PxPair<PxU32, PxU32> pair(sim0.getNodeIndex().index(), sim1.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim0.getNodeIndex(), sim1.getNodeIndex(), NULL, IG::Edge::eFEM_CLOTH_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; return handle; } void Sc::Scene::removeTriClothAttachment(FEMClothCore& core, FEMClothSim& sim1, PxU32 handle) { Sc::FEMClothSim& sim0 = *core.getSim(); mSimulationController->removeTriClothAttachment(sim0.getLowLevelFEMCloth(), handle); PxPair<PxU32, PxU32> pair(sim0.getNodeIndex().index(), sim1.getNodeIndex().index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addParticleSystemSimControl(Sc::ParticleSystemCore& core) { Sc::ParticleSystemSim* sim = core.getSim(); if (sim) { mSimulationController->addParticleSystem(sim->getLowLevelParticleSystem(), sim->getNodeIndex(), core.getSolverType()); mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getCore().getShapeCore().getCore(), sim->getLowLevelParticleSystem()->getElementId(), sim->getPxActor()); } } void Sc::Scene::removeParticleSystemSimControl(Sc::ParticleSystemCore& core) { Sc::ParticleSystemSim* sim = core.getSim(); if (sim) { mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getCore().getShapeCore().getCore(), sim->getShapeSim().getElementID()); mSimulationController->releaseParticleSystem(sim->getLowLevelParticleSystem(), core.getSolverType()); } } void Sc::Scene::addRigidAttachment(Sc::BodyCore* core, Sc::ParticleSystemSim& sim) { PxNodeIndex nodeIndex; if (core) { nodeIndex = core->getSim()->getNodeIndex(); } PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::ePARTICLE_SYSTEM_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::ePARTICLE_SYSTEM_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; } void Sc::Scene::removeRigidAttachment(Sc::BodyCore* core, Sc::ParticleSystemSim& sim) { PxNodeIndex nodeIndex; if (core) nodeIndex = core->getSim()->getNodeIndex(); PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; interaction.mCount--; if (interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } void Sc::Scene::addHairSystemSimControl(Sc::HairSystemCore& core) { Sc::HairSystemSim* sim = core.getSim(); if (sim) { mSimulationController->addHairSystem(sim->getLowLevelHairSystem(), sim->getNodeIndex()); mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), sim->getPxActor()); } } void Sc::Scene::removeHairSystemSimControl(Sc::HairSystemCore& core) { Sc::HairSystemSim* sim = core.getSim(); if (sim) { mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID()); mSimulationController->releaseHairSystem(sim->getLowLevelHairSystem()); } } void Sc::Scene::addAttachment(const Sc::BodySim& bodySim, const Sc::HairSystemSim& hairSim) { const PxNodeIndex nodeIndex = bodySim.getNodeIndex(); const PxPair<PxU32, PxU32> pair(hairSim.getNodeIndex().index(), nodeIndex.index()); ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; if (interaction.mCount == 0) { IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, hairSim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eHAIR_SYSTEM_CONTACT); mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eHAIR_SYSTEM_CONTACT); interaction.mIndex = edgeIdx; } interaction.mCount++; } void Sc::Scene::removeAttachment(const Sc::BodySim& bodySim, const Sc::HairSystemSim& hairSim) { const PxNodeIndex nodeIndex = bodySim.getNodeIndex(); const PxPair<PxU32, PxU32> pair(hairSim.getNodeIndex().index(), nodeIndex.index()); if(mParticleOrSoftBodyRigidInteractionMap.find(pair)) // find returns pointer to const so we cannot use it directly { ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair]; PX_ASSERT(interaction.mCount > 0); interaction.mCount--; if(interaction.mCount == 0) { mSimpleIslandManager->removeConnection(interaction.mIndex); mParticleOrSoftBodyRigidInteractionMap.erase(pair); } } } PxActor** Sc::Scene::getActiveSoftBodyActors(PxU32& nbActorsOut) { nbActorsOut = mActiveSoftBodyActors.size(); if (!nbActorsOut) return NULL; return mActiveSoftBodyActors.begin(); } void Sc::Scene::setActiveSoftBodyActors(PxActor** actors, PxU32 nbActors) { mActiveSoftBodyActors.forceSize_Unsafe(0); mActiveSoftBodyActors.resize(nbActors); PxMemCopy(mActiveSoftBodyActors.begin(), actors, sizeof(PxActor*) * nbActors); } //PxActor** Sc::Scene::getActiveFEMClothActors(PxU32& nbActorsOut) //{ // nbActorsOut = mActiveFEMClothActors.size(); // // if (!nbActorsOut) // return NULL; // // return mActiveFEMClothActors.begin(); //} // //void Sc::Scene::setActiveFEMClothActors(PxActor** actors, PxU32 nbActors) //{ // mActiveFEMClothActors.forceSize_Unsafe(0); // mActiveFEMClothActors.resize(nbActors); // PxMemCopy(mActiveFEMClothActors.begin(), actors, sizeof(PxActor*) * nbActors); //} #endif //PX_SUPPORT_GPU_PHYSX
148,828
C++
33.708256
238
0.738927
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBodySim.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef SC_BODYSIM_H #define SC_BODYSIM_H #include "foundation/PxUtilities.h" #include "foundation/PxIntrinsics.h" #include "ScRigidSim.h" #include "PxvDynamics.h" #include "ScBodyCore.h" #include "ScSimStateData.h" #include "PxRigidDynamic.h" #include "PxsRigidBody.h" namespace physx { namespace Bp { class BoundsArray; } class PxsTransformCache; namespace Sc { class Scene; class ArticulationSim; #if PX_VC #pragma warning(push) #pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value. #endif class BodySim : public RigidSim { public: BodySim(Scene&, BodyCore&, bool); virtual ~BodySim(); void switchToKinematic(); void switchToDynamic(); PX_FORCE_INLINE const SimStateData* getSimStateData(bool isKinematic) const { return (mSimStateData && (checkSimStateKinematicStatus(isKinematic)) ? mSimStateData : NULL); } PX_FORCE_INLINE SimStateData* getSimStateData(bool isKinematic) { return (mSimStateData && (checkSimStateKinematicStatus(isKinematic)) ? mSimStateData : NULL); } PX_FORCE_INLINE SimStateData* getSimStateData_Unchecked() const { return mSimStateData; } PX_FORCE_INLINE bool checkSimStateKinematicStatus(bool isKinematic) const { PX_ASSERT(mSimStateData); return mSimStateData->isKine() == isKinematic; } void setKinematicTarget(const PxTransform& p); void addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc); void setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc); void clearSpatialAcceleration(bool force, bool torque); void addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta); void clearSpatialVelocity(bool force, bool torque); void updateCached(PxBitMapPinned* shapeChangedMap); void updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray); void updateContactDistance(PxReal* contactDistance, PxReal dt, const Bp::BoundsArray& boundsArray); // hooks for actions in body core when it's attached to a sim object. Generally // we get called after the attribute changed. virtual void postActorFlagChange(PxU32 oldFlags, PxU32 newFlags) PX_OVERRIDE; void postBody2WorldChange(); void postSetWakeCounter(PxReal t, bool forceWakeUp); void postPosePreviewChange(PxU32 posePreviewFlag); // called when PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW changes PX_FORCE_INLINE const PxTransform& getBody2World() const { return getBodyCore().getCore().body2World; } PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return getBodyCore().getCore().getBody2Actor(); } PX_FORCE_INLINE const PxsRigidBody& getLowLevelBody() const { return mLLBody; } PX_FORCE_INLINE PxsRigidBody& getLowLevelBody() { return mLLBody; } void setActive(bool active, bool asPartOfCreation=false); void wakeUp(); // note: for user API call purposes only, i.e., use from BodyCore. For simulation internal purposes there is internalWakeUp(). void putToSleep(); void disableCompound(); static PxU32 getRigidBodyOffset() { return PxU32(PX_OFFSET_OF_RT(BodySim, mLLBody));} void activate(); void deactivate(); // Kinematics PX_FORCE_INLINE bool isKinematic() const { return getBodyCore().getFlags() & PxRigidBodyFlag::eKINEMATIC; } PX_FORCE_INLINE bool isArticulationLink() const { return getActorType() == PxActorType::eARTICULATION_LINK; } PX_FORCE_INLINE bool hasForcedKinematicNotif() const { return getBodyCore().getFlags() & (PxRigidBodyFlag::eFORCE_KINE_KINE_NOTIFICATIONS|PxRigidBodyFlag::eFORCE_STATIC_KINE_NOTIFICATIONS); } void calculateKinematicVelocity(PxReal oneOverDt); void updateKinematicPose(); bool deactivateKinematic(); // Sleeping virtual void internalWakeUp(PxReal wakeCounterValue) PX_OVERRIDE; // PT: TODO: does it need to be virtual? void internalWakeUpArticulationLink(PxReal wakeCounterValue); // called by ArticulationSim to wake up this link PxReal updateWakeCounter(PxReal dt, PxReal energyThreshold, const Cm::SpatialVector& motionVelocity); void notifyReadyForSleeping(); // inform the sleep island generation system that the body is ready for sleeping void notifyNotReadyForSleeping(); // inform the sleep island generation system that the body is not ready for sleeping PX_FORCE_INLINE bool checkSleepReadinessBesidesWakeCounter(); // for API triggered changes to test sleep readiness // PT: TODO: this is only used for the rigid bodies' sleep check, the implementations in derived classes look useless virtual void registerCountedInteraction() PX_OVERRIDE { mLLBody.getCore().numCountedInteractions++; PX_ASSERT(mLLBody.getCore().numCountedInteractions); } virtual void unregisterCountedInteraction() PX_OVERRIDE { PX_ASSERT(mLLBody.getCore().numCountedInteractions); mLLBody.getCore().numCountedInteractions--; } // PT: TODO: this is only used for the rigid bodies' sleep check called from the articulation sim code virtual PxU32 getNumCountedInteractions() const PX_OVERRIDE { return mLLBody.getCore().numCountedInteractions; } PX_FORCE_INLINE PxIntBool isFrozen() const { return PxIntBool(mLLBody.mInternalFlags & PxsRigidBody::eFROZEN); } // External velocity changes - returns true if any forces were applied to this body bool updateForces(PxReal dt, PxsRigidBody** updatedBodySims, PxU32* updatedBodyNodeIndices, PxU32& index, Cm::SpatialVector* acceleration); PX_FORCE_INLINE bool readVelocityModFlag(VelocityModFlags f) { return (mVelModState & f) != 0; } // Miscellaneous PX_FORCE_INLINE bool notInScene() const { return mActiveListIndex == SC_NOT_IN_SCENE_INDEX; } PX_FORCE_INLINE PxU32 getNbShapes() const { return mShapes.getCount(); } PX_FORCE_INLINE PxU32 getFlagsFast() const { return getBodyCore().getFlags(); } PX_FORCE_INLINE BodyCore& getBodyCore() const { return static_cast<BodyCore&>(getRigidCore()); } PX_FORCE_INLINE ArticulationSim* getArticulation() const { return mArticulation; } void setArticulation(ArticulationSim* a, PxReal wakeCounter, bool asleep, PxU32 bodyIndex); PX_FORCE_INLINE void onConstraintAttach() { raiseInternalFlag(BF_HAS_CONSTRAINTS); registerCountedInteraction(); } void onConstraintDetach(); PX_FORCE_INLINE void onOriginShift(const PxVec3& shift, const bool isKinematic) { PX_ASSERT(!mSimStateData || checkSimStateKinematicStatus(isKinematic)); mLLBody.mLastTransform.p -= shift; if (mSimStateData && isKinematic && mSimStateData->getKinematicData()->targetValid) mSimStateData->getKinematicData()->targetPose.p -= shift; } PX_FORCE_INLINE bool usingSqKinematicTarget() const { const PxU32 ktFlags(PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES | PxRigidBodyFlag::eKINEMATIC); return (getFlagsFast()&ktFlags) == ktFlags; } void createSqBounds(); void destroySqBounds(); void freezeTransforms(PxBitMapPinned* shapeChangedMap); void addToSpeculativeCCDMap(); void removeFromSpeculativeCCDMap(); private: // Base body PxsRigidBody mLLBody; // External velocity changes // VelocityMod data allocated on the fly when the user applies velocity changes // which need to be accumulated. // VelMod dirty flags stored in BodySim so we can save ourselves the expense of looking at // the separate velmod data if no forces have been set. //PxU16 mInternalFlags; SimStateData* mSimStateData; PxU8 mVelModState; // Articulation ArticulationSim* mArticulation; // NULL if not in an articulation // Joints & joint groups bool setupSimStateData(bool isKinematic); void tearDownSimStateData(bool isKinematic); void raiseVelocityModFlagAndNotify(VelocityModFlags flag); PX_FORCE_INLINE void notifyAddSpatialAcceleration() { raiseVelocityModFlagAndNotify(VMF_ACC_DIRTY); } PX_FORCE_INLINE void notifyClearSpatialAcceleration() { raiseVelocityModFlagAndNotify(VMF_ACC_DIRTY); } PX_FORCE_INLINE void notifyAddSpatialVelocity() { raiseVelocityModFlagAndNotify(VMF_VEL_DIRTY); } PX_FORCE_INLINE void notifyClearSpatialVelocity() { raiseVelocityModFlagAndNotify(VMF_VEL_DIRTY); } PX_FORCE_INLINE void initKinematicStateBase(BodyCore&, bool asPartOfCreation); void notifyWakeUp(); // inform the sleep island generation system that the object got woken up void notifyPutToSleep(); // inform the sleep island generation system that the object was put to sleep void internalWakeUpBase(PxReal wakeCounterValue); PX_FORCE_INLINE void raiseVelocityModFlag(VelocityModFlags f) { mVelModState |= f; } PX_FORCE_INLINE void clearVelocityModFlag(VelocityModFlags f) { mVelModState &= ~f; } PX_FORCE_INLINE void setForcesToDefaults(bool enableGravity); }; #if PX_VC #pragma warning(pop) #endif } // namespace Sc PX_FORCE_INLINE void Sc::BodySim::setForcesToDefaults(bool enableGravity) { if (!(mLLBody.mCore->mFlags & PxRigidBodyFlag::eRETAIN_ACCELERATIONS)) { SimStateData* simStateData = getSimStateData(false); if(simStateData) { VelocityMod* velmod = simStateData->getVelocityModData(); velmod->clear(); } if (enableGravity) mVelModState = VMF_GRAVITY_DIRTY; // We want to keep the gravity flag to make sure the acceleration gets changed to gravity-only // in the next step (unless the application adds new forces of course) else mVelModState = 0; } else { SimStateData* simStateData = getSimStateData(false); if (simStateData) { VelocityMod* velmod = simStateData->getVelocityModData(); velmod->clearPerStep(); } mVelModState &= (~(VMF_VEL_DIRTY)); } } PX_FORCE_INLINE bool Sc::BodySim::checkSleepReadinessBesidesWakeCounter() { const BodyCore& bodyCore = getBodyCore(); const SimStateData* simStateData = getSimStateData(false); const VelocityMod* velmod = simStateData ? simStateData->getVelocityModData() : NULL; bool readyForSleep = bodyCore.getLinearVelocity().isZero() && bodyCore.getAngularVelocity().isZero(); if (readVelocityModFlag(VMF_ACC_DIRTY)) { readyForSleep = readyForSleep && (!velmod || velmod->getLinearVelModPerSec().isZero()); readyForSleep = readyForSleep && (!velmod || velmod->getAngularVelModPerSec().isZero()); } if (readVelocityModFlag(VMF_VEL_DIRTY)) { readyForSleep = readyForSleep && (!velmod || velmod->getLinearVelModPerStep().isZero()); readyForSleep = readyForSleep && (!velmod || velmod->getAngularVelModPerStep().isZero()); } return readyForSleep; } } #endif
12,922
C
45.822464
176
0.715292
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintBreakage.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScScene.h" #include "ScConstraintSim.h" #include "ScConstraintCore.h" #include "ScConstraintInteraction.h" #include "common/PxProfileZone.h" using namespace physx; // PT: the breakable constraints are added to / removed from mActiveBreakableConstraints: void Sc::Scene::addActiveBreakableConstraint(Sc::ConstraintSim* c, Sc::ConstraintInteraction* ci) { PX_ASSERT(ci && ci->readInteractionFlag(InteractionFlag::eIS_ACTIVE)); PX_UNUSED(ci); PX_ASSERT(!mActiveBreakableConstraints.contains(c)); PX_ASSERT(!c->isBroken()); mActiveBreakableConstraints.insert(c); c->setFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED); } void Sc::Scene::removeActiveBreakableConstraint(Sc::ConstraintSim* c) { const bool exists = mActiveBreakableConstraints.erase(c); PX_ASSERT(exists); PX_UNUSED(exists); c->clearFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED); } // PT: then at runtime we parse mActiveBreakableConstraints, check for max force exceeded, // and add broken constraints to mBrokenConstraints: void Sc::Scene::checkConstraintBreakage() { PX_PROFILE_ZONE("Sim.checkConstraintBreakage", mContextId); PxU32 count = mActiveBreakableConstraints.size(); if(!count) return; PxPinnedArray<Dy::ConstraintWriteback>& pool = mDynamicsContext->getConstraintWriteBackPool(); ConstraintSim* const* constraints = mActiveBreakableConstraints.getEntries(); while(count--) { ConstraintSim* sim = constraints[count]; // start from the back because broken constraints get removed from the list PX_ASSERT(sim->readFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED)); const Dy::ConstraintWriteback& solverOutput = pool[sim->getLowLevelConstraint().index]; if(solverOutput.broken) { sim->setFlag(ConstraintSim::eBROKEN); ConstraintCore& core = sim->getCore(); if(mSimulationEventCallback) { PX_ASSERT(mBrokenConstraints.find(&core) == mBrokenConstraints.end()); mBrokenConstraints.pushBack(&core); } core.breakApart(); ConstraintInteraction* interaction = const_cast<ConstraintInteraction*>(sim->getInteraction()); interaction->destroy(); // PT: this will call removeFromActiveBreakableList above // update related SIPs { ActorSim& a0 = interaction->getActorSim0(); ActorSim& a1 = interaction->getActorSim1(); ActorSim& actor = (a0.getActorInteractionCount() < a1.getActorInteractionCount()) ? a0 : a1; actor.setActorsInteractionsDirty(InteractionDirtyFlag::eFILTER_STATE, NULL, InteractionFlag::eRB_ELEMENT); // because broken constraints can re-enable contact response between the two bodies } PX_ASSERT(!sim->readFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED)); } } } // PT: finally mBrokenConstraints is parsed and callbacks issued: void Sc::Scene::fireBrokenConstraintCallbacks() { if(!mSimulationEventCallback) return; const PxU32 count = mBrokenConstraints.size(); for(PxU32 i=0;i<count;i++) { Sc::ConstraintCore* c = mBrokenConstraints[i]; PX_ASSERT(c->getSim()); PxU32 typeID = 0xffffffff; void* externalRef = c->getPxConnector()->getExternalReference(typeID); PX_CHECK_MSG(typeID != 0xffffffff, "onConstraintBreak: Invalid constraint type ID."); PxConstraintInfo constraintInfo(c->getPxConstraint(), externalRef, typeID); mSimulationEventCallback->onConstraintBreak(&constraintInfo, 1); } }
5,014
C++
37.282442
118
0.759673